Programs & Examples On #Ftp4j

The ftp4j library implements a Java full-features FTP client. With ftp4j embedded in your application you can: transfer files (upload and download), browse the remote FTP site (directory listing included), create, delete, rename and move remote directories and files. Source:

How set the android:gravity to TextView from Java side in Android

We can set layout gravity on any view like below way-

myView = findViewById(;

This is equilent to below xml code


How to check a string against null in java?

Sure it works. You're missing out a vital part of the code. You just need to do like this:

boolean isNull = false;
try {
} catch (NullPointerException npe) {
    isNull = true;


Gradle proxy configuration

An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.

The following sets the username and password if provided or just adds the host and port if no username and password is set.

task setHttpProxyFromEnv {
    def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
    for (e in System.getenv()) {
        def key = e.key.toUpperCase()
        if (key in map) {
            def base = map[key]
            //Get proxyHost,port, username, and password from http system properties 
            // in the format http://username:password@proxyhost:proxyport
            def (val1,val2) = e.value.tokenize( '@' )
            def (val3,val4) = val1.tokenize( '//' )
            def(userName, password) = val4.tokenize(':')
            def url = e.value.toURL()
            //println " - systemProp.${base}.proxy=${}:${url.port}"
            System.setProperty("${base}.proxyPort", url.port.toString())
            System.setProperty("${base}.proxyUser", userName.toString())
            System.setProperty("${base}.proxyPassword", password.toString())

Search input with an icon Bootstrap 4

Here's a fairly simple way to achieve it by enclosing both the magnifying glass icon and the input field inside a div with relative positioning.

Absolute positioning is applied to the icon, which takes it out of the normal document layout flow. The icon is then positioned inside the input. Left padding is applied to the input so that the user's input appears to the right of the icon.

Note that this example places the magnifying glass icon on the left instead of the right. This is recommended when using <input type="search"> as Chrome adds an X button in the right side of the searchbox. If we placed the icon there it would overlay the X button and look fugly.

Here is the needed Bootstrap markup.

<div class="position-relative">
    <i class="fa fa-search position-absolute"></i>
    <input class="form-control" type="search">

...and a couple CSS classes for the things which I couldn't do with Bootstrap classes:

i {
    font-size: 1rem;
    color: #333;
    top: .75rem;
    left: .75rem

input {
    padding-left: 2.5rem;

You may have to fiddle with the values for top, left, and padding-left.

Converting string to date in mongodb

In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);; 

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):



The element css needs to have the following declaration:


Strange, but that's what it took to get things working again!

How to for each the hashmap?

Streams Java 8

Along with forEach method that accepts a lambda expression we have also got stream APIs, in Java 8.

Iterate over entries (Using forEach and Streams):

sample.forEach((k,v) -> System.out.println(k + "=" + v)); 
sample.entrySet().stream().forEachOrdered((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + "=" + currentValue);
sample.entrySet().parallelStream().forEach((entry) -> {
            Object currentKey = entry.getKey();
            Object currentValue = entry.getValue();
            System.out.println(currentKey + "=" + currentValue);

The advantage with streams is they can be parallelized easily and can be useful when we have multiple CPUs at disposal. We simply need to use parallelStream() in place of stream() above. With parallel streams it makes more sense to use forEach as forEachOrdered would make no difference in performance. If we want to iterate over keys we can use sample.keySet() and for values sample.values().

Why forEachOrdered and not forEach with streams ?

Streams also provide forEach method but the behaviour of forEach is explicitly nondeterministic where as the forEachOrdered performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach does not guarantee that the order would be kept. Also check this for more.

Get user's non-truncated Active Directory groups from command line

A little stale post, but I figured what the heck. Does "whoami" meet your needs?

I just found out about it today (from the same Google search that brought me here, in fact). Windows has had a whoami tool since XP (part of an add on toolkit) and has been built-in since Vista.

whoami /groups

Lists all the AD groups for the currently logged-on user. I believe it does require you to be logged on AS that user, though, so this won't help if your use case requires the ability to run the command to look at another user.

Group names only:

whoami /groups /fo list |findstr /c:"Group Name:"

Can't bind to 'routerLink' since it isn't a known property

You need to add RouterModule to imports of every @NgModule() where components use any component or directive from (in this case routerLink and <router-outlet>.

declarations: [] is to make components, directives, pipes, known inside the current module.

exports: [] is to make components, directives, pipes, available to importing modules. What is added to declarations only is private to the module. exports makes them public.

See also

How to properly assert that an exception gets raised in pytest?

There are two ways to handle these kind of cases in pytest:

  • Using pytest.raises function

  • Using pytest.mark.xfail decorator

As the documentation says:

Using pytest.raises is likely to be better for cases where you are testing exceptions your own code is deliberately raising, whereas using @pytest.mark.xfail with a check function is probably better for something like documenting unfixed bugs (where the test describes what “should” happen) or bugs in dependencies.

Usage of pytest.raises:

def whatever():
    return 9/0
def test_whatever():
    with pytest.raises(ZeroDivisionError):

Usage of pytest.mark.xfail:

def test_whatever():

Output of pytest.raises:

============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- 
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item PASSED

======================== 1 passed in 0.01 seconds =============================

Output of pytest.xfail marker:

============================= test session starts ============================
platform linux2 -- Python 2.7.10, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 -- 
cachedir: .cache
rootdir: /home/user, inifile:
collected 1 item xfail

======================== 1 xfailed in 0.03 seconds=============================

equivalent of vbCrLf in c#

I typically abbreviate so that I can use several places in my code. Near the top, do something like this:

 string nl = System.Environment.NewLine;

Then I can just use "nl" instead of the full qualification everywhere when constructing strings.

Can't access to HttpContext.Current

Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.

The answer from Andrei means that you can use HttpContext just as you would use System.Web.HttpContext.Current. For example, if you want to do this:


you should instead do this:


Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.

Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.

Removing leading and trailing spaces from a string

void TrimWhitespaces(std::wstring& str)
    if (str.empty())

    const std::wstring& whitespace = L" \t";
    std::wstring::size_type strBegin = str.find_first_not_of(whitespace);
    std::wstring::size_type strEnd = str.find_last_not_of(whitespace);

    if (strBegin != std::wstring::npos || strEnd != std::wstring::npos)
        strBegin == std::wstring::npos ? 0 : strBegin;
        strEnd == std::wstring::npos ? str.size() : 0;

        const auto strRange = strEnd - strBegin + 1;
        str.substr(strBegin, strRange).swap(str);
    else if (str[0] == ' ' || str[0] == '\t')   // handles non-empty spaces-only or tabs-only
        str = L"";

void TrimWhitespacesTest()
    std::wstring EmptyStr = L"";
    std::wstring SpacesOnlyStr = L"    ";
    std::wstring TabsOnlyStr = L"           ";
    std::wstring RightSpacesStr = L"12345     ";
    std::wstring LeftSpacesStr = L"     12345";
    std::wstring NoSpacesStr = L"12345";


    assert(EmptyStr == L"");
    assert(SpacesOnlyStr == L"");
    assert(TabsOnlyStr == L"");
    assert(RightSpacesStr == L"12345");
    assert(LeftSpacesStr == L"12345");
    assert(NoSpacesStr == L"12345");

cmd line rename file with date and time

ls | xargs -I % mv % %_`date +%d%b%Y`

One line is enough. ls all files/dirs under current dir and append date to each file.

PHP Function with Optional Parameters

Just set Null to ignore parameters that you don't want to use and then set the parameter needed according to the position.

 function myFunc($p1,$p2,$p3=Null,$p4=Null,$p5=Null,$p6=Null,$p7=Null,$p8=Null){
    for ($i=1; $i<9; $i++){
        $varName = "p$i";
        if (isset($$varName)){
            echo $varName." = ".$$varName."<br>\n";

myFunc( "1", "2", Null, Null, Null, Null, Null, "eight" );

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

Visual Studio Expand/Collapse keyboard shortcuts

Visual Studio 2015:

Tools > Options > Settings > Environment > Keyboard


Edit.CollapsetoDefinitions: CTRL + M + O

Edit.CollapseCurrentRegion: CTRL + M +CTRL + S

Edit.ExpandAllOutlining: CTRL + M + CTRL + X

Edit.ExpandCurrentRegion: CTRL + M + CTRL + E

I like to set and use IntelliJ's shortcuts:

Edit.CollapsetoDefinitions: CTRL + SHIFT + NUM-

Edit.CollapseCurrentRegion: CTRL + NUM-

Edit.ExpandAllOutlining: CTRL + SHIFT + NUM+

Edit.ExpandCurrentRegion: CTRL + NUM+

When should I create a destructor?

When you have unmanaged resources and you need to make sure they will be cleaned up when your object goes away. Good example would be COM objects or File Handlers.

How to get a context in a recycler view adapter

First globally declare

Context mContext;

pass context with the constructor, by modifying it.

public FeedAdapter(List<Post> myDataset, Context context) {
    mDataset = myDataset;
    this.mContext = context;

then use the mContext whereever you need it

How to stick text to the bottom of the page?

Try this

 <style type ="text/css" >
       position: fixed;     
       text-align: center;    
       bottom: 0px; 
       width: 100%;
    <div class="footer">All Rights Reserved</div>

Getting a link to go to a specific section on another page

I tried the above answer - using page.html#ID_name it gave me a 404 page doesn't exist error.

Then instead of using .html, I simply put a slash / before the # and that worked fine. So my example on the sending page between the link tags looks like:

<a href= "http://my">El Chorro</a>

Just use / instead of .html.

"android.view.WindowManager$BadTokenException: Unable to add window" on

android.view.WindowManager$BadTokenException: Unable to add window"

Problem :

This exception occurs when the app is trying to notify the user from the background thread (AsyncTask) by opening a Dialog.

If you are trying to modify the UI from background thread (usually from onPostExecute() of AsyncTask) and if the activity enters finishing stage i.e.) explicitly calling finish(), user pressing home or back button or activity clean up made by Android then you get this error.

Reason :

The reason for this exception is that, as the exception message says, the activity has finished but you are trying to display a dialog with a context of the finished activity. Since there is no window for the dialog to display the android runtime throws this exception.


Use isFinishing() method which is called by Android to check whether this activity is in the process of finishing: be it explicit finish() call or activity clean up made by Android. By using this method it is very easy to avoid opening dialog from background thread when activity is finishing.

Also maintain a weak reference for the activity (and not a strong reference so that activity can be destroyed once not needed) and check if the activity is not finishing before performing any UI using this activity reference (i.e. showing a dialog).


private class chkSubscription extends AsyncTask<String, Void, String>{

  private final WeakReference<login> loginActivityWeakRef;

  public chkSubscription (login loginActivity) {
    this.loginActivityWeakRef= new WeakReference<login >(loginActivity)

  protected String doInBackground(String... params) {
    //web service call

  protected void onPostExecute(String result) {
    if(page.contains("error")) //when not subscribed
      if (loginActivityWeakRef.get() != null && !loginActivityWeakRef.get().isFinishing()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(login.this);

        builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog, int whichButton){

Update :

Window Tokens:

As its name implies, a window token is a special type of Binder token that the window manager uses to uniquely identify a window in the system. Window tokens are important for security because they make it impossible for malicious applications to draw on top of the windows of other applications. The window manager protects against this by requiring applications to pass their application's window token as part of each request to add or remove a window. If the tokens don't match, the window manager rejects the request and throws a BadTokenException. Without window tokens, this necessary identification step wouldn't be possible and the window manager wouldn't be able to protect itself from malicious applications.

 A real-world scenario:

When an application starts up for the first time, the ActivityManagerService creates a special kind of window token called an application window token, which uniquely identifies the application's top-level container window. The activity manager gives this token to both the application and the window manager, and the application sends the token to the window manager each time it wants to add a new window to the screen. This ensures secure interaction between the application and the window manager (by making it impossible to add windows on top of other applications), and also makes it easy for the activity manager to make direct requests to the window manager.

Difference between two dates in MySQL

Why not just

Select Sum(Date1 - Date2) from table

date1 and date2 are datetime

Angularjs - Pass argument to directive

Insert the var msg in the click event with scope.$apply to make the changes to the confirm, based on your controller changes to the variables shown in ng-confirm-click therein.

<button type="button" class="btn" ng-confirm-click="You are about to send {{quantity}} of {{thing}} selected? Confirm with OK" confirmed-click="youraction(id)" aria-describedby="passwordHelpBlock">Send</button>

app.directive('ngConfirmClick', [
  function() {
    return {
      link: function(scope, element, attr) {
        var clickAction = attr.confirmedClick;
        element.on('click', function(event) {
          var msg = attr.ngConfirmClick || "Are you sure? Click OK to confirm.";
          if (window.confirm(msg)) {

OR, AND Operator

If what interests you is bitwise operations look here for a brief tutorial : .bitwise operation perform the same operations like the ones exemplified above they just work with binary representation (the operation applies to each individual bit of the value)

If you want logical operation answers are already given.

How can I build for release/distribution on the Xcode 4?

That part is now located under Schemes. If you edit your schemes you will see that you can set the debug/release/adhoc/distribution build config for each scheme.

Java read file and store text in an array

Just read the whole file into a StringBuilder, then split the String by dot following a space. You will get a String array.

Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt"));

StringBuilder sb = new Stringbuilder();
while(inFile1.hasNext()) {

String[] yourArray = sb.toString().split(", ");

How do I point Crystal Reports at a new database

Use the Database menu and "Set Datasource Location" menu option to change the name or location of each table in a report.

This works for changing the location of a database, changing to a new database, and changing the location or name of an individual table being used in your report.

To change the datasource connection, go the Database menu and click Set Datasource Location.

  1. Change the Datasource Connection:
    1. From the Current Data Source list (the top box), click once on the datasource connection that you want to change.
    2. In the Replace with list (the bottom box), click once on the new datasource connection.
    3. Click Update.
  2. Change Individual Tables:
    1. From the Current Data Source list (the top box), expand the datasource connection that you want to change.
    2. Find the table for which you want to update the location or name.
    3. In the Replace with list (the bottom box), expand the new datasource connection.
    4. Find the new table you want to update to point to.
    5. Click Update.
    6. Note that if the table name has changed, the old table name will still appear in the Field Explorer even though it is now using the new table. (You can confirm this be looking at the Table Name of the table's properties in Current Data Source in Set Datasource Location. Screenshot It's possible to rename the old table name to the new name from the context menu in Database Expert -> Selected Tables.
  3. Change Subreports:
    1. Repeat each of the above steps for any subreports you might have embedded in your report.
    2. Close the Set Datasource Location window.
  4. Any Commands or SQL Expressions:
    1. Go to the Database menu and click Database Expert.
    2. If the report designer used "Add Command" to write custom SQL it will be shown in the Selected Tables box on the right.
    3. Right click that command and choose "Edit Command".
    4. Check if that SQL is specifying a specific database. If so you might need to change it.
    5. Close the Database Expert window.
    6. In the Field Explorer pane on the right, right click any SQL Expressions.
    7. Check if the SQL Expressions are specifying a specific database. If so you might need to change it also.
    8. Save and close your Formula Editor window when you're done editing.

And try running the report again.

The key is to change the datasource connection first, then any tables you need to update, then the other stuff. The connection won't automatically change the tables underneath. Those tables are like goslings that've imprinted on the first large goose-like animal they see. They'll continue to bypass all reason and logic and go to where they've always gone unless you specifically manually change them.

To make it more convenient, here's a tip: You can "Show SQL Query" in the Database menu, and you'll see table names qualified with the database (like "Sales"."dbo"."Customers") for any tables that go straight to a specific database. That might make the hunting easier if you have a lot of stuff going on. When I tackled this problem I had to change each and every table to point to the new table in the new database.

Sorting a vector in descending order

Instead of a functor as Mehrdad proposed, you could use a Lambda function.

sort(numbers.begin(), numbers.end(), [](const int a, const int b) {return a > b; });

Remove empty strings from a list of strings

>>> lstr = ['hello', '', ' ', 'world', ' ']
>>> lstr
['hello', '', ' ', 'world', ' ']

>>> ' '.join(lstr).split()
['hello', 'world']

>>> filter(None, lstr)
['hello', ' ', 'world', ' ']

Compare time

>>> from timeit import timeit
>>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
>>> timeit('filter(None, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)

Notice that filter(None, lstr) does not remove empty strings with a space ' ', it only prunes away '' while ' '.join(lstr).split() removes both.

To use filter() with white space strings removed, it takes a lot more time:

>>> timeit('filter(None, [l.replace(" ", "") for l in lstr])', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)

splitting a number into the integer and decimal parts

This also works for me

>>> val_int = int(a)
>>> val_fract = a - val_int

Mysql: Select all data between two dates

you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)

How can I specify the default JVM arguments for programs I run from eclipse?

As far as I know there is no option to create global configuration for java applications. You always create a duplicate of the configuration.

enter image description here

Also, if you are using PDE (for plugin development), you can create target platform using windows -> Preferences -> Plug-in development -> Target Platform. Edit has options for program/vm arguments.

Hope this helps

PHP header redirect 301 - what are the implications?

This is better:

//* Permanently redirect page
header("Location: new_page.php",TRUE,301);

Just one call including code 301. Also notice the relative path to the file in the same directory (not "/dir/dir/new_page.php", etc.), which all modern browsers seem to support.

I think this is valid since PHP 5.1.2, possibly earlier.

SQL Server: Examples of PIVOTing String data

Well, for your sample and any with a limited number of unique columns, this should do it.

    distinct a,
    (select distinct t2.b  from t t2  where t1.a=t2.a and t2.b='VIEW'),
    (select distinct t2.b from t t2  where t1.a=t2.a and t2.b='EDIT')
from t t1

Generate MD5 hash string with T-SQL

You didn't explicitly say you wanted the string to be hex; if you are open to the more space efficient base 64 string encoding, and you are using SQL Server 2016 or later, here's an alternative:

select SubString(h, 1, 32) from OpenJson(
    (select HashBytes('MD5', '[email protected]') h for json path)
) with (h nvarchar(max));

This produces:


JavaScript override methods

the method modify() that you called in the last is called in global context if you want to override modify() you first have to inherit A or B.

Maybe you're trying to do this:

In this case C inherits A

function A() {
    this.modify = function() {
        alert("in A");

function B() {
    this.modify = function() {
        alert("in B");

C = function() {
    this.modify = function() {
        alert("in C");

    C.prototype.modify(); // you can call this method where you need to call modify of the parent class

C.prototype = new A();

T-SQL split string based on delimiter

Try filtering out the rows that contain strings with the delimiter and work on those only like:

SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE CHARINDEX('/', myColumn) > 0


SELECT SUBSTRING(myColumn, 1, CHARINDEX('/', myColumn)-1) AS FirstName,
       SUBSTRING(myColumn, CHARINDEX('/', myColumn) + 1, 1000) AS LastName
FROM   MyTable
WHERE myColumn LIKE '%/%'

How to write lists inside a markdown table?

If you want a no-bullet list (or any other non-standard usage) or more lines in a cell use <br />

| Event         | Platform      | Description |
| ------------- |-----------| -----:|
| `message_received`| `facebook-messenger`<br/>`skype`|

Best way to check if column returns a null value (from database to .net application)

Just check for

if(table.rows[0][0] == null)
     //Whatever I want to do

or you could

     //Whatever I want to do

CSS: How to align vertically a "label" and "input" inside a "div"?

Wrap the label and input in another div with a defined height. This may not work in IE versions lower than 8.

top:0; bottom:0; left:0; right:0;

removing table border

From your case, you need to set the border to none on <table> and <td> tags.

    <table width=1000 style="border:none; border-collapse:collapse; cellspacing:0; cellpadding:0" >
            <td style="border:none" rowspan=2>
                <img src="/Content/Images/elk_banner.jpg" />
            <td style="border:none">
                <div id="logindisplay">

How to export private key from a keystore of self-signed certificate

Use Keystore Explorer gui - - allows you to extract the private key from a .jks in various formats.

How to Sort Date in descending order From Arraylist Date in android?

Date's compareTo() you're using will work for ascending order.

To do descending, just reverse the value of compareTo() coming out. You can use a single Comparator class that takes in a flag/enum in the constructor that identifies the sort order

public int compare(MyObject lhs, MyObject rhs) {

    if(SortDirection.Ascending == m_sortDirection) {
        return lhs.MyDateTime.compareTo(rhs.MyDateTime);

    return rhs.MyDateTime.compareTo(lhs.MyDateTime);

You need to call Collections.sort() to actually sort the list.

As a side note, I'm not sure why you're defining your map inside your for loop. I'm not exactly sure what your code is trying to do, but I assume you want to populate the indexed values from your for loop in to the map.

How do you check "if not null" with Eloquent?

If you want to search deleted record (Soft Deleted Record), do't user Eloquent Model Query. Instead use Db::table query e.g Instead of using Below:

$stu = Student::where('rollNum', '=', $rollNum . '-' . $nursery)->first();


$stu = DB::table('students')->where('rollNum', '=', $newRollNo)->first();

Extract Number from String in Python

Above solutions seem to assume integers. Here's a minor modification to allow decimals:

num = float("".join(filter(lambda d: str.isdigit(d) or d == '.', inputString)

(Doesn't account for - sign, and assumes any period is properly placed in digit string, not just some english-language period lying around. It's not built to be indestructible, but worked for my data case.)

Insert line break inside placeholder attribute of a textarea?

I modified @Richard Bronosky's fiddle like this.

It's better approach to use data-* attribute rather than a custom attribute. I replaced <textarea placeholdernl> to <textarea data-placeholder> and some other styles as well.

Here is the Richard's original answer which contains full code snippet.

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

Android: How do I prevent the soft keyboard from pushing my view up?

Add following code to the 'activity' of Manifest file.


How do I read all classes from a Java package in the classpath?

Spring has implemented an excellent classpath search function in the PathMatchingResourcePatternResolver. If you use the classpath*: prefix, you can find all the resources, including classes in a given hierarchy, and even filter them if you want. Then you can use the children of AbstractTypeHierarchyTraversingFilter, AnnotationTypeFilter and AssignableTypeFilter to filter those resources either on class level annotations or on interfaces they implement.

Copy and Paste a set range in the next empty row

Below is the code that works well but my values overlap in sheet "Final" everytime the condition of <=11 meets in sheet "Calculator"

I would like you to kindly support me to modify the code so that the cursor should move to next blank cell and values keeps on adding up like a list.

Dim i As Integer
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Calculator")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Final")

For i = 2 To ws1.Range("A65536").End(xlUp).Row

    If ws1.Cells(i, 4) <= 11 Then

        ws2.Cells(i, 1).Value = Left(Worksheets("Calculator").Cells(i, 1).Value, Len(Worksheets("Calculator").Cells(i, 1).Value) - 0)
        ws2.Cells(i, 2) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:D"), 4, False)
        ws2.Cells(i, 3) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:E"), 5, False)
        ws2.Cells(i, 4) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:B"), 2, False)
        ws2.Cells(i, 5) = Application.VLookup(Cells(i, 1), Worksheets("Calculator").Columns("A:C"), 3, False)

    End If
Next i

Adding Git-Bash to the new Windows Terminal

Change the profiles parameter to "commandline": "%PROGRAMFILES%\\Git\\bin\\bash.exe -l -i"

This works for me and allows for my .bash_profile alias autocomplete scripts to run.

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Install Genymotion 2.10 or above, now there is a dedicated button to install Google Play Services name "Open GApps". Link for more info

3 Steps process for Genymotion 2.9 or below:-

4.4 Kitkat
5.0 Lollipop
5.1 Lollipop
6.0 Marshmallow
7.0 Nougat
7.1 Nougat (webview patch)
8.0 Oreo
8.1 Oreo
9.0 Pie

  1. Download from above link
  2. Just drag & drop downloaded zip file to genymotion and restart
  3. Add google account and download "Google Play Music" and Run.

android EditText - finished typing event

I personally prefer automatic submit after end of typing. Here's how you can detect this event.

Declarations and initialization:

private Timer timer = new Timer();
private final long DELAY = 1000; // in ms

Listener in e.g. onCreate()

EditText editTextStop = (EditText) findViewById(;
    editTextStop.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
        public void onTextChanged(final CharSequence s, int start, int before,
                int count) {
            if(timer != null)
        public void afterTextChanged(final Editable s) {
            //avoid triggering event when text is too short
            if (s.length() >= 3) {              

                timer = new Timer();
                timer.schedule(new TimerTask() {
                    public void run() {
                        // TODO: do what you need here (refresh list)
                        // you will probably need to use
                        // runOnUiThread(Runnable action) for some specific
                        // actions

                }, DELAY);

So, when text is changed the timer is starting to wait for any next changes to happen. When they occure timer is cancelled and then started once again.

correct quoting for cmd.exe for multiple arguments

Spaces are horrible in filenames or directory names.

The correct syntax for this is to include every directory name that includes spaces, in double quotes

cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\ mysolution.sln /build "release|win32"

Ubuntu - Run command on start-up with "sudo"

Nice answers. You could also set Jobs (i.e., commands) with "Crontab" for more flexibility (which provides different options to run scripts, loggin the outputs, etc.), although it requires more time to be understood and set properly:

Using '@reboot' you can Run a command once, at startup.

Wrapping up: run $ sudo crontab -e -u root

And add a line at the end of the file with your command as follows:

@reboot sudo searchd

Check if element is clickable in Selenium Java

List<WebElement> wb=driver.findElements(By.xpath(newXpath));
        for(WebElement we: wb){
            if(we.isDisplayed() && we.isEnabled())

.htaccess redirect www to non-www with SSL/HTTPS

To me was better hardcoding "" as string, so I need less rules, even you can use it to redirect from .org to .com or similar too:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTP_HOST} !^example\.com$ [NC]
  RewriteRule ^{REQUEST_URI} [L,NE,R=301]

How to change a text with jQuery

This should work fine (using .text():

$("#toptitle").text("New word");

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

I had to be logged into Ubuntu as root in order to access Mariadb as root. It may have something to do with that "Harden ..." that it prompts you to do when you first install. So:

$ sudo su
[sudo] password for user: yourubunturootpassword
# mysql -r root -p
Enter password: yourmariadbrootpassword

and you're in.

Can table columns with a Foreign Key be NULL?

Yes, the value can be NULL, but you must be explicit. I have experienced this same situation before, and it's easy to forget WHY this happens, and so it takes a little bit to remember what needs to be done.

If the data submitted is cast or interpreted as an empty string, it will fail. However, by explicitly setting the value to NULL when INSERTING or UPDATING, you're good to go.

But this is the fun of programming, isn't it? Creating our own problems and then fixing them! Cheers!

"while :" vs. "while true"

The colon is a built-in command that does nothing, but returns 0 (success). Thus, it's shorter (and faster) than calling an actual command to do the same thing.

How do I convert a string to enum in TypeScript?

As of Typescript 2.1 string keys in enums are strongly typed. keyof typeof is used to get info about available string keys (1):

enum Color{
    Red, Green

let typedColor: Color = Color.Green;
let typedColorString: keyof typeof Color = "Green";

// Error "Black is not assignable ..." (indexing using Color["Black"] will return undefined runtime)
typedColorString = "Black";

// Error "Type 'string' is not assignable ..." (indexing works runtime)
let letColorString = "Red";
typedColorString = letColorString;

// Works fine
typedColorString = "Red";

// Works fine
const constColorString = "Red";
typedColorString = constColorString

// Works fine (thanks @SergeyT)
let letColorString = "Red";
typedColorString = letColorString as keyof typeof Color;

typedColor = Color[typedColorString];

Javascript can't find element by id?

The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

Is it possible to change the speed of HTML's <marquee> tag?

There isn't specifically an attribute to control that. Marquee isn't a highly reliable tag anyways. You may want to consider using jQuery and the .animate() function. If you are interested in pursuing that avenue and need code for it, just let me know.

Show datalist labels but submit the actual value

Note that datalist is not the same as a select. It allows users to enter a custom value that is not in the list, and it would be impossible to fetch an alternate value for such input without defining it first.

Possible ways to handle user input are to submit the entered value as is, submit a blank value, or prevent submitting. This answer handles only the first two options.

If you want to disallow user input entirely, maybe select would be a better choice.

To show only the text value of the option in the dropdown, we use the inner text for it and leave out the value attribute. The actual value that we want to send along is stored in a custom data-value attribute:

To submit this data-value we have to use an <input type="hidden">. In this case we leave out the name="answer" on the regular input and move it to the hidden copy.

<input list="suggestionList" id="answerInput">
<datalist id="suggestionList">
    <option data-value="42">The answer</option>
<input type="hidden" name="answer" id="answerInput-hidden">

This way, when the text in the original input changes we can use javascript to check if the text also present in the datalist and fetch its data-value. That value is inserted into the hidden input and submitted.

document.querySelector('input[list]').addEventListener('input', function(e) {
    var input =,
        list = input.getAttribute('list'),
        options = document.querySelectorAll('#' + list + ' option'),
        hiddenInput = document.getElementById(input.getAttribute('id') + '-hidden'),
        inputValue = input.value;

    hiddenInput.value = inputValue;

    for(var i = 0; i < options.length; i++) {
        var option = options[i];

        if(option.innerText === inputValue) {
            hiddenInput.value = option.getAttribute('data-value');

The id answer and answer-hidden on the regular and hidden input are needed for the script to know which input belongs to which hidden version. This way it's possible to have multiple inputs on the same page with one or more datalists providing suggestions.

Any user input is submitted as is. To submit an empty value when the user input is not present in the datalist, change hiddenInput.value = inputValue to hiddenInput.value = ""

Working jsFiddle examples: plain javascript and jQuery

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

How to rename a table column in Oracle 10g

alter table table_name rename column oldColumn to newColumn;

How to parseInt in Angular.js

<input type="number" string-to-number ng-model="num1">
<input type="number" string-to-number ng-model="num2">

Total: {{num1 + num2}}

and in js :

parseInt($scope.num1) + parseInt($scope.num2)

How can I set the 'backend' in matplotlib in Python?

I hit this when trying to compile python, numpy, scipy, matplotlib in my own VIRTUAL_ENV

Before installing matplotlib you have to build and install: pygobject pycairo pygtk

And then do it with matplotlib: Before building matplotlib check with 'python ./ build --help' if 'gtkagg' backend is enabled. Then build and install

Before export PKG_CONFIG_PATH=$VIRTUAL_ENV/lib/pkgconfig

Ruby capitalize every word first letter

try this:

puts 'one TWO three foUR'' ')

#=> One Two Three Four


puts 'one TWO three foUR'*' '

Avoid browser popup blockers

I didn't want to make the new page unless the callback returned successfully, so I did this to simulate the user click:

function submitAndRedirect {
  apiCall.then(({ redirect }) => {
      const a = document.createElement('a');
      a.href = redirect; = '_blank';

How to copy an object in Objective-C

I don't know the difference between that code and mine, but I have problems with that solution, so I read a little bit more and found that we have to set the object before return it. I mean something like:

#import <Foundation/Foundation.h>

@interface YourObject : NSObject <NSCopying>

@property (strong, nonatomic) NSString *name;
@property (strong, nonatomic) NSString *line;
@property (strong, nonatomic) NSMutableString *tags;
@property (strong, nonatomic) NSString *htmlSource;
@property (strong, nonatomic) NSMutableString *obj;

-(id) copyWithZone: (NSZone *) zone;


@implementation YourObject

-(id) copyWithZone: (NSZone *) zone
    YourObject *copy = [[YourObject allocWithZone: zone] init];

    [copy setNombre:];
    [copy setLinea: self.line];
    [copy setTags: self.tags];
    [copy setHtmlSource: self.htmlSource];

    return copy;

I added this answer because I have a lot of problems with this issue and I have no clue about why is it happening. I don't know the difference, but it's working for me and maybe it can be useful for others too : )

Convert a bitmap into a byte array

Very simple use this just in one line:

byte[] imgdata = File.ReadAllBytes(@"C:\download.png");

how to set width for PdfPCell in ItextSharp

aca definis los anchos

 float[] anchoDeColumnas= new float[] {10f, 20f, 30f, 10f};

aca se los insertas a la tabla que tiene las columnas


Adding an onclick event to a div element

maybe your script tab has some problem.

if you set type, must type="application/javascript".

<!DOCTYPE html>
        <div onclick="showMsg('Hello')">
            Click me show message
        <script type="application/javascript">
            function showMsg(item) {

OS X: equivalent of Linux's wget

Curl has a mode that is almost equivalent to the default wget.

curl -O <url>

This works just like

wget <url>

And, if you like, you can add this to your .bashrc:

alias wget='curl -O'

It's not 100% compatible, but it works for the most common wget usage (IMO)

Return JsonResult from web api without its properties

return JsonConvert.SerializeObject(images.ToList(), Formatting.None, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

using Newtonsoft.Json;

Oracle date function for the previous month

It is working with me in Oracle sql developer

    SELECT add_months(trunc(sysdate,'mm'), -1),
           last_day(add_months(trunc(sysdate,'mm'), -1)) 
    FROM dual

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/ in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called, loaded it in a script in file

C:\Temp> cat
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }


C:\Temp> cat
use strict; use warnings;

    require '';

my $p = Example::Plot::FourD->new;

C:\Temp> s

This example shows that module files do not have to end in 1, any true value will do.

Create a function with optional call variables

I don't think your question is very clear, this code assumes that if you're going to include the -domain parameter, it's always 'named' (i.e. dostuff computername arg2 -domain domain); this also makes the computername parameter mandatory.

Function DoStuff(){
        $domain = 'domain1'
    write-host $domain
        write-host "arg2 present... executing script block"
        write-host "arg2 missing... exiting or whatever"

Unable to copy ~/.ssh/

Try this and it will work like a charm. I was having the same error but this approach did the trick for me:

ssh USER@REMOTE "cat file"|xclip -i

The data-toggle attributes in Twitter Bootstrap

It is a Bootstrap defined HTML5 data attribute. It binds a button to an event.

How to modify existing, unpushed commit messages?

If it's your last commit, just amend the commit:

git commit --amend -o -m "New commit message"

(Using the -o (--only) flag to make sure you change only the commit message)

If it's a buried commit, use the awesome interactive rebase:

git rebase -i @~9   # Show the last 9 commits in a text editor

Find the commit you want, change pick to r (reword), and save and close the file. Done!

Miniature Vim tutorial (or, how to rebase with only 8 keystrokes 3jcwrEscZZ):

  • Run vimtutor if you have time
  • hjkl correspond to movement keys ????
  • All commands can be prefixed with a "range", e.g. 3j moves down three lines
  • i to enter insert mode — text you type will appear in the file
  • Esc or Ctrlc to exit insert mode and return to "normal" mode
  • u to undo
  • Ctrlr to redo
  • dd, dw, dl to delete a line, word, or letter, respectively
  • cc, cw, cl to change a line, word, or letter, respectively (same as ddi)
  • yy, yw, yl to copy ("yank") a line, word, or letter, respectively
  • p or P to paste after, or before current position, respectively
  • :wEnter to save (write) a file
  • :q!Enter to quit without saving
  • :wqEnter or ZZ to save and quit

If you edit text a lot, then switch to the Dvorak keyboard layout, learn to touch-type, and learn Vim. Is it worth the effort? Yes.

ProTip™: Don't be afraid to experiment with "dangerous" commands that rewrite history* — Git doesn't delete your commits for 90 days by default; you can find them in the reflog:

$ git reset @~3   # Go back three commits
$ git reflog
c4f708b HEAD@{0}: reset: moving to @~3
2c52489 HEAD@{1}: commit: more changes
4a5246d HEAD@{2}: commit: make important changes
e8571e4 HEAD@{3}: commit: make some changes
... earlier commits ...
$ git reset 2c52489
... and you're back where you started

* Watch out for options like --hard and --force though — they can discard data. * Also, don't rewrite history on any branches you're collaborating on.

How to use Chrome's network debugger with redirects

I don't know of a way to force Chrome to not clear the Network debugger, but this might accomplish what you're looking for:

  1. Open the js console
  2. window.addEventListener("beforeunload", function() { debugger; }, false)

This will pause chrome before loading the new page by hitting a breakpoint.

Why is there an unexplainable gap between these inline-block div elements?

You need to add


because whenever you write display:inline-block it takes an additional margin-right:4px. So, you need to remove it.

java.sql.SQLException Parameter index out of range (1 > number of parameters, which is 0)

This is an issue with the jdbc Driver version. I had this issue when I was using mysql-connector-java-commercial-5.0.3-bin.jar but when I changed to a later driver version mysql-connector-java-5.1.22.jar, the issue was fixed.

Only allow specific characters in textbox

You can probably use the KeyDown event, KeyPress event or KeyUp event. I would first try the KeyDown event I think.

You can set the Handled property of the event args to stop handling the event.

'Microsoft.ACE.OLEDB.16.0' provider is not registered on the local machine. (System.Data)

An alternative that works for me is to simply convert to a CSV.

How to finish Activity when starting other activity in Android?

The best - and simplest - solution might be this:

Intent intent = new Intent(this, OtherActivity.class);

Documentation for finishAndRemoveTask():

Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.

Is that what you're looking for?

What's the best way to join on the same table twice?

First, I would try and refactor these tables to get away from using phone numbers as natural keys. I am not a fan of natural keys and this is a great example why. Natural keys, especially things like phone numbers, can change and frequently so. Updating your database when that change happens will be a HUGE, error-prone headache. *

Method 1 as you describe it is your best bet though. It looks a bit terse due to the naming scheme and the short aliases but... aliasing is your friend when it comes to joining the same table multiple times or using subqueries etc.

I would just clean things up a bit:

SELECT t.PhoneNumber1, t.PhoneNumber2, 
   t1.SomeOtherFieldForPhone1, t2.someOtherFieldForPhone2
FROM Table1 t
JOIN Table2 t1 ON t1.PhoneNumber = t.PhoneNumber1
JOIN Table2 t2 ON t2.PhoneNumber = t.PhoneNumber2

What i did:

  • No need to specify INNER - it's implied by the fact that you don't specify LEFT or RIGHT
  • Don't n-suffix your primary lookup table
  • N-Suffix the table aliases that you will use multiple times to make it obvious

*One way DBAs avoid the headaches of updating natural keys is to not specify primary keys and foreign key constraints which further compounds the issues with poor db design. I've actually seen this more often than not.

Parsing a CSV file using NodeJS

I use this simple one:

Very simple to use:

const csv = require('csv-parser')
const fs = require('fs')
const results = [];

fs.createReadStream('./CSVs/Update 20191103C.csv')
  .on('data', (data) => results.push(data))
  .on('end', () => {
    console.log(results[0]['Lowest Selling Price'])

How to add conditional attribute in Angular 2?

You can use a better approach for someone writing HTML for an already existing scss.



[role = "true"] { ... }

That way you don't need to <boolean> ? true : null every time.

Disable all dialog boxes in Excel while running VB script?

Solution: Automation Macros

It sounds like you would benefit from using an automation utility. If you were using a windows PC I would recommend AutoHotkey. I haven't used automation utilities on a Mac, but this Ask Different post has several suggestions, though none appear to be free.

This is not a VBA solution. These macros run outside of Excel and can interact with programs using keyboard strokes, mouse movements and clicks.

Basically you record or write a simple automation macro that waits for the Excel "Save As" dialogue box to become active, hits enter/return to complete the save action and then waits for the "Save As" window to close. You can set it to run in a continuous loop until you manually end the macro.

Here's a simple version of a Windows AutoHotkey script that would accomplish what you are attempting to do on a Mac. It should give you an idea of the logic involved.

Example Automation Macro: AutoHotkey

; ' Infinite loop.  End the macro by closing the program from the Windows taskbar.
Loop {

    ; ' Wait for ANY "Save As" dialogue box in any program.
    ; ' BE CAREFUL!
    ; '  Ignore the "Confirm Save As" dialogue if attempt is made
    ; '  to overwrite an existing file.
    WinWait, Save As,,, Confirm Save As
    IfWinNotActive, Save As,,, Confirm Save As
        WinActivate, Save As,,, Confirm Save As
    WinWaitActive, Save As,,, Confirm Save As

    sleep, 250 ; ' 0.25 second delay
    Send, {ENTER} ; ' Save the Excel file.

    ; ' Wait for the "Save As" dialogue box to close.
    WinWaitClose, Save As,,, Confirm Save As

How to combine two byte arrays

You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils class ). You need to do the following

byte[] concatBytes = ArrayUtils.addAll(one,two);

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

fname = 'filenotfound.txt'
    f = open(fname, 'rb')
except FileNotFoundError:
    print("file {} does not exist".format(fname))

file filenotfound.txt does not exist

exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.
This exception does not exist in Python 2.

How to remove ASP.Net MVC Default HTTP Headers?

.NET Core

To remove the Server header, within the Program.cs file, add the following option:

.UseKestrel(opt => opt.AddServerHeader = false)

For dot net core 1, put add the option inside the .UseKestrel() call. For dot net core 2, add the line after UseStartup().

To remove X-Powered-By header, if deployed to IIS, edit your web.config and add the following section inside the system.webServer tag:

        <remove name="X-Powered-By" />

.NET 4.5.2

To remove the Server header, within your global.asax file add the following:

    protected void Application_BeginRequest(object sender, EventArgs e)
        string[] headers = { "Server", "X-AspNet-Version" };

        if (!Response.HeadersWritten)
            Response.AddOnSendingHeaders((c) =>
                if (c != null && c.Response != null && c.Response.Headers != null)
                    foreach (string header in headers)
                        if (c.Response.Headers[header] != null)


Pre .NET 4.5.2

Add the following c# class to your project:

public class RemoveServerHeaderModule : IHttpModule
    public void Init(HttpApplication context)
        context.PreSendRequestHeaders += OnPreSendRequestHeaders;

    public void Dispose() { }

    void OnPreSendRequestHeaders(object sender, EventArgs e)

and then within your web.config add the following <modules> section:

    <add name="RemoveServerHeaderModule" type="MyNamespace.RemoveServerHeaderModule" />

However I had a problem where sub-projects couldn't find this module. Not fun.

Removing X-AspNetMvc-Version header

To remove the ''X-AspNetMvc-Version'' tag, for any version of .NET, modify your ''web.config'' file to include:

   <httpRuntime enableVersionHeader="false" />

Thanks Microsoft for making this unbelievably difficult. Or maybe that was your intention so that you could track IIS and MVC installs across the world ...

Check/Uncheck all the checkboxes in a table


Add onClick event to checkbox where you want, like below.

<input type="checkbox" onClick="selectall(this)"/>Select All<br/>
<input type="checkbox" name="foo" value="make">Make<br/>
<input type="checkbox" name="foo" value="model">Model<br/>
<input type="checkbox" name="foo" value="descr">Description<br/>
<input type="checkbox" name="foo" value="startYr">Start Year<br/>
<input type="checkbox" name="foo" value="endYr">End Year<br/>

In JavaScript you can write selectall function as

function selectall(source) {
  checkboxes = document.getElementsByName('foo');
  for(var i=0, n=checkboxes.length;i<n;i++) {
    checkboxes[i].checked = source.checked;

Node Sass couldn't find a binding for your current environment

This is something that may not happen to anyone else, but in my case, this error appeared when I decided to restart my project (to follow a different vue.js tutorial).

The steps that created my problem was:

# move my existing project
mv project-name project-name-old
# create a new project
vue create project-name
# run server
npm run server

The problem was that my previous server was still running on a different terminal tab. On localhost:8080, the page that was still showing was the old project.

All I had to do was shut down the old server in the terminal and execute "npm run serve" again (or view localhost:8081).

Just in case this confounds someone else for half an hour, or for laughs and giggles.

How to display the string html contents into webbrowser control?

Try this:

webBrowser1.DocumentText =
    "<html><body>Please enter your name:<br/>" +
    "<input type='text' name='userName'/><br/>" +
    "<a href=''>continue</a>" +

java.lang.NoSuchMethodError: org.apache.commons.codec.binary.Base64.encodeBase64String() in Java EE application

Some Google tooling such as GWT has an embedded version of commons-codec with a pre-1.4 Base64 class. You may need to make such tooling JARs inaccessible to your code by refactoring your project such that only the parts of your code that need that tooling can see the dependency.

Get the time of a datetime using T-SQL?


IN SQL Server 2008+


Accessing Websites through a Different Port?

It depends.

The web server on the other end will be set to a certain port, usually 80 and will only accept requests on that specific port. Something along the chain will need to be talking to port 80 to the website.

If you control the website, then you can change the port, or get it to accept requests on multiple ports.

If the website is already talking on a different port, you can just use the colon syntax to reference another port (eg: for port 1234).

If you want to use a different port on your client end, but you want to talk to port 80 at the web server end, you'll need to route traffic from port x to port 80. A common way to get this up and running is to use Port Fowarding. ssh can do this for you, see here for a Unix/technical overview or here if you're on Windows.

Hope that helps.

How to check whether Kafka Server is running?

For Linux, "ps aux | grep kafka" see if kafka properties are shown in the results. E.g. /path/to/kafka/

Get an object attribute

If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName") - or to elaborate:

user = User()
property = "fullName"
name = getattr(user, property)

Otherwise just use user.fullName.

How do I fix 'ImportError: cannot import name IncompleteRead'?

This should work for you. Follow these simple steps.

First, let's remove the pip which is already installed so it won't cause any error.

Open Terminal.

Type: sudo apt-get remove python-pip

It removes pip that is already installed.


Step: 1 sudo easy_install -U pip

It will install pip latest version.

And will return its address: Installed /usr/local/lib/python2.7/dist-packages/pip-6.1.1-py2.7.egg



Step: 1 go to this link.

Step: 2 Right click >> Save as.. with name .

Step: 3 use: cd to go to the same directory as your file

Step: 4 use: sudo python

It will install pip latest version.



Step: 1 use: sudo apt-get install python-pip

It will install pip latest version.

Referring to the null object in Python

Null is a special object type like:

<class 'NoneType'>

You can check if an object is in class 'NoneType':

>>>variable = None
>>>variable is None

More information is available at Python Docs

How to line-break from css, without using <br />?

Impossible with the same HTML structure, you must have something to distinguish between Hello and How are you.

I suggest using spans that you will then display as blocks (just like a <div> actually).

p span {_x000D_
  display: block;_x000D_
<p><span>hello</span><span>How are you</span></p>

How to get arguments with flags in Bash


if getopts "n:" arg; then
  echo "Welcome $OPTARG"

Save it as and try running

sh -n John

in your terminal.

Unable to load DLL 'SQLite.Interop.dll'

As the SQLite wiki says, your application deployment must be:

Application deployment

So you need to follow the rules. Find dll that matches your target platform and put it in location, describes in the picture. Dlls can be found in YourSolution/packages/System.Data.SQLite.Core.%version%/.

I had problems with application deployment, so I just added right SQLite.Interop.dll into my project, the added x86 folder to AppplicationFolder in setup project and added file references to dll.

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Install a Nuget package in Visual Studio Code

Modify your project.json or *.csproj file. Add a dependency entry with the name of the package and the version desired.

JSON example:

   "dependencies" : {

     "AutoMapper": "5.2.0"

How do you write a migration to rename an ActiveRecord model and its table in Rails?

Here's an example:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def self.up
    rename_table :old_table_name, :new_table_name

  def self.down
    rename_table :new_table_name, :old_table_name

I had to go and rename the model declaration file manually.


In Rails 3.1 & 4, ActiveRecord::Migration::CommandRecorder knows how to reverse rename_table migrations, so you can do this:

class RenameOldTableToNewTable < ActiveRecord::Migration
  def change
    rename_table :old_table_name, :new_table_name

(You still have to go through and manually rename your files.)

how to change class name of an element by jquery


Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

Handling errors in Promise.all

That's how Promise.all is designed to work. If a single promise reject()'s, the entire method immediately fails.

There are use cases where one might want to have the Promise.all allowing for promises to fail. To make this happen, simply don't use any reject() statements in your promise. However, to ensure your app/script does not freeze in case any single underlying promise never gets a response, you need to put a timeout on it.

function getThing(uid,branch){
    return new Promise(function (resolve, reject) {
        xhr.get().then(function(res) {
            if (res) {
            else {
        }).catch(function(error) {

div background color, to change onhover

Using Javascript

   <div id="mydiv" style="width:200px;background:white" onmouseover="'gray';" onmouseout="'white';">
    Jack and Jill went up the hill 
    To fetch a pail of water. 
    Jack fell down and broke his crown, 
    And Jill came tumbling after. 

Sending email in .NET through Gmail

If you want to send background email, then please do the below

 public void SendEmail(string address, string subject, string message)
 Thread threadSendMails;
 threadSendMails = new Thread(delegate()

      //Place your Code here 

  threadSendMails.IsBackground = true;

and add namespace

using System.Threading;

How can I exit from a javascript function?

you can use

return false; or return; within your condition.

function refreshGrid(entity) {
    var store = window.localStorage;
    var partitionKey;
    if(some_condition) {
      return false;

VBA equivalent to Excel's mod function

My way to replicate Excel's MOD(a,b) in VBA is to use XLMod(a,b) in VBA where you include the function:

Function XLMod(a, b)
    ' This replicates the Excel MOD function
    XLMod = a - b * Int(a / b)
End Function

in your VBA Module

Why would a " Connection timed out" exception occur when URL is up?

Connection timeouts (assuming a local network and several client machines) typically result from

a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"

b) packet loss due to wrong network configuration or line overload

c) too many requests overloading the server

d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).

Hope this helps.

How to create a QR code reader in a HTML5 website?

There aren't many JavaScript decoders.

There is one at

The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.

How to filter wireshark to see only dns queries that are sent/received from/by my computer?

use this filter:

(dns.flags.response == 0) and (ip.src ==

what this query does is it only gives dns queries originated from your ip

Javascript find json value

Making more general the @showdev answer.

var getObjectByValue = function (array, key, value) {
    return array.filter(function (object) {
        return object[key] === value;


getObjectByValue(data, "code", "DZ" );

Play sound file in a web-page in the background

<audio src="/music/good_enough.mp3" autoplay>
<p>If you are reading this, it is because your browser does not support the audio element.     </p>
<embed src="/music/good_enough.mp3" width="180" height="90" hidden="true" />

Works for me just fine.

How to set thousands separator in Java?

You can use format function with ",";

int no = 124750;
String str = String.format("%,d", no);

//str = 124,750

"," includes locale-specific grouping characters.


Export result set on Dbeaver to CSV

The problem was the box "open new connection" that was checked. So I couldn't use my temporary table.

How to fix 'sudo: no tty present and no askpass program specified' error?


  1. Use NOPASSWD line for all commands, I mean:

    jenkins ALL=(ALL) NOPASSWD: ALL
  2. Put the line after all other lines in the sudoers file.

That worked for me (Ubuntu 14.04).

"Prevent saving changes that require the table to be re-created" negative effects

Tools --> Options --> Designers node --> Uncheck " Prevent saving changes that require table recreation ".

Python Key Error=0 - Can't find Dict error in code

The defaultdict solution is better. But for completeness you could also check and create empty list before the append. Add the + lines:

+ if not u in self.adj.keys():
+     self.adj[u] = []

Convert Data URI to File then append to FormData

The evolving standard looks to be canvas.toBlob() not canvas.getAsFile() as Mozilla hazarded to guess.

I don't see any browser yet supporting it :(

Thanks for this great thread!

Also, anyone trying the accepted answer should be careful with BlobBuilder as I'm finding support to be limited (and namespaced):

    var bb;
    try {
        bb = new BlobBuilder();
    } catch(e) {
        try {
            bb = new WebKitBlobBuilder();
        } catch(e) {
            bb = new MozBlobBuilder();

Were you using another library's polyfill for BlobBuilder?

ORA-28001: The password has expired

Just go to the machine where your database resides, search windows -> search SqlPlus Type the user name, then type password, it will prompt you to give new password. On providing new password, it will say successfully changed the password.

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Perfectly fine.
You can't instantiate abstract classes.. but abstract classes can be used to house common implementations for m1() and m3().
So if m2() implementation is different for each implementation but m1 and m3 are not. You could create different concrete IAnything implementations with just the different m2 implementation and derive from AbstractThing -- honoring the DRY principle. Validating if the interface is completely implemented for an abstract class is futile..

Update: Interestingly, I find that C# enforces this as a compile error. You are forced to copy the method signatures and prefix them with 'abstract public' in the abstract base class in this scenario.. (something new everyday:)

How to pass password to scp?

steps to get sshpass For rhel/centos 6 :

# wget
# rpm -ivh epel-release-6-8.noarch.rpm
# yum install sshpass


How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

This is exactly what I needed for my MVC site configuration!

I added a little modification to the OnException method to handle multiple HandleErrorAttribute instances, as suggested by Atif Aziz:

bear in mind that you may have to take care that if multiple HandleErrorAttribute instances are in effect then duplicate logging does not occur.

I simply check context.ExceptionHandled before invoking the base class, just to know if someone else handled the exception before current handler.
It works for me and I post the code in case someone else needs it and to ask if anyone knows if I overlooked anything.

Hope it is useful:

public override void OnException(ExceptionContext context)
    bool exceptionHandledByPreviousHandler = context.ExceptionHandled;


    Exception e = context.Exception;
    if (exceptionHandledByPreviousHandler
        || !context.ExceptionHandled  // if unhandled, will be logged anyhow
        || RaiseErrorSignal(e)        // prefer signaling, if possible
        || IsFiltered(context))       // filtered?


Fixing npm path in Windows 8 and 10

If after installing your npm successfully, and you want to install VueJS then this is what you should do

after running the following command (as Admin)

npm install --global vue-cli

It will place the vue.cmd in the following directory C:\Users\YourUserName\AppData\Roaming\npm

you will see this in your directory.

Now to use vue as a command in cmd. Open the cmd as admin and run the following command.

setx /M path "%path%;%appdata%\npm"

Now restart the cmd and run the vue again. It should work just fine, and then you can begin to develop with VueJS.

I hope this helps.

Component is not part of any NgModule or the module has not been imported into your module

My case is same as @7guyo mentioned. I'm using lazyloading and was unconsiously doing this:

import { component1Route } from './path/component1.route';

export const entityState: Routes = [
   path: 'home',
   children: component1Route

Instead of:

imports: [
     path: '',
     loadChildren: () => import('./component1/component1.module').then(m => m.ComponentOneModule)
    path: '',
    loadChildren: () => import('./component2/component2.module').then(m => m.ComponentTwoModule)

  export class MainModule {}

How can I open Java .class files in a human-readable way?

JAD and/or JADclipse Eclipse plugin, for sure.

Have a div cling to top of screen if scrolled down past it

The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.

This is done with something like this, attaching a handler to the window.scroll event

   // Cache selectors outside callback for performance. 
   var $window = $(window),
       $stickyEl = $('#the-sticky-div'),
       elTop = $stickyEl.offset().top;

   $window.scroll(function() {
        $stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);

This simply adds a sticky CSS class when the page has scrolled past it, and removes the class when it's back up.

And the CSS class looks like this

  #the-sticky-div.sticky {
     position: fixed;
     top: 0;

EDIT- Modified code to cache jQuery objects, faster now.

Using FFmpeg in .net?

The original question is now more than 5 years old. In the meantime there is now a solution for a WinRT solution from ffmpeg and an integration sample from Microsoft.

Socket send and receive byte array

First, do not use DataOutputStream unless it’s really necessary. Second:

Socket socket = new Socket("host", port);
OutputStream socketOutputStream = socket.getOutputStream();

Of course this lacks any error checking but this should get you going. The JDK API Javadoc is your friend and can help you a lot.

LEFT JOIN only first row

@Matt Dodges answer put me on the right track. Thanks again for all the answers, which helped a lot of guys in the mean time. Got it working like this:

FROM feeds f
LEFT JOIN artists a ON a.artist_id = (
    SELECT artist_id
    FROM feeds_artists fa 
    WHERE fa.feed_id =
    LIMIT 1
WHERE = '13815'

How do I remove whitespace from the end of a string in Python?

>>> "    xyz     ".rstrip()
'    xyz'

There is more about rstrip in the documentation.

Can't compile C program on a Mac after upgrade to Mojave

I've found great solution and explanation at this GitHub comment. The trick:

make SDKROOT=`xcrun --show-sdk-path` MACOSX_DEPLOYMENT_TARGET=

Did the job.

Error while trying to retrieve text for error ORA-01019


Just worked it out. While having both installations we have two ORACLE_HOME directories and both have SQAORA32.dll files. While looking up for ORACLE_HOMe my app was getting confused..I just removed the Client oracle home entry as oracle client is by default present in oracle DB Now its working...Thanks!!

Vertical and horizontal align (middle and center) with CSS

There are many methods :

  1. Center horizontal and vertical align of an element with fixed measure


 <div style="width:200px;height:100px;position:absolute;left:50%;top:50%;

2 . Center horizontally and vertically a single line of text


<div style="width:400px;height:200px;text-align:center;line-height:200px;">

3 . Center horizontal and vertical align of an element with no specific measure


<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">

wget command to download a file and save as a different filename

Using CentOS Linux I found that the easiest syntax would be:

wget "link" -O file.ext

where "link" is the web address you want to save and "file.ext" is the filename and extension of your choice.

Set angular scope variable in markup

You can set values from html like this. I don't think there is a direct solution from angular yet.

 <div style="visibility: hidden;">{{activeTitle='home'}}</div>

Pass Multiple Parameters to jQuery ajax call

    type: 'POST',
    url: 'popup.aspx/GetJewellerAssets',      
    data: "jewellerId=" + filter+ "&locale=" +  locale,  
    success: AjaxSucceeded,
    error: AjaxFailed

compilation error: identifier expected

You have not defined a method around your code.


public class details
    public static void main( String[] args )
        BufferedReader in = new BufferedReader(new InputStreamReader(;
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);

In this case, I have assumed that you want your code to be executed in the main method of the class. It is, of course, possible that this code goes in any other method.

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

In our case we FIXED by adding changeDetection into the component and call detectChanges() in ngAfterContentChecked, code as follows

  selector: 'app-spinner',
  templateUrl: './spinner.component.html',
  styleUrls: ['./spinner.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
export class SpinnerComponent implements OnInit, OnDestroy, AfterContentChecked {

  show = false;

  private subscription: Subscription;

  constructor(private spinnerService: SpinnerService, private changeDedectionRef: ChangeDetectorRef) { }

  ngOnInit() {
    this.subscription = this.spinnerService.spinnerState
      .subscribe((state: SpinnerState) => { =;

  ngAfterContentChecked(): void {

  ngOnDestroy() {


Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

How to grant remote access permissions to mysql server for user?

This grants root access with the same password from any machine in *

    IDENTIFIED BY 'some_characters' 

If name resolution is not going to work, you may also grant access by IP or subnet:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'192.168.1.%'
    IDENTIFIED BY 'some_characters'  

MySQL GRANT syntax docs.

Adding sheets to end of workbook in Excel (normal method not working?)

Be sure to fully qualify your sheets with which workbook they are referencing!

 mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name

How do I enable/disable log levels in Android?

We can use class Log in our local component and define the methods as v/i/e/d. Based on the need of we can make call further.
example is shown below.

    public class Log{
        private static boolean TAG = false;
        public static void d(String enable_tag, String message,Object...args){
            android.util.Log.d(enable_tag, message+args);
        public static void e(String enable_tag, String message,Object...args){
            android.util.Log.e(enable_tag, message+args);
        public static void v(String enable_tag, String message,Object...args){
            android.util.Log.v(enable_tag, message+args);
    if we do not need any print(s), at-all make TAG as false for all else 
    remove the check for type of Log (say Log.d).
    public static void i(String enable_tag, String message,Object...args){
    //      if(TAG)
            android.util.Log.i(enable_tag, message+args);

here message is for string and and args is the value you want to print.

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

Just to complete the answer - on Ubuntu/Mint you can just run:

zcat /usr/share/doc/phpmyadmin/examples/create_tables.sql.gz | mysql

(of course this assumes development environment where your default mysql user is root and you use no password; in other case use | mysql -uuser_name -p)

Search in all files in a project in Sublime Text 3

Here's the easiest way : File -> Find in files

enter image description here

MySQL Event Scheduler on a specific time everyday

The documentation on CREATE EVENT is quite good, but it takes a while to get it right.

You have two problems, first, making the event recur, second, making it run at 13:00 daily.

This example creates a recurring event.

      EVERY 1 HOUR
    COMMENT 'Clears out sessions table each hour.'
      DELETE FROM site_activity.sessions;

When in the command-line MySQL client, you can:


This lists each event with its metadata, like if it should run once only, or be recurring.

The second problem: pointing the recurring event to a specific schedule item.

By trying out different kinds of expression, we can come up with something like:

CREATE EVENT IF NOT EXISTS `session_cleaner_event`
  COMMENT 'Clean up sessions at 13:00 daily!'
    DELETE FROM site_activity.sessions;

Apply a function to every row of a matrix or a data frame

First step would be making the function object, then applying it. If you want a matrix object that has the same number of rows, you can predefine it and use the object[] form as illustrated (otherwise the returned value will be simplified to a vector):

bvnormdens <- function(x=c(0,0),mu=c(0,0), sigma=c(1,1), rho=0){
                           2*rho*x[1]*x[2]/(sigma[1]*sigma[2]))) * 

 bvout<-matrix(NA, ncol=1, nrow=3)
 bvout[] <-apply(out, 1, bvnormdens)
[1,] 1.306423e-02
[2,] 5.931153e-07
[3,] 9.033134e-15

If you wanted to use other than your default parameters then the call should include named arguments after the function:

bvout[] <-apply(out, 1, FUN=bvnormdens, mu=c(-1,1), rho=0.6)

apply() can also be used on higher dimensional arrays and the MARGIN argument can be a vector as well as a single integer.

How to calculate percentage when old value is ZERO

There is no rate of growth from 0 to any other number. That is to say, there is no percentage of increase from zero to greater than zero and there is no percentage of decrease from zero to less than zero (a negative number). What you have to decide is what to put as an output when this situation happens. Here are two possibilities I am comfortable with:

  1. Any time you have to show a rate of increase from zero, output the infinity symbol (8). That's Alt + 236 on your number pad, in case you're wondering. You could also use negative infinity (-8) for a negative growth rate from zero.
  2. Output a statement such as "[Increase/Decrease] From Zero" or something along those lines.

Unfortunately, if you need the growth rate for further calculations, the above options will not work, but, on the other hand, any number would give your following calculations incorrect data any way so the point is moot. You'd need to update your following calculations to account for this eventuality.

As an aside, the ((New-Old)/Old) function will not work when your new and old values are both zero. You should create an initial check to see if both values are zero and, if they are, output zero percent as the growth rate.

What is wrong with my SQL here? #1089 - Incorrect prefix key

It works for me:

    `user_id` INT(10) NOT NULL AUTO_INCREMENT,
    `username` VARCHAR(255) NOT NULL,
    `password` VARCHAR(255) NOT NULL,
    PRIMARY KEY (`user_id`)
) ENGINE = MyISAM;       

scale fit mobile web content using viewport meta tag

I think this should help you.

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">

Tell me if it works.

P/s: here is some media query for standard devices.

Process escape sequences in a string in Python

The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:

>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)

This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).

How do you get the process ID of a program in Unix or Linux using Python?

With psutil:

(can be installed with [sudo] pip install psutil)

import psutil

# Get current process pid
current_process_pid = psutil.Process().pid
print(current_process_pid)  # e.g 12971

# Get pids by program name
program_name = 'chrome'
process_pids = [ for process in psutil.process_iter() if == program_name]
print(process_pids)  # e.g [1059, 2343, ..., ..., 9645]

Concatenate multiple result rows of one column into one, group by another column

Simpler with the aggregate function string_agg() (Postgres 9.0 or later):

SELECT movie, string_agg(actor, ', ') AS actor_list
FROM   tbl

The 1 in GROUP BY 1 is a positional reference and a shortcut for GROUP BY movie in this case.

string_agg() expects data type text as input. Other types need to be cast explicitly (actor::text) - unless an implicit cast to text is defined - which is the case for all other character types (varchar, character, "char"), and some other types.

As isapir commented, you can add an ORDER BY clause in the aggregate call to get a sorted list - should you need that. Like:

SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM   tbl

But it's typically faster to sort rows in a subquery. See:

Setting the selected attribute on a select list using jQuery

I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).

 $('#dropdown').find('option').each( function() {
      var $this = $(this);
      if ($this.text() == 'B') {
         return false;

Regex allow a string to only contain numbers 0 - 9 and limit length to 45

The first matches any number of digits within your string (allows other characters too, i.e.: "039330a29"). The second allows only 45 digits (and not less). So just take the better from both:


where \d is the same like [0-9].

How to check undefined in Typescript

Late to the story but I think some details are overlooked?

if you use

if (uemail !== undefined) {
  //some function

You are, technically, comparing variable uemail with variable undefined and, as the latter is not instantiated, it will give both type and value of 'undefined' purely by default, hence the comparison returns true. But it overlooks the potential that a variable by the name of undefined may actually exist -however unlikely- and would therefore then not be of type undefined. In that case, the comparison will return false.

To be correct one would have to declare a constant of type undefined for example:

const _undefined: undefined

and then test by:

if (uemail === _undefined) {
  //some function

This test will return true as uemail now equals both value & type of _undefined as _undefined is now properly declared to be of type undefined.

Another way would be

if (typeof(uemail) === 'undefined') {
  //some function

In which case the boolean return is based on comparing the two strings on either end of the comparison. This is, from a technical point of view, NOT testing for undefined, although it achieves the same result.

Python: subplot within a loop: first panel appears in wrong position

Using your code with some random data, this would work:

fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)

axs = axs.ravel()

for i in range(10):


The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).

enter image description here

How to clean node_modules folder of packages that are not in package.json?

simple just run

rm -r node_modules

in fact, you can delete any folder with this.

like rm -r AnyFolderWhichIsNotDeletableFromShiftDeleteOrDelete.

just open the gitbash move to root of the folder and run this command

Hope this will help.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

import os
os.environ["PATH"] += os.pathsep + 'D:/Program Files (x86)/Graphviz2.38/bin/'

In windows just add these 2 lines in the beginning, where 'D:/Program Files (x86)/Graphviz2.38/bin/' is replaced by the address of where your bin file is.

That solves the problem.

Using HTML data-attribute to set CSS background-image url

For those who want a dumb down answer like me

Something like how to steps as 1, 2, 3

Here it is what I did

First create the HTML markup

<div class="thumb" data-image-src="images/img.jpg"></div>

Then before your ending body tag, add this script

I included the ending body on the code below as an example

So becareful when you copy

var list = document.getElementsByClassName('thumb');

for (var i = 0; i < list.length; i++) {
  var src = list[i].getAttribute('data-image-src');
  list[i].style.backgroundImage="url('" + src + "')";


Git says remote ref does not exist when I delete remote branch

The command git branch -a shows remote branches that exist in your local repository. This may sound a bit confusing but to understand it, you have to understand that there is a difference between a remote branch, and a branch that exists in a remote repository. Remote branches are local branches that map to branches of the remote repository. So the set of remote branches represent the state of the remote repository.

The usual way to update the list of remote branches is to use git fetch. This automatically gets an updated list of branches from the remote and sets up remote branches in the local repository, also fetching any commit objects you may be missing.

However, by default, git fetch does not remove remote branches that no longer have a counterpart branch on the remote. In order to do that, you explicitly need to prune the list of remote branches:

git fetch --prune

This will automatically get rid of remote branches that no longer exist on the remote. Afterwards, git branch -r will show you an updated list of branches that really exist on the remote: And those you can delete using git push.

That being said, in order to use git push --delete, you need to specify the name of the branch on the remote repository; not the name of your remote branch. So to delete the branch test (represented by your remote branch origin/test), you would use git push origin --delete test.

TypeError: $.browser is undefined

I placed the following html in my code and this cleared up the $.browser error

<script src=""></script>

Hope this helps u

mysql extract year from date format

This should work:

SELECT YEAR(STR_TO_DATE(subdateshow, '%m/%d/%Y')) FROM table;


SELECT YEAR(STR_TO_DATE('01/17/2009', '%m/%d/%Y'));  /* shows "2009" */

Reading a List from properties file and load with spring annotation @Value

In my case of a list of integers works this:

private List<Integer> listOfIntegers;

Property file:


XML Parsing - Read a Simple XML File and Retrieve Values

I usually use XmlDocument for this. The interface is pretty straight forward:

var doc = new XmlDocument();

You can access nodes similar to a dictionary:

var tasks = doc["Tasks"];

and loop over all children of a node.

Diff files present in two different directories

If it's GNU diff then you should just be able to point it at the two directories and use the -r option.

Otherwise, try using

for i in $(\ls -d ./dir1/*); do diff ${i} dir2; done

N.B. As pointed out by Dennis in the comments section, you don't actually need to do the command substitution on the ls. I've been doing this for so long that I'm pretty much doing this on autopilot and substituting the command I need to get my list of files for comparison.

Also I forgot to add that I do '\ls' to temporarily disable my alias of ls to GNU ls so that I lose the colour formatting info from the listing returned by GNU ls.

simple Jquery hover enlarge

Demo Link

Tutorial Link

This will show original dimensions of Image on Hover using jQuery custom code


        <ul class="thumb">
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/1.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/2.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/3.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/4.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/5.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/6.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/7.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/8.jpg)"></div>
                <a href="javascript:void(0)">
                    <div class="thumbnail-wrap" style="background-image:url(./images/9.jpg)"></div>


    ul.thumb {
        float: left;
        list-style: none;
        padding: 10px;
        width: 360px;
        margin: 80px;

    ul.thumb li {
        margin: 0;
        padding: 5px;
        float: left;
        position: relative;
        /* Set the absolute positioning base coordinate */
        width: 110px;
        height: 110px;

    ul.thumb li .thumbnail-wrap {
        width: 100px;
        height: 100px;
        /* Set the small thumbnail size */
        -ms-interpolation-mode: bicubic;
        /* IE Fix for Bicubic Scaling */
        border: 1px solid #ddd;
        padding: 5px;
        position: absolute;
        left: 0;
        top: 0;
        background-size: cover;
        background-repeat: no-repeat;

        -webkit-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
        -moz-box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);
        box-shadow: inset -3px 0px 40px -15px rgba(0, 0, 0, 1);


    ul.thumb li .thumbnail-wrap.hover {
        -webkit-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
        -moz-box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);
        box-shadow: -2px 1px 22px -1px rgba(0, 0, 0, 0.75);

    .thumnail-zoomed-wrapper {
        display: none;
        position: fixed;
        top: 0px;
        left: 0px;
        height: 100vh;
        width: 100%;
        background: rgba(0, 0, 0, 0.2);
        z-index: 99;

    .thumbnail-zoomed-image {
        margin: auto;
        display: block;
        text-align: center;
        margin-top: 12%;

    .thumbnail-zoomed-image img {
        max-width: 100%;

    .close-image-zoom {
        z-index: 10;
        float: right;
        margin: 10px;
        cursor: pointer;


        var perc = 40;
        $("ul.thumb li").hover(function () {
            $("ul.thumb li").find(".thumbnail-wrap").css({
                "z-index": "0"
                "z-index": "10"
            var imageval = $(this).find(".thumbnail-wrap").css("background-image").slice(5);
            var img;
            var thisImage = this;
            img = new Image();
            img.src = imageval.substring(0, imageval.length - 2);
            img.onload = function () {
                var imgh = this.height * (perc / 100);
                var imgw = this.width * (perc / 100);
                        marginTop: "-" + (imgh / 4) + "px",
                        marginLeft: "-" + (imgw / 4) + "px",
                        width: imgw + "px",
                        height: imgh + "px"
                    }, 200);
        }, function () {
            var thisImage = this;
                    marginTop: "0",
                    marginLeft: "0",
                    top: "0",
                    left: "0",
                    width: "100px",
                    height: "100px",
                    padding: "5px"
                }, 400, function () {});

        //Show thumbnail in fullscreen
        $("ul.thumb li .thumbnail-wrap").click(function () {

            var imageval = $(this).css("background-image").slice(5);
            imageval = imageval.substring(0, imageval.length - 2);
            $(".thumbnail-zoomed-image img").attr({
                src: imageval
            return false;

        //Close fullscreen preview
        $(".thumnail-zoomed-wrapper .close-image-zoom").click(function () {
            return false;

enter image description here

Magento addFieldToFilter: Two fields, match as OR, not AND

I also tried to get the field1 = 'a' OR field2 = 'b'

Your code didn't work for me.

Here is my solution

$results = Mage::getModel('xyz/abc')->getCollection();

$results->getSelect()->where("keywords like '%foo%' or additional_keywords  like '%bar%'");


echo json_encode($results->toArray());

It gives me

SELECT name, keywords FROM abc WHERE keywords like '%foo%' OR additional_keywords like '%bar%'.

It is maybe not the "magento's way" but I was stuck 5 hours on that.

Hope it will help

How to both read and write a file in C#

This thread seems to answer your question : simultaneous-read-write-a-file

Basically, what you need is to declare two FileStream, one for read operations, the other for write operations. Writer Filestream needs to open your file in 'Append' mode.

Use and meaning of "in" in an if statement?

Since you claim to be used to JavaScript:

The Python in operator is similar to the JavaScript in operator.

Here's some JavaScript:

var d = {1: 2, 3: 4};
if (1 in d) {

And the equivalent Python:

d = {1: 2, 3: 4}
if 1 in d:

With objects/dicts, they're nearly identical, both checking whether 1 is a key of the object/dict. The big difference, of course, is that JavaScript is sloppily-typed, so '1' in d would be just as true.

With arrays/lists, they're very different. A JS array is an object, and its indexes are the keys, so 1 in [3, 4, 5] will be true. A Python list is completely different from a dict, and its in operator checks the values, not the indexes, which tends to be more useful. And Python extends this behavior to all iterables.

With strings, they're even more different. A JS string isn't an object, so you will get a TypeError. But a Python str or unicode will check whether the other operand is a substring. (This means 1 in '123' is illegal, because 1 can't be a substring of anything, but '1' in '123' is true.)

With objects as objects, in JS there is of course no distinction, but in Python, objects are instances of classes, not dicts. So, in JS, 1 in d will be true for an object if it has a member or method named '1', but in Python, it's up to your class what it means—Python will call d.__contains__(1), then, if that fails, it tries to use your object as an utterable (by calling its __iter__, and, if that fails, by trying to index it with integers starting from 0).

Also, note that JS's in, because it's actually checking for object membership, does the usual JS method-resolution-order search, while Python's in, because it's checking for keys of a dict, members of a sequence, etc., does no such thing. So, technically, it's probably a bit closer to the hasOwnProperty method than the in operator.

How to use: while not in

Using sets will be screaming fast if you have any volume of data

If you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.

MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])

while not MyList.isdisjoint(MyOper):
    print "No boolean Operator"

How to center form in bootstrap 3

Wrap whatever you are trying to center around this div.

<div class="position-absolute top-50 start-50 translate-middle"></div>

jQuery: more than one handler for same event

You should be able to use chaining to execute the events in sequence, e.g.:

  .bind('click',function(event) {
  .bind('click',function(event) {
    alert('Hello again!');
  .bind('click',function(event) {
    alert('Hello yet again!');

I guess the below code is doing the same

      .click(function(event) {
      .click(function(event) {
        alert('Hello again!');
      .click(function(event) {
        alert('Hello yet again!');


TFM also says:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

How to enable scrolling on website that disabled scrolling?

You can paste the following code to the console to scroll up/down using the a/z keyboard keys. If you want to set your own keys you can visit this page to get the keycodes

function KeyPress(e) {
  var evtobj = window.event? event : e
  if (evtobj.keyCode == 90) {
    window.scrollBy(0, 100) 
  if (evtobj.keyCode == 65) {
    window.scrollBy(0, -100) 

document.onkeydown = KeyPress;

AngularJS - Multiple ng-view in single template

I believe you can accomplish it by just having single ng-view. In the main template you can have ng-include sections for sub views, then in the main controller define model properties for each sub template. So that they will bind automatically to ng-include sections. This is same as having multiple ng-view

You can check the example given in ng-include documentation

in the example when you change the template from dropdown list it changes the content. Here assume you have one main ng-view and instead of manually selecting sub content by selecting drop down, you do it as when main view is loaded.

Comparing Arrays of Objects in JavaScript

Here is my attempt, using Node's assert module + npm package object-hash.

I suppose that you would like to check if two arrays contain the same objects, even if those objects are ordered differently between the two arrays.

var assert = require('assert');
var hash = require('object-hash');

var obj1 = {a: 1, b: 2, c: 333},
    obj2 = {b: 2, a: 1, c: 444},
    obj3 = {b: "AAA", c: 555},
    obj4 = {c: 555, b: "AAA"};

var array1 = [obj1, obj2, obj3, obj4];
var array2 = [obj3, obj2, obj4, obj1]; // [obj3, obj3, obj2, obj1] should work as well

// calling assert.deepEquals(array1, array2) at this point FAILS (throws an AssertionError)
// even if array1 and array2 contain the same objects in different order,
// because array1[0].c !== array2[0].c

// sort objects in arrays by their hashes, so that if the arrays are identical,
// their objects can be compared in the same order, one by one
var array1 = sortArrayOnHash(array1);
var array2 = sortArrayOnHash(array2);

// then, this should output "PASS"
try {
    assert.deepEqual(array1, array2);
} catch (e) {

// You could define as well something like Array.prototype.sortOnHash()...
function sortArrayOnHash(array) {
    return array.sort(function(a, b) {
        return hash(a) > hash(b);

Updating the list view when the adapter data changes




((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

Group list by values

>>> import collections
>>> D1 = collections.defaultdict(list)
>>> for element in L1:
...     D1[element[1]].append(element[0])
>>> L2 = D1.values()
>>> print L2
[['A', 'C'], ['B'], ['D', 'E']]

How to start Spyder IDE on Windows

I had the same problem after setting up my environment on Windows 10. I have Python 3.6.2 x64 installed as my default Python distribution and is in my PATH so I can launch from cmd prompt.

I installed PyQt5 (pip install pyqt5) and Spyder (pip install spyder) which both installed w/out error and included all of the necessary dependencies.

To launch Spyder, I created a simple Python script (

# Spyder Start Script
from import start

Then I created a Windows batch file (Spyder.bat):

@echo off
python c:\<path_to_Spyder_py>\

Lastly, I created a shortcut on my desktop which launches Spyder.bat and updated the icon to one I downloaded from the Spyder github project.

Works like a charm for me.

Is it possible to cast a Stream in Java 8?

Late to the party, but I think it is a useful answer.

flatMap would be the shortest way to do it.

Stream.of(objects).flatMap(o->(o instanceof Client)?Stream.of((Client)o):Stream.empty())

If o is a Client then create a Stream with a single element, otherwise use the empty stream. These streams will then be flattened into a Stream<Client>.

Accessing an SQLite Database in Swift

You can use this library in Swift for SQLite


SQLite Demo using Swift with SQLDataAccess class written in Swift

Adding to Your Project

You only need three files to add to your project * SQLDataAccess.swift * DataConstants.swift * Bridging-Header.h Bridging-Header must be set in your Xcode's project 'Objective-C Bridging Header' under 'Swift Compiler - General'

Examples for Use

Just follow the code in ViewController.swift to see how to write simple SQL with SQLDataAccess.swift First you need to open the SQLite Database your dealing with

    let db = SQLDataAccess.shared
    let opened = db.openConnection(copyFile:true)

If openConnection succeeded, now you can do a simple insert into Table AppInfo

    //Insert into Table AppInfo
    let status = db.executeStatement("insert into AppInfo (name,value,descrip,date) values(?,?,?,?)",
        //Read Table AppInfo into an Array of Dictionaries
        let results = db.getRecordsForQuery("select * from AppInfo ")
        NSLog("Results = \(results)")

See how simple that was!

The first term in db.executeStatement is your SQL as String, all the terms that follow are a variadic argument list of type Any, and are your parameters in an Array. All these terms are separated by commas in your list of SQL arguments. You can enter Strings, Integers, Date’s, and Blobs right after the sequel statement since all of these terms are considered to be parameters for the sequel. The variadic argument array just makes it convenient to enter all your sequel in just one executeStatement or getRecordsForQuery call. If you don’t have any parameters, don’t enter anything after your SQL.

The results array is an Array of Dictionary’s where the ‘key’ is your tables column name, and the ‘value’ is your data obtained from SQLite. You can easily iterate through this array with a for loop or print it out directly or assign these Dictionary elements to custom data object Classes that you use in your View Controllers for model consumption.

    for dic in results as! [[String:AnyObject]] {
       print(“result = \(dic)”)

SQLDataAccess will store, text, double, float, blob, Date, integer and long long integers. For Blobs you can store binary, varbinary, blob.

For Text you can store char, character, clob, national varying character, native character, nchar, nvarchar, varchar, variant, varying character, text.

For Dates you can store datetime, time, timestamp, date.

For Integers you can store bigint, bit, bool, boolean, int2, int8, integer, mediumint, smallint, tinyint, int.

For Doubles you can store decimal, double precision, float, numeric, real, double. Double has the most precision.

You can even store Nulls of type Null.

In ViewController.swift a more complex example is done showing how to insert a Dictionary as a 'Blob'. In addition SQLDataAccess understands native Swift Date() so you can insert these objects with out converting, and it will convert them to text and store them, and when retrieved convert them back from text to Date.

Of course the real power of SQLite is it's Transaction capability. Here you can literally queue up 400 SQL statements with parameters and insert them all at once which is really powerful since it's so fast. ViewController.swift also shows you an example of how to do this. All you're really doing is creating an Array of Dictionaries called 'sqlAndParams', in this Array your storing Dictionaries with two keys 'SQL' for the String sequel statement or query, and 'PARAMS' which is just an Array of native objects SQLite understands for that query. Each 'sqlParams' which is an individual Dictionary of sequel query plus parameters is then stored in the 'sqlAndParams' Array. Once you've created this array, you just call.

    let status = db.executeTransaction(sqlAndParams)
        //Read Table AppInfo into an Array of Dictionaries for the above Transactions
        let results = db.getRecordsForQuery("select * from AppInfo ")
        NSLog("Results = \(results)")

In addition all executeStatement and getRecordsForQuery methods can be done with simple String for SQL query and an Array for the parameters needed by the query.

    let sql : String = "insert into AppInfo (name,value,descrip) values(?,?,?)"
    let params : Array = ["SQLiteDemo","1.0.0","unencrypted"]
    let status = db.executeStatement(sql, withParameters: params)
        //Read Table AppInfo into an Array of Dictionaries for the above Transactions
        let results = db.getRecordsForQuery("select * from AppInfo ")
        NSLog("Results = \(results)")

An Objective-C version also exists and is called the same SQLDataAccess, so now you can choose to write your sequel in Objective-C or Swift. In addition SQLDataAccess will also work with SQLCipher, the present code isn't setup yet to work with it, but it's pretty easy to do, and an example of how to do this is actually in the Objective-C version of SQLDataAccess.

SQLDataAccess is a very fast and efficient class, and can be used in place of CoreData which really just uses SQLite as it's underlying data store without all the CoreData core data integrity fault crashes that come with CoreData.

How to decrypt the password generated by wordpress

This is one of the proposed solutions found in the article Jacob mentioned, and it worked great as a manual way to change the password without having to use the email reset.

  1. In the DB table wp_users, add a key, like abc123 to the user_activation column.
  2. Visit
  3. You will be prompted to enter a new password.

Conversion from byte array to base64 and back

The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.

The way you get your original array back is by using Convert.FromBase64String:

 byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);