Programs & Examples On #Agrep

An approximate grep for fuzzy matching

How do I include a pipe | in my linux find -exec command?

I found that running a string shell command (sh -c) works best, for example:

find -name 'file_*' -follow -type f -exec bash -c "zcat \"{}\" | agrep -dEOE 'grep'" \;

Terminating idle mysql connections

Manual cleanup:

You can KILL the processid.

mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id      | User       | Host              | db   | Command | Time  | State | Info                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www  | Sleep   | 25946 |       | NULL                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+

mysql> kill 1193777;

But:

  • the php application might report errors (or the webserver, check the error logs)
  • don't fix what is not broken - if you're not short on connections, just leave them be.

Automatic cleaner service ;)

Or you configure your mysql-server by setting a shorter timeout on wait_timeout and interactive_timeout

mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| connect_timeout          | 5     |
| delayed_insert_timeout   | 300   |
| innodb_lock_wait_timeout | 50    |
| interactive_timeout      | 28800 |
| net_read_timeout         | 30    |
| net_write_timeout        | 60    |
| slave_net_timeout        | 3600  |
| table_lock_wait_timeout  | 50    |
| wait_timeout             | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)

Set with:

set global wait_timeout=3;
set global interactive_timeout=3;

(and also set in your configuration file, for when your server restarts)

But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...

Overriding the java equals() method - not working?

Slightly off-topic to your question, but it's probably worth mentioning anyway:

Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.

I also agree that you should use the @Override annotation whenever you're overriding equals (or any other method).

How to sort a List of objects by their date (java collections, List<Object>)

In your compare method, o1 and o2 are already elements in the movieItems list. So, you should do something like this:

Collections.sort(movieItems, new Comparator<Movie>() {
    public int compare(Movie m1, Movie m2) {
        return m1.getDate().compareTo(m2.getDate());
    }
});

Capturing browser logs with Selenium WebDriver using Java

Starting with Firefox 65 an about:config flag exists now so console API calls like console.log() land in the output stream and thus the log file (see (https://github.com/mozilla/geckodriver/issues/284#issuecomment-458305621).

profile = new FirefoxProfile();
profile.setPreference("devtools.console.stdout.content", true);

Implementing IDisposable correctly

The following example shows the general best practice to implement IDisposable interface. Reference

Keep in mind that you need a destructor(finalizer) only if you have unmanaged resources in your class. And if you add a destructor you should suppress Finalization in the Dispose, otherwise it will cause your objects resides in memory for two garbage cycles (Note: Read how Finalization works). Below example elaborate all above.

public class DisposeExample
{
    // A base class that implements IDisposable. 
    // By implementing IDisposable, you are announcing that 
    // instances of this type allocate scarce resources. 
    public class MyResource: IDisposable
    {
        // Pointer to an external unmanaged resource. 
        private IntPtr handle;
        // Other managed resource this class uses. 
        private Component component = new Component();
        // Track whether Dispose has been called. 
        private bool disposed = false;

        // The class constructor. 
        public MyResource(IntPtr handle)
        {
            this.handle = handle;
        }

        // Implement IDisposable. 
        // Do not make this method virtual. 
        // A derived class should not be able to override this method. 
        public void Dispose()
        {
            Dispose(true);
            // This object will be cleaned up by the Dispose method. 
            // Therefore, you should call GC.SupressFinalize to 
            // take this object off the finalization queue 
            // and prevent finalization code for this object 
            // from executing a second time.
            GC.SuppressFinalize(this);
        }

        // Dispose(bool disposing) executes in two distinct scenarios. 
        // If disposing equals true, the method has been called directly 
        // or indirectly by a user's code. Managed and unmanaged resources 
        // can be disposed. 
        // If disposing equals false, the method has been called by the 
        // runtime from inside the finalizer and you should not reference 
        // other objects. Only unmanaged resources can be disposed. 
        protected virtual void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called. 
            if(!this.disposed)
            {
                // If disposing equals true, dispose all managed 
                // and unmanaged resources. 
                if(disposing)
                {
                    // Dispose managed resources.
                    component.Dispose();
                }

                // Call the appropriate methods to clean up 
                // unmanaged resources here. 
                // If disposing is false, 
                // only the following code is executed.
                CloseHandle(handle);
                handle = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;

            }
        }

        // Use interop to call the method necessary 
        // to clean up the unmanaged resource.
        [System.Runtime.InteropServices.DllImport("Kernel32")]
        private extern static Boolean CloseHandle(IntPtr handle);

        // Use C# destructor syntax for finalization code. 
        // This destructor will run only if the Dispose method 
        // does not get called. 
        // It gives your base class the opportunity to finalize. 
        // Do not provide destructors in types derived from this class.
        ~MyResource()
        {
            // Do not re-create Dispose clean-up code here. 
            // Calling Dispose(false) is optimal in terms of 
            // readability and maintainability.
            Dispose(false);
        }
    }
    public static void Main()
    {
        // Insert code here to create 
        // and use the MyResource object.
    }
}

fatal: could not read Username for 'https://github.com': No such file or directory

Double check the repository URL, Github will prompt you to login if the repo doesn't exist.

I'm guessing this is probably to check if it's a private repo you have access to. Possibly to make it harder to enumerate private repos. But this is all conjecture. /shrug

SameSite warning Chrome 77

This console warning is not an error or an actual problem — Chrome is just spreading the word about this new standard to increase developer adoption.

It has nothing to do with your code. It is something their web servers will have to support.

Release date for a fix is February 4, 2020 per: https://www.chromium.org/updates/same-site

February, 2020: Enforcement rollout for Chrome 80 Stable: The SameSite-by-default and SameSite=None-requires-Secure behaviors will begin rolling out to Chrome 80 Stable for an initial limited population starting the week of February 17, 2020, excluding the US President’s Day holiday on Monday. We will be closely monitoring and evaluating ecosystem impact from this initial limited phase through gradually increasing rollouts.

For the full Chrome release schedule, see here.

I solved same problem by adding in response header

response.setHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");

SameSite prevents the browser from sending the cookie along with cross-site requests. The main goal is mitigating the risk of cross-origin information leakage. It also provides some protection against cross-site request forgery attacks. Possible values for the flag are Lax or Strict.

SameSite cookies explained here

Please refer this before applying any option.

Hope this helps you.

Maven Unable to locate the Javac Compiler in:

I tried all of the above suggestions, which did not work for me, but I found how to fix the error in my case.

The following steps made the project compile succesfully:

In project explorer, right-click on project, select “properties” In the tree on the right, go to Java build path. Select the tab “libraries”. Click “Add library”. Select JRE system library. Click next. Select radio button Alternate JRE. Click “installed JRE’s”. Select the JRE with the right version. Click Appy and close. In the next screen, click finish. In the properties window, click Apply and close. In the project explorer, right-click your pom.xml and select run as > maven build In the goal textbox, write “install”. Click Run.

This made the project build succesfully in my case.

Executing multiple commands from a Windows cmd script

Note that you don't need semicolons in batch files. And the reason why you need to use call is that mvn itself is a batch file and batch files need to call each other with call, otherwise control does not return to the caller.

How to Convert double to int in C?

I suspect you don't actually have that problem - I suspect you've really got:

double a = callSomeFunction();
// Examine a in the debugger or via logging, and decide it's 3669.0

// Now cast
int b = (int) a;
// Now a is 3668

What makes me say that is that although it's true that many decimal values cannot be stored exactly in float or double, that doesn't hold for integers of this kind of magnitude. They can very easily be exactly represented in binary floating point form. (Very large integers can't always be exactly represented, but we're not dealing with a very large integer here.)

I strongly suspect that your double value is actually slightly less than 3669.0, but it's being displayed to you as 3669.0 by whatever diagnostic device you're using. The conversion to an integer value just performs truncation, not rounding - hence the issue.

Assuming your double type is an IEEE-754 64-bit type, the largest value which is less than 3669.0 is exactly

3668.99999999999954525264911353588104248046875

So if you're using any diagnostic approach where that value would be shown as 3669.0, then it's quite possible (probable, I'd say) that this is what's happening.

Check if PHP session has already started

This is what I use to determine if a session has started. By using empty and isset as follows:

if (empty($_SESSION)  && !isset($_SESSION))  {
    session_start();
}

Convert an image to grayscale

To summarize a few items here: There are some pixel-by-pixel options that, while being simple just aren't fast.

@Luis' comment linking to: (archived) https://web.archive.org/web/20110827032809/http://www.switchonthecode.com/tutorials/csharp-tutorial-convert-a-color-image-to-grayscale is superb.

He runs through three different options and includes timings for each.

Kotlin - Property initialization using "by lazy" vs. "lateinit"

If you are using Spring container and you want to initialize non-nullable bean field, lateinit is better suited.

    @Autowired
    lateinit var myBean: MyBean

How to check if user input is not an int value

Taken from a related post:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    }
    // only got here if we didn't return false
    return true;
}

How to implement my very own URI scheme on Android

This is very possible; you define the URI scheme in your AndroidManifest.xml, using the <data> element. You setup an intent filter with the <data> element filled out, and you'll be able to create your own scheme. (More on intent filters and intent resolution here.)

Here's a short example:

<activity android:name=".MyUriActivity">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="myapp" android:host="path" />
    </intent-filter>
</activity>

As per how implicit intents work, you need to define at least one action and one category as well; here I picked VIEW as the action (though it could be anything), and made sure to add the DEFAULT category (as this is required for all implicit intents). Also notice how I added the category BROWSABLE - this is not necessary, but it will allow your URIs to be openable from the browser (a nifty feature).

Add a new element to an array without specifying the index in Bash

If your array is always sequential and starts at 0, then you can do this:

array[${#array[@]}]='foo'

# gets the length of the array
${#array_name[@]}

If you inadvertently use spaces between the equal sign:

array[${#array[@]}] = 'foo'

Then you will receive an error similar to:

array_name[3]: command not found

How to locate the git config file in Mac

The solution to the problem is:

  1. Find the .gitconfig file

  2. [user] name = 1wQasdTeedFrsweXcs234saS56Scxs5423 email = [email protected] [credential] helper = osxkeychain [url ""] insteadOf = git:// [url "https://"] [url "https://"] insteadOf = git://

there would be a blank url="" replace it with url="https://"

[user]
    name = 1wQasdTeedFrsweXcs234saS56Scxs5423
    email = [email protected]
[credential]
    helper = osxkeychain
[url "https://"]
    insteadOf = git://
[url "https://"]
[url "https://"]
    insteadOf = git://

This will work :)

Happy Bower-ing

Image steganography that could survive jpeg compression

Quite a few applications seem to implement Steganography on JPEG, so it's feasible:

http://www.jjtc.com/Steganography/toolmatrix.htm

Here's an article regarding a relevant algorithm (PM1) to get you started:

http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)

You can get the script that SSMS provides by doing the following:

  1. Right-click on a database in SSMS and choose delete
  2. In the dialog, check the checkbox for "Close existing connections."
  3. Click the Script button at the top of the dialog.

The script will look something like this:

USE [master]
GO
ALTER DATABASE [YourDatabaseName] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
DROP DATABASE [YourDatabaseName]
GO

Convert string to float?

Using Float.parseFloat()?

class Test {
    public static void main(String[] args) {
        String s = "3.14";
        float f = Float.parseFloat(s);
        System.out.println(f);
    }
}

Hash Map in Python

In python you would use a dictionary.

It is a very important type in python and often used.

You can create one easily by

name = {}

Dictionaries have many methods:

# add entries:
>>> name['first'] = 'John'
>>> name['second'] = 'Doe'
>>> name
{'first': 'John', 'second': 'Doe'}

# you can store all objects and datatypes as value in a dictionary
# as key you can use all objects and datatypes that are hashable
>>> name['list'] = ['list', 'inside', 'dict']
>>> name[1] = 1
>>> name
{'first': 'John', 'second': 'Doe', 1: 1, 'list': ['list', 'inside', 'dict']}

You can not influence the order of a dict.

Center Div inside another (100% width) div

The below style to the inner div will center it.

margin: 0 auto;

How can one see the structure of a table in SQLite?

You can use the Firefox add-on called SQLite Manager to view the database's structure clearly.

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

A lot of these answers are pretty old, so I thought I would update with a solution that I think is helpful.

Our issue was similar to OP's, we upgraded 32 bit XP machines to 64 bit windows 7 and our application software that uses a 32 bit ODBC driver stopped being able to write to our database.

Turns out, there are two ODBC Data Source Managers, one for 32 bit and one for 64 bit. So I had to run the 32 bit version which is found in C:\Windows\SysWOW64\odbcad32.exe. Inside the ODBC Data Source Manager, I was able to go to the System DSN tab and Add my driver to the list using the Add button. (You can check the Drivers tab to see a list of the drivers you can add, if your driver isn't in this list then you may need to install it).

The next issue was the software that we ran was compiled to use 'Any CPU'. This would see the operating system was 64 bit, so it would look at the 64 bit ODBC Data Sources. So I had to force the program to compile as an x86 program, which then tells it to look at the 32 bit ODBC Data Sources. To set your program to x86, in Visual Studio go to your project properties and under the build tab at the top there is a platform drop down list, and choose x86. If you don't have the source code and can't compile the program as x86, you might be able to right click the program .exe and go to the compatibility tab and choose a compatibility that works for you.

Once I had the drivers added and the program pointing to the right drivers, everything worked like it use to. Hopefully this helps anyone working with older software.

php search array key and get value

The key is already the ... ehm ... key

echo $array[20120504];

If you are unsure, if the key exists, test for it

$key = 20120504;
$result = isset($array[$key]) ? $array[$key] : null;

Minor addition:

$result = @$array[$key] ?: null;

One may argue, that @ is bad, but keep it serious: This is more readable and straight forward, isn't?

Update: With PHP7 my previous example is possible without the error-silencer

$result = $array[$key] ?? null;

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Deny access to one specific folder in .htaccess

You can also put this IndexIgnore * at your root .htaccess file to disable file listing of all of your website directories including sub-dir

Python: Adding element to list while iterating

You could use the islice from itertools to create an iterator over a smaller portion of the list. Then you can append entries to the list without impacting the items you're iterating over:

islice(myarr, 0, len(myarr)-1)

Even better, you don't even have to iterate over all the elements. You can increment a step size.

MySQL DROP all tables, ignoring foreign keys

DB="your database name" \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=0" \
    && mysqldump --add-drop-table --no-data $DB | grep 'DROP TABLE' | grep -Ev "^$" | mysql $DB \
    && mysql $DB < "SET FOREIGN_KEY_CHECKS=1"

Remove Rows From Data Frame where a Row matches a String

Just use the == with the negation symbol (!). If dtfm is the name of your data.frame:

dtfm[!dtfm$C == "Foo", ]

Or, to move the negation in the comparison:

dtfm[dtfm$C != "Foo", ]

Or, even shorter using subset():

subset(dtfm, C!="Foo")

Data binding in React

There are actually people wanting to write with two-way binding, but React does not work in that way.

That's true, there are people who want to write with two-way data binding. And there's nothing fundamentally wrong with React preventing them from doing so. I wouldn't recommend them to use deprecated React mixin for that, though. Because it looks so much better with some third-party packages.

import { LinkedComponent } from 'valuelink'

class Test extends LinkedComponent {
    state = { a : "Hi there! I'm databinding demo!" };

    render(){
        // Bind all state members...
        const { a } = this.linkAll();

        // Then, go ahead. As easy as that.
        return (
             <input type="text" ...a.props />
        )
    }
}

The thing is that the two-way data binding is the design pattern in React. Here's my article with a 5-minute explanation on how it works

Does a foreign key automatically create an index?

A foreign key is a constraint, a relationship between two tables - that has nothing to do with an index per se.

But it is a known fact that it makes a lot of sense to index all the columns that are part of any foreign key relationship, because through a FK-relationship, you'll often need to lookup a relating table and extract certain rows based on a single value or a range of values.

So it makes good sense to index any columns involved in a FK, but a FK per se is not an index.

Check out Kimberly Tripp's excellent article "When did SQL Server stop putting indexes on Foreign Key columns?".

Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?

There is a whole new approach that you may want to consider if what you're after is the power and performance of stored procedures, and the rapid development that tools like Entity Framework provide.

I've taken SQL+ for a test drive on a small project, and it is really something special. You basically add what amounts to comments to your SQL routines, and those comments provide instructions to a code generator, which then builds a really nice object oriented class library based on the actual SQL routine. Kind of like entity framework in reverse.

Input parameters become part of an input object, output parameters and result sets become part of an output object, and a service component provides the method calls.

If you want to use stored procedures, but still want rapid development, you might want to have a look at this stuff.

How to find longest string in the table column data

SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) ASC LIMIT 1;
SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) DESC LIMIT 1;

CSS :selected pseudo class similar to :checked, but for <select> elements

This worked for me :

select option {
   color: black;
}
select:not(:checked) {
   color: gray;
}

Python truncate a long string

Even more concise:

data = data[:75]

If it is less than 75 characters there will be no change.

How do I name the "row names" column in r

The tibble package now has a dedicated function that converts row names to an explicit variable.

library(tibble)
rownames_to_column(mtcars, var="das_Auto") %>% head

Gives:

           das_Auto  mpg cyl disp  hp drat    wt  qsec vs am gear carb
1         Mazda RX4 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
2     Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
3        Datsun 710 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
4    Hornet 4 Drive 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
5 Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
6           Valiant 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

How to specify the bottom border of a <tr>?

You should define the style on the td element like so:

<html>
<head>
    <style type="text/css">
        .bb
        {
            border-bottom: solid 1px black;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td>
                Test 1
            </td>
        </tr>
        <tr>
            <td class="bb">
                Test 2
            </td>
        </tr>
    </table>
</body>
</html>

Using Python to execute a command on every file in a folder

The new recommend way in Python3 is to use pathlib:

from pathlib import Path

mydir = Path("path/to/my/dir")
for file in mydir.glob('*.mp4'):
    print(file.name)
    # do your stuff

Instead of *.mp4 you can use any filter, even a recursive one like **/*.mp4. If you want to use more than one extension, you can simply iterate all with * or **/* (recursive) and check every file's extension with file.name.endswith(('.mp4', '.webp', '.avi', '.wmv', '.mov'))

Add & delete view from Layout

Kotlin Reusable Extension Solution

Simplify removal

Add this extension:

myView.removeSelf()

fun View?.removeSelf() {
    this ?: return
    val parent = parent as? ViewGroup ?: return
    parent.removeView(this)
}

Simplify addition

Here are a few options:

// Built-in
myViewGroup.addView(myView)

// Null-safe extension
fun ViewGroup?.addView(view: View?) {
    this ?: return
    view ?: return
    addView(view)
}

// Reverse addition
myView.addTo(myViewGroup)

fun View?.addTo(parent: ViewGroup?) {
    this ?: return
    parent ?: return
    parent.addView(this)
}

How do I discard unstaged changes in Git?

To do a permanent discard: git reset --hard

To save changes for later: git stash

How to prevent SIGPIPEs (or handle them properly)

In this post I described possible solution for Solaris case when neither SO_NOSIGPIPE nor MSG_NOSIGNAL is available.

Instead, we have to temporarily suppress SIGPIPE in the current thread that executes library code. Here's how to do this: to suppress SIGPIPE we first check if it is pending. If it does, this means that it is blocked in this thread, and we have to do nothing. If the library generates additional SIGPIPE, it will be merged with the pending one, and that's a no-op. If SIGPIPE is not pending then we block it in this thread, and also check whether it was already blocked. Then we are free to execute our writes. When we are to restore SIGPIPE to its original state, we do the following: if SIGPIPE was pending originally, we do nothing. Otherwise we check if it is pending now. If it does (which means that out actions have generated one or more SIGPIPEs), then we wait for it in this thread, thus clearing its pending status (to do this we use sigtimedwait() with zero timeout; this is to avoid blocking in a scenario where malicious user sent SIGPIPE manually to a whole process: in this case we will see it pending, but other thread may handle it before we had a change to wait for it). After clearing pending status we unblock SIGPIPE in this thread, but only if it wasn't blocked originally.

Example code at https://github.com/kroki/XProbes/blob/1447f3d93b6dbf273919af15e59f35cca58fcc23/src/libxprobes.c#L156

Division in Python 2.7. and 3.3

In Python 2.x, make sure to have at least one operand of your division in float. Multiple ways you may achieve this as the following examples:

20. / 15
20 / float(15)

Resetting MySQL Root Password with XAMPP on Localhost

If you indeed forgot the root password to the MySQL server, you need to start it with the option skip-grant-tables. Search for the appropriate Ini-File my.ini (C:\ProgramData\MySQL Server ... or something like this) and add skip-grant-tables to the section [mysqld] like so:

[mysqld]
skip-grant-tables

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

Why call super() in a constructor?

A call to your parent class's empty constructor super() is done automatically when you don't do it yourself. That's the reason you've never had to do it in your code. It was done for you.

When your superclass doesn't have a no-arg constructor, the compiler will require you to call super with the appropriate arguments. The compiler will make sure that you instantiate the class correctly. So this is not something you have to worry about too much.

Whether you call super() in your constructor or not, it doesn't affect your ability to call the methods of your parent class.

As a side note, some say that it's generally best to make that call manually for reasons of clarity.

Npm Error - No matching version found for

first, in C:\users\your PC write npm uninstall -g create-react-app then, create your project folder with npx create-react-app folder-name.

How to Write text file Java

You can try a Java Library. FileUtils, It has many functions that write to Files.

How do I specify unique constraint for multiple columns in MySQL?

If you want to avoid duplicates in future. Create another column say id2.

UPDATE tablename SET id2 = id;

Now add the unique on two columns:

alter table tablename add unique index(columnname, id2);

Call removeView() on the child's parent first

Ok, call me paranoid but I suggest:

  final android.view.ViewParent parent = view.getParent ();

  if (parent instanceof android.view.ViewManager)
  {
     final android.view.ViewManager viewManager = (android.view.ViewManager) parent;

     viewManager.removeView (view);
  } // if

casting without instanceof just seems wrong. And (thanks IntelliJ IDEA for telling me) removeView is part of the ViewManager interface. And one should not cast to a concrete class when a perfectly suitable interface is available.

How to change line width in IntelliJ (from 120 character)

Be aware that need to change both location:

File > Settings... > Editor > Code Style > "Hard Wrap at"

and

File > Settings... > Editor > Code Style > (your language) > Wrapping and Braces > Hard wrap at

Checking if a list is empty with LINQ

I would make one small addition to the code you seem to have settled on: check also for ICollection, as this is implemented even by some non-obsolete generic classes as well (i.e., Queue<T> and Stack<T>). I would also use as instead of is as it's more idiomatic and has been shown to be faster.

public static bool IsEmpty<T>(this IEnumerable<T> list)
{
    if (list == null)
    {
        throw new ArgumentNullException("list");
    }

    var genericCollection = list as ICollection<T>;
    if (genericCollection != null)
    {
        return genericCollection.Count == 0;
    }

    var nonGenericCollection = list as ICollection;
    if (nonGenericCollection != null)
    {
        return nonGenericCollection.Count == 0;
    }

    return !list.Any();
}

java SSL and cert keystore

you can also mention the path at runtime using -D properties as below

-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks

In my apache spark application, I used to provide the path of certs and keystore using --conf option and extraJavaoptions in spark-submit as below

--conf 'spark.driver.extraJavaOptions= 
-Djavax.net.ssl.trustStore=/home/user/SSL/my-cacerts 
-Djavax.net.ssl.keyStore=/home/user/SSL/server_keystore.jks' 

Changing button color programmatically

use jquery :  $("#id").css("background","red");

How do I get the opposite (negation) of a Boolean in Python?

Python has a "not" operator, right? Is it not just "not"? As in,

  return not bool

Get URL query string parameters

For getting each node in the URI, you can use function explode() to $_SERVER['REQUEST_URI']. If you want to get strings without knowing if it is passed or not. you may use the function I defined myself to get query parameters from $_REQUEST (as it works both for POST and GET params).

function getv($key, $default = '', $data_type = '')
{
    $param = (isset($_REQUEST[$key]) ? $_REQUEST[$key] : $default);

    if (!is_array($param) && $data_type == 'int') {
        $param = intval($param);
    }

    return $param;
}

There might be some cases when we want to get query parameters converted into Integer type, so I added the third parameter to this function.

Viewing all `git diffs` with vimdiff

git config --global diff.tool vimdiff
git config --global difftool.prompt false

Typing git difftool yields the expected behavior.

Navigation commands,

  • :qa in vim cycles to the next file in the changeset without saving anything.

Aliasing (example)

git config --global alias.d difftool

.. will let you type git d to invoke vimdiff.

Advanced use-cases,

  • By default, git calls vimdiff with the -R option. You can override it with git config --global difftool.vimdiff.cmd 'vimdiff "$LOCAL" "$REMOTE"'. That will open vimdiff in writeable mode which allows edits while diffing.
  • :wq in vim cycles to the next file in the changeset with changes saved.

Failed to install *.apk on device 'emulator-5554': EOF

When it shows the red writing - the error , don't close the emulator - leave it as is and run the application again.

Remove credentials from Git

Update Actually useHttpPath is a git configuration, which should work for all GCMs. Corrected.

Summary of The Original Question

  • working with git on Windows
  • working on multiple repositories on GitHub
  • wrong credentials used for another GitHub repository

Although the title says "Remove credentials", the description leads me to the assumption that you may have multiple accounts on GitHub, e.g. for job-related vs. private projects. (At least that issue made me find this topic.) If so read on, otherwise ignore the answer, but it may come in handy at some time.

Reason

Git Credential Managers (short GCM) like Microsoft's GCM for Windows store credentials per host by default. This can be verified by checking the Windows Credential Manager (see other answers how to access it on English, French and German Windows versions). So working with multiple accounts on the same host (here github.com) is not possible by default.

In October 2020 GCM for Windows got deprecated and superseeded by GCM Core. The information here still applies for the new GCM and it should even use the credentials stored by GCM for Windows.

Solution

Configure git to include the full path to the repository as additional information for each credential entry. Also documented on GCM for Windows.
I personally prefer to include the HTTP(S) [repository] path to be able to use a separate account for each and every repository.

For all possible hosts:

git config --global credential.useHttpPath true

For github.com only:

git config --global credential.github.com.useHttpPath true

Have a look at the GCM and git docs and maybe you want to specify something different.

Git Commit Messages: 50/72 Formatting

Is the maximum recommended title length really 50?

I have believed this for years, but as I just noticed the documentation of "git commit" actually states

$ git help commit | grep -C 1 50
      Though not required, it’s a good idea to begin the commit message with
      a single short (less than 50 character) line summarizing the change,
      followed by a blank line and then a more thorough description. The text

$  git version
git version 2.11.0

One could argue that "less then 50" can only mean "no longer than 49".

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

I found the answer!

I want to acknowledge the hard work of everyone in trying to find a better way to solve this problem, unfortunately because of a series of larger constraints I am unable to select them as the "answer" (I am voting them up because you deserve points for contributing).

The specific problem I was facing was a JavaScript onScoll event that was firing but a subsequent CSS update that wasn't causing IE8 (in standards mode) to redraw. Even stranger was the fact that in some pages it was redrawing while in others (with no obvious similarity) it wasn't. The solution in the end was to add the following CSS

#ActionBox {
  position: relative;
  float: right;
}

Here is an updated pastbin showing this (I added some more style to show how I am implementing this code). The IE "edit code" then "view output" bug fudgey talked about still occurs (but it seems to be a event binding issue unique to pastbin (and similar services)

I don't know why adding "float: right" allows IE8 to complete a redraw on an event that was already firing, but for some reason it does.

What is the use of ByteBuffer in Java?

Java IO using stream oriented APIs is performed using a buffer as temporary storage of data within user space. Data read from disk by DMA is first copied to buffers in kernel space, which is then transfer to buffer in user space. Hence there is overhead. Avoiding it can achieve considerable gain in performance.

We could skip this temporary buffer in user space, if there was a way directly to access the buffer in kernel space. Java NIO provides a way to do so.

ByteBuffer is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect() API on Buffer.

Java Documentation of Byte Buffer has useful information.

How to access SOAP services from iPhone

One word: Don't.

OK obviously that isn't a real answer. But still SOAP should be avoided at all costs. ;-) Is it possible to add a proxy server between the iPhone and the web service? Perhaps something that converts REST into SOAP for you?

You could try CSOAP, a SOAP library that depends on libxml2 (which is included in the iPhone SDK).

I've written my own SOAP framework for OSX. However it is not actively maintained and will require some time to port to the iPhone (you'll need to replace NSXML with TouchXML for a start)

ggplot2: sorting a plot

This seems to be what you're looking for:

g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()

The reorder() function will reorder your x axis items according to the value of variable.

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How to get the selected radio button value using js

Possibly not the most efficient way... but I have used an ID on each radio button (this is just because I'm not passing it as an actual form, it is just the raw fields).

I then call a function with a button, which checks each radio button to see if it is checked. It does this using the .checked function. If this is set to true I can change the value of another variable.

_x000D_
_x000D_
function createOutput() {_x000D_
  var order = "in";_x000D_
  if (document.getElementById('radio1').checked == true) {_x000D_
    order = "pre";_x000D_
  } else if (document.getElementById('radio2').checked == true) {_x000D_
    order = "in";_x000D_
  } else if (document.getElementById('radio3').checked == true) {_x000D_
    order = "post";_x000D_
  }_x000D_
  document.getElementById('outputBox').innerHTML = order;_x000D_
}
_x000D_
<input id="radio1" type="radio" name="order" value="preorder" />Preorder_x000D_
<input id="radio2" type="radio" name="order" value="inorder" checked="true" />Inorder_x000D_
<input id="radio3" type="radio" name="order" value="postorder" />Postorder_x000D_
<button onclick="createOutput();">Generate Output</button>_x000D_
<textarea id="outputBox" rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

Hope this is useful, in someway,

Beanz

In Python, how do you convert a `datetime` object to seconds?

I tried the standard library's calendar.timegm and it works quite well:

# convert a datetime to milliseconds since Epoch
def datetime_to_utc_milliseconds(aDateTime):
    return int(calendar.timegm(aDateTime.timetuple())*1000)

Ref: https://docs.python.org/2/library/calendar.html#calendar.timegm

HTTP POST with URL query parameters -- good idea or not?

If your action is not idempotent, then you MUST use POST. If you don't, you're just asking for trouble down the line. GET, PUT and DELETE methods are required to be idempotent. Imagine what would happen in your application if the client was pre-fetching every possible GET request for your service – if this would cause side effects visible to the client, then something's wrong.

I agree that sending a POST with a query string but without a body seems odd, but I think it can be appropriate in some situations.

Think of the query part of a URL as a command to the resource to limit the scope of the current request. Typically, query strings are used to sort or filter a GET request (like ?page=1&sort=title) but I suppose it makes sense on a POST to also limit the scope (perhaps like ?action=delete&id=5).

How to tell bash that the line continues on the next line

\ does the job. @Guillaume's answer and @George's comment clearly answer this question. Here I explains why The backslash has to be the very last character before the end of line character. Consider this command:

   mysql -uroot \
   -hlocalhost      

If there is a space after \, the line continuation will not work. The reason is that \ removes the special meaning for the next character which is a space not the invisible line feed character. The line feed character is after the space not \ in this example.

How to run an android app in background?

You can probably start a Service here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.

UDPATE

You can use START_STICKY to make your Service running continuously.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

jQuery Dialog Box

I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.

The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.

So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!

<script type="text/javascript"> 
        jQuery(document).ready( function(){       
            jQuery("#myButton").click( showDialog );

            //variable to reference window
            $myWindow = jQuery('#myDiv');

            //instantiate the dialog
            $myWindow.dialog({ height: 350,
                width: 400,
                modal: true,
                position: 'center',
                autoOpen:false,
                title:'Hello World',
                overlay: { opacity: 0.5, background: 'black'}
                });
            }

        );
    //function to show dialog   
    var showDialog = function() {
        //if the contents have been hidden with css, you need this
        $myWindow.show(); 
        //open the dialog
        $myWindow.dialog("open");
        }

    //function to close dialog, probably called by a button in the dialog
    var closeDialog = function() {
        $myWindow.dialog("close");
    }


</script>
</head>

<body>

<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
    <p>I am a modal dialog</p>
</div>

Autocompletion in Vim

I recently discovered a project called OniVim, which is an electron-based front-end for NeoVim that comes with very nice autocomplete for several languages out of the box, and since it's basically just a wrapper around NeoVim, you have the full power of vim at your disposal if the GUI doesn't meet your needs. It's still in early development, but it is rapidly improving and there is a really active community around it. I have been using vim for over 10 years and started giving Oni a test drive a few weeks ago, and while it does have some bugs here and there it hasn't gotten in my way. I would strongly recommend it to new vim users who are still getting their vim-fingers!

enter image description here

OniVim: https://www.onivim.io/

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

People using Java 9 include this dependency:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

How to make google spreadsheet refresh itself every 1 minute?

I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.

How to solve java.lang.NullPointerException error?

Just a shot in the dark(since you did not share the compiler initialization code with us): the way you retrieve the compiler causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools hence, results in NPE.

Thread-safe List<T> property

Looking at the original sample one may guess that the intention was to be able to simply replace the list with the new one. The setter on the property tells us about it.

The Micrisoft's Thread-Safe Collections are for safely adding and removing items from collection. But if in the application logic you are intending to replace the collection with the new one, one may guess, again, that the adding and deleting functionality of the List is not required.

If this is the case then, the simple answer would be to use IReadOnlyList interface:

 private IReadOnlyList<T> _readOnlyList = new List<T>();

    private IReadOnlyList<T> MyT
    {
       get { return _readOnlyList; }
       set { _readOnlyList = value; }
    }

One doesn't need to use any locking in this situation because there is no way to modify the collection. If in the setter the "_readOnlyList = value;" will be replaced by something more complicated then the lock could be required.

Accessing constructor of an anonymous class

That is not possible, but you can add an anonymous initializer like this:

final int anInt = ...;
Object a = new Class1()
{
  {
    System.out.println(anInt);
  }

  void someNewMethod() {
  }
};

Don't forget final on declarations of local variables or parameters used by the anonymous class, as i did it for anInt.

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Difference between Math.Floor() and Math.Truncate()

Try this, Examples:

Math.Floor() vs Math.Truncate()

Math.Floor(2.56) = 2
Math.Floor(3.22) = 3
Math.Floor(-2.56) = -3
Math.Floor(-3.26) = -4

Math.Truncate(2.56) = 2
Math.Truncate(2.00) = 2
Math.Truncate(1.20) = 1
Math.Truncate(-3.26) = -3
Math.Truncate(-3.96) = -3

Also Math.Round()

   Math.Round(1.6) = 2
   Math.Round(-8.56) = -9
   Math.Round(8.16) = 8
   Math.Round(8.50) = 8
   Math.Round(8.51) = 9

math.floor()

Returns the largest integer less than or equal to the specified number. MSDN system.math.floor

math.truncate()

Calculates the integral part of a number. MSDN system.math.truncate

Column count doesn't match value count at row 1

  1. you missed the comma between two values or column name
  2. you put extra values or an extra column name

How to check file MIME type with javascript before upload?

For anyone who's looking to not implement this themselves, Sindresorhus has create a utility that works in the browser and has the header-to-mime mappings for most documents you could want.

https://github.com/sindresorhus/file-type

You could combine Vitim.us's suggestion of only reading in the first X bytes to avoid loading everything into memory with using this utility (example in es6):

import fileType from 'file-type'; // or wherever you load the dependency

const blob = file.slice(0, fileType.minimumBytes);

const reader = new FileReader();
reader.onloadend = function(e) {
  if (e.target.readyState !== FileReader.DONE) {
    return;
  }

  const bytes = new Uint8Array(e.target.result);
  const { ext, mime } = fileType.fromBuffer(bytes);

  // ext is the desired extension and mime is the mimetype
};
reader.readAsArrayBuffer(blob);

How can I print a circular structure in a JSON-like format?

@RobW's answer is correct, but this is more performant ! Because it uses a hashmap/set:

const customStringify = function (v) {
  const cache = new Set();
  return JSON.stringify(v, function (key, value) {
    if (typeof value === 'object' && value !== null) {
      if (cache.has(value)) {
        // Circular reference found
        try {
          // If this value does not reference a parent it can be deduped
         return JSON.parse(JSON.stringify(value));
        }
        catch (err) {
          // discard key if value cannot be deduped
         return;
        }
      }
      // Store value in our set
      cache.add(value);
    }
    return value;
  });
};

Eclipse/Java code completion not working

In my case, Intellisense had only disappeared in a few classes in one project. It turned out this was because of a missing library on the build path (although it worked previously).

So definitely check all the errors or problems in Eclipse and try to find if a library may be missing

How do I remove the top margin in a web page?

I had this exact same problem. For me, this was the only thing that worked:

div.mainContainer { padding-top: 1px; }

It actually works with any number that's not zero. I really have no idea why this took care of it. I'm not that knowledgeable about CSS and HTML and it seems counterintuitive. Setting the body, html, h1 margins and paddings to 0 had no effect for me. I also had an h1 at the top of my page

What is "loose coupling?" Please provide examples

I'll use Java as an example. Let's say we have a class that looks like this:

public class ABC
{
   public void doDiskAccess() {...}
}

When I call the class, I'll need to do something like this:

ABC abc = new ABC();

abc. doDiskAccess();

So far, so good. Now let's say I have another class that looks like this:

public class XYZ
{
   public void doNetworkAccess() {...}
}

It looks exactly the same as ABC, but let's say it works over the network instead of on disk. So now let's write a program like this:

if(config.isNetwork()) new XYZ().doNetworkAccess();
else new ABC().doDiskAccess();

That works, but it's a bit unwieldy. I could simplify this with an interface like this:

public interface Runnable
{
    public void run();
}

public class ABC implements Runnable
{
   public void run() {...}
}

public class XYZ implements Runnable
{
   public void run() {...}
}

Now my code can look like this:

Runnable obj = config.isNetwork() ? new XYZ() : new ABC();

obj.run();

See how much cleaner and simpler to understand that is? We've just understood the first basic tenet of loose coupling: abstraction. The key from here is to ensure that ABC and XYZ do not depend on any methods or variables of the classes that call them. That allows ABC and XYZ to be completely independent APIs. Or in other words, they are "decoupled" or "loosely coupled" from the parent classes.

But what if we need communication between the two? Well, then we can use further abstractions like an Event Model to ensure that the parent code never needs to couple with the APIs you have created.

Put request with simple string as request body

Have you tried the following:

axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
    .then(function(response){
        console.log('saved successfully')
});

Reference: http://codeheaven.io/how-to-use-axios-as-your-http-client/

Check if a file exists with wildcard in shell script

Using new fancy shmancy features in ksh, bash, and zsh shells (this example doesn't handle spaces in filenames):

# Declare a regular array (-A will declare an associative array. Kewl!)
declare -a myarray=( /mydir/tmp*.txt )
array_length=${#myarray[@]}

# Not found if the 1st element of the array is the unexpanded string
# (ie, if it contains a "*")
if [[ ${myarray[0]} =~ [*] ]] ; then
   echo "No files not found"
elif [ $array_length -eq 1 ] ; then
   echo "File was found"
else
   echo "Files were found"
fi

for myfile in ${myarray[@]}
do
  echo "$myfile"
done

Yes, this does smell like Perl. Glad I didn't step in it ;)

How to properly highlight selected item on RecyclerView?

As noted in this linked question, setting listeners for viewHolders should be done in onCreateViewHolder. That said, the implementation below was originally aimed at multiple selection, but I threw a hack in the snippet to force single selection.(*1)

// an array of selected items (Integer indices) 
private final ArrayList<Integer> selected = new ArrayList<>();

// items coming into view
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    // each time an item comes into view, its position is checked
    // against "selected" indices
    if (!selected.contains(position)){
        // view not selected
        holder.parent.setBackgroundColor(Color.LTGRAY);
    }
    else
        // view is selected
        holder.parent.setBackgroundColor(Color.CYAN);
}

// selecting items
@Override
public boolean onLongClick(View v) {
        
        // select (set color) immediately.
        v.setBackgroundColor(Color.CYAN);

        // (*1)
        // forcing single selection here...
        if (selected.isEmpty()){
            selected.add(position); // (done - see note)
        }else {
            int oldSelected = selected.get(0);
            selected.clear(); // (*1)... and here.
            selected.add(position);
            // note: We do not notify that an item has been selected
            // because that work is done here.  We instead send
            // notifications for items which have been deselected.
            notifyItemChanged(oldSelected);
        }
        return false;
}

How do I execute a program using Maven?

In order to execute multiple programs, I also needed a profiles section:

<profiles>
  <profile>
    <id>traverse</id>
    <activation>
      <property>
        <name>traverse</name>
      </property>
    </activation>
    <build>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>exec-maven-plugin</artifactId>
          <configuration>
            <executable>java</executable>
            <arguments>
              <argument>-classpath</argument>
              <argument>org.dhappy.test.NeoTraverse</argument>
            </arguments>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </profile>
</profiles>

This is then executable as:

mvn exec:exec -Ptraverse

not:first-child selector

You can use your selector with :not like bellow you can use any selector inside the :not()

any_CSS_selector:not(any_other_CSS_selector){
    /*YOUR STYLE*/
}

you can use :not without parent selector as well.

   :not(:nth-child(2)){
        /*YOUR STYLE*/
   }

More examples

any_CSS_selector:not(:first-child){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:checked){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:last-child){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:last-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:first-of-type){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-of-type(2)){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-last-child(2)){
    /*YOUR STYLE*/
}
any_CSS_selector:not(:nth-child(2)){
    /*YOUR STYLE*/
}

AngularJS access parent scope from child controller

I've just checked

$scope.$parent.someProperty

works for me.

and it will be

{{$parent.someProperty}}

for the view.

Find (and kill) process locking port 3000 on Mac

Execute in command line on OS-X El Captain:

kill -kill `lsof -t -i tcp:3000`

Terse option of lsof returns just the PID.

How to create the pom.xml for a Java project with Eclipse

Right click on Project -> Add FrameWork Support -> Maven

How does Spring autowire by name when more than one matching bean is found?

You can use the @Qualifier annotation

From here

Fine-tuning annotation-based autowiring with qualifiers

Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:

class Main {
    private Country country;
    @Autowired
    @Qualifier("country")
    public void setCountry(Country country) {
        this.country = country;
    }
}

This will use the UK add an id to USA bean and use that if you want the USA.

Getting Python error "from: can't read /var/mail/Bio"

I ran into a similar error

"from: can't read /var/mail/django.test.utils"

when trying to run a command

>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()

in the tutorial at https://docs.djangoproject.com/en/1.8/intro/tutorial05/

after reading the answer by Tamás I realized I was not trying this command in the python shell but in the termnial (this can happen to those new to linux)

solution was to first enter in the python shell with the command python and when you get these >>> then run any python commands

Multiline TextBox multiple newline

Try this one

textBox1.Text = "Line1" + Environment.NewLine + "Line2";

Working fine for me...

How should I multiple insert multiple records?

When it are a lot of entries consider to use SqlBulkCopy. The performance is much faster than a series of single inserts.

Is it possible to Turn page programmatically in UIPageViewController?

Since I needed this as well, I'll go into more detail on how to do this.

Note: I assume you used the standard template form for generating your UIPageViewController structure - which has both the modelViewController and dataViewController created when you invoke it. If you don't understand what I wrote - go back and create a new project that uses the UIPageViewController as it's basis. You'll understand then.

So, needing to flip to a particular page involves setting up the various pieces of the method listed above. For this exercise, I'm assuming that it's a landscape view with two views showing. Also, I implemented this as an IBAction so that it could be done from a button press or what not - it's just as easy to make it selector call and pass in the items needed.

So, for this example you need the two view controllers that will be displayed - and optionally, whether you're going forward in the book or backwards.

Note that I merely hard-coded where to go to pages 4 & 5 and use a forward slip. From here you can see that all you need to do is pass in the variables that will help you get these items...

-(IBAction) flipToPage:(id)sender {

    // Grab the viewControllers at position 4 & 5 - note, your model is responsible for providing these.  
    // Technically, you could have them pre-made and passed in as an array containing the two items...

    DataViewController *firstViewController = [self.modelController viewControllerAtIndex:4 storyboard:self.storyboard];
    DataViewController *secondViewController = [self.modelController viewControllerAtIndex:5 storyboard:self.storyboard];

    //  Set up the array that holds these guys...

    NSArray *viewControllers = nil;

    viewControllers = [NSArray arrayWithObjects:firstViewController, secondViewController, nil];

    //  Now, tell the pageViewContoller to accept these guys and do the forward turn of the page.
    //  Again, forward is subjective - you could go backward.  Animation is optional but it's 
    //  a nice effect for your audience.

      [self.pageViewController setViewControllers:viewControllers direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:NULL];

    //  Voila' - c'est fin!  

}

How to copy a collection from one database to another in MongoDB

I know this question has been answered however I personally would not do @JasonMcCays answer due to the fact that cursors stream and this could cause an infinite cursor loop if the collection is still being used. Instead I would use a snapshot():

http://www.mongodb.org/display/DOCS/How+to+do+Snapshotted+Queries+in+the+Mongo+Database

@bens answer is also a good one and works well for hot backups of collections not only that but mongorestore does not need to share the same mongod.

if var == False

var = False
if not var: print 'learnt stuff'

How to set the context path of a web application in Tomcat 7.0

In Tomcat 8.X ,under tomcat home directory /conf/ folder in server.xml you can add <Context> tag under <Host> tag as shown below . But you have to restart the server in order to take effect

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

     <Context docBase="${catalina.base}\webapps\<Your App Directory Name>" path="<your app path you wish>" reloadable="true" />
  </Host>

OR if you are using Tomcat 7.X you can add context.xml file in WEB-INF folder in your project . The contents of the file i used is as shown . and it worked fine for me . you don't have to restart server in this case .

<?xml version="1.0" encoding="UTF-8"?>

<Context docBase="${catalina.base}\webapps\<My App Directory Name>" path="<your app path you wish>" reloadable="true" />

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

What is the difference between .text, .value, and .value2?

.Text is the formatted cell's displayed value; .Value is the value of the cell possibly augmented with date or currency indicators; .Value2 is the raw underlying value stripped of any extraneous information.

range("A1") = Date
range("A1").numberformat = "yyyy-mm-dd"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
2018-06-14
6/14/2018 
43265 

range("A1") = "abc"
range("A1").numberformat = "_(_(_(@"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
   abc
abc
abc

range("A1") = 12
range("A1").numberformat = "0 \m\m"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
12 mm
12
12

If you are processing the cell's value then reading the raw .Value2 is marginally faster than .Value or .Text. If you are locating errors then .Text will return something like #N/A as text and can be compared to a string while .Value and .Value2 will choke comparing their returned value to a string. If you have some custom cell formatting applied to your data then .Text may be the better choice when building a report.

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

If you have previously installed node using brew, then you will have a bunch of extra files that you should clean up before installing node "the right way". Plus, I had to add a few settings to my startup script to make things work smoothly.

I wrote a script to make this easy.

# filename:  install-nvm-npm-node
# author:    Lex Sheehan
# purpose:   To cleanly install NVM, NODE and NPM
# dependencies:  brew

NOW=$(date +%x\ %H:%M:%S)
CR=$'\n'
REV=$(tput rev)
OFF=$(tput sgr0)
BACKUP_DIR=$HOME/backups/nvm-npm-bower-caches/$NOW
MY_NAME=$(basename $0)
NODE_VER_TO_INSTALL=$1
if [ "$NODE_VER_TO_INSTALL" == "" ]; then
    NODE_VER_TO_INSTALL=v0.12.2
fi
if [ "`echo "$NODE_VER_TO_INSTALL" | cut -c1-1`" != "v" ]; then
    echo """$CR""Usage:   $ $MY_NAME <NODE_VERSION_TO_INSALL>"
    echo "Example: $ $MY_NAME v0.12.1"
    echo "Example: $ $MY_NAME $CR"
    exit 1
fi
echo """$CR""First, run:  $ brew update"
echo "Likely, you'll need to do what it suggests."
echo "Likely, you'll need to run: $ brew update$CR"
echo "To install latest node version, run the following command to get the latest version:  $ nvm ls-remote"
echo "... and pass the version number you want as the only param to $MY_NAME. $CR"
echo "Are you ready to install the latest version of nvm and npm and node version $NODE_VER_TO_INSTALL ?$CR"
echo "Press CTL+C to exit --or-- Enter to continue..."
read x

echo """$REV""Uninstalling nvm...$CR$OFF"
# Making backups, but in all likelyhood you'll just reinstall them (and won't need these backups)
if [ ! -d "$BACKUP_DIR" ]; then 
    echo "Creating directory to store $HOME/.nvm .npm and .bower cache backups: $BACKUP_DIR"
    mkdir -p $BACKUP_DIR
fi 
set -x
mv $HOME/.nvm   $BACKUP_DIR  2>/dev/null
mv $HOME/.npm   $BACKUP_DIR  2>/dev/null
mv $HOME/.bower $BACKUP_DIR  2>/dev/null
{ set +x; } &>/dev/null

echo "$REV""$CR""Uninstalling node...$CR$OFF"
echo "Enter your password to remove user some node-related /usr/local directories"
set -x
sudo rm -rf /usr/local/lib/node_modules
rm -rf /usr/local/lib/node
rm -rf /usr/local/include/node
rm -rf /usr/local/include/node_modules
rm /usr/local/bin/npm
rm /usr/local/lib/dtrace/node.d
rm -rf $HOME/.node
rm -rf $HOME/.node-gyp
rm /opt/local/bin/node
rm /opt/local/include/node
rm -rf /opt/local/lib/node_modules
rm -rf /usr/local/Cellar/nvm
brew uninstall node 2>/dev/null
{ set +x; } &>/dev/null

echo "$REV""$CR""Installing nvm...$CR$OFF"

echo "++brew install nvm"
brew install nvm 
echo '$(brew --prefix nvm)/nvm.sh'
source $(brew --prefix nvm)/nvm.sh

echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc):$CR$OFF"
echo "export NVM_DIR=\"\$(brew --prefix nvm)\"; [ -s \"\$NVM_DIR/nvm.sh\" ] && . \"\$NVM_DIR/nvm.sh\"$CR"
NVM_DIR="$(brew --prefix nvm)"

echo """$CR""Using nvm install node...$CR"
echo "++ nvm install $NODE_VER_TO_INSTALL"
nvm install $NODE_VER_TO_INSTALL
NODE_BINARY_PATH="`find /usr/local/Cellar/nvm -name node -type d|head -n 1`/$NODE_VER_TO_INSTALL/bin"
echo "$REV""$CR""Insert the following line in your startup script (ex: $HOME/.bashrc) and then restart your shell:$CR$OFF"
echo "export PATH=\$PATH:$NODE_BINARY_PATH:$HOME/.node/bin"

echo """$CR""Upgrading npm...$CR"
echo '++ install -g npm@latest'
npm install -g npm@latest
{ set +x; } &>/dev/null
echo "$REV""$CR""Insert following line in your $HOME/.npmrc file:$OFF"
echo """$CR""prefix=$HOME/.node$CR"
echo "Now, all is likley well if you can run the following without errors:  npm install -g grunt-cli$CR"
echo "Other recommended global installs: bower, gulp, yo, node-inspector$CR"

I wrote a short article here that details why this is "the right way".

If you need to install iojs, do so using nvm like this:

nvm install iojs-v1.7.1

To install brew, just see its home page.

See alexpods answer for the rest.

Function pointer as parameter

Replace void *disconnectFunc; with void (*disconnectFunc)(); to declare function pointer type variable. Or even better use a typedef:

typedef void (*func_t)(); // pointer to function with no args and void return
...
func_t fptr; // variable of pointer to function
...
void D::setDisconnectFunc( func_t func )
{
    fptr = func;
}

void D::disconnected()
{
    fptr();
    connected = false;
}

How to insert text into the textarea at the current cursor position?


_x000D_
_x000D_
function insertAtCaret(text) {_x000D_
  const textarea = document.querySelector('textarea')_x000D_
  textarea.setRangeText(_x000D_
    text,_x000D_
    textarea.selectionStart,_x000D_
    textarea.selectionEnd,_x000D_
    'end'_x000D_
  )_x000D_
}_x000D_
_x000D_
setInterval(() => insertAtCaret('Hello'), 3000)
_x000D_
<textarea cols="60">Stack Overflow Stack Exchange Starbucks Coffee</textarea>
_x000D_
_x000D_
_x000D_

div background color, to change onhover

You can just put the anchor around the div.

<a class="big-link"><div>this is a div</div></a>

and then

a.big-link {
background-color: 888;
}
a.big-link:hover {
 background-color: f88;
}

error: ORA-65096: invalid common user or role name in oracle

In Oracle 12c and above, we have two types of databases:

  1. Container DataBase (CDB), and
  2. Pluggable DataBase (PDB).

If you want to create an user, you have two possibilities:

  1. You can create a "container user" aka "common user".
    Common users belong to CBDs as well as to current and future PDBs. It means they can perform operations in Container DBs or Pluggable DBs according to assigned privileges.

    create user c##username identified by password;

  2. You can create a "pluggable user" aka "local user".
    Local users belong only to a single PDB. These users may be given administrative privileges, but only for that PDB inside which they exist. For that, you should connect to pluggable datable like that:

    alter session set container = nameofyourpluggabledatabase;

    and there, you can create user like usually:

    create user username identified by password;

Don't forget to specify the tablespace(s) to use, it can be useful during import/export of your DBs. See this for more information about it https://docs.oracle.com/database/121/SQLRF/statements_8003.htm#SQLRF01503

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

What is the proper way to check if a string is empty in Perl?

The very concept of a "proper" way to do anything, apart from using CPAN, is non existent in Perl.

Anyways those are numeric operators, you should use

if($foo eq "")

or

if(length($foo) == 0)

Create a shortcut on Desktop

For Windows Vista/7/8/10, you can create a symlink instead via mklink.

Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");

Alternatively, call CreateSymbolicLink via P/Invoke.

Python != operation vs "is not"

== is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their __eq__ or __cmp__ methods.)

is is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can't influence the is operation.

You use is (and is not) for singletons, like None, where you don't care about objects that might want to pretend to be None or where you want to protect against objects breaking when being compared against None.

How to capture Curl output to a file?

A tad bit late, but I think the OP was looking for something like:

curl -K myfile.txt --trace-asci output.txt

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

The X-Frame-Options header is a security feature enforced at the browser level.

If you have control over your user base (IT dept for corp app), you could try something like a greasemonkey script (if you can a) deploy greasemonkey across everyone and b) deploy your script in a shared way)...

Alternatively, you can proxy their result. Create an endpoint on your server, and have that endpoint open a connection to the target endpoint, and simply funnel traffic backwards.

Count the Number of Tables in a SQL Server Database

You can use INFORMATION_SCHEMA.TABLES to retrieve information about your database tables.

As mentioned in the Microsoft Tables Documentation:

INFORMATION_SCHEMA.TABLES returns one row for each table in the current database for which the current user has permissions.

The following query, therefore, will return the number of tables in the specified database:

USE MyDatabase
SELECT COUNT(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

As of SQL Server 2008, you can also use sys.tables to count the the number of tables.

From the Microsoft sys.tables Documentation:

sys.tables returns a row for each user table in SQL Server.

The following query will also return the number of table in your database:

SELECT COUNT(*)
FROM sys.tables

Swift Error: Editor placeholder in source file

After Command + Shift + B, the project works fine.

How can I use console logging in Internet Explorer?

For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:

  • If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)

    window.console = { debug : function() {}, ...};

  • Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !

    window.console = { debug : window.console.log, ...};

Not sure about the assert support in various IE versions, but any suggestions are welcome.

How to use Angular4 to set focus by element id

Component

import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
... 

@ViewChild('input1', {static: false}) inputEl: ElementRef;
    
ngAfterViewInit() {
   setTimeout(() => this.inputEl.nativeElement.focus());
}

HTML

<input type="text" #input1>

What is the difference between baud rate and bit rate?

The bit rate is a measure of the number of bits that are transmitted per unit of time.

The baud rate, which is also known as symbol rate, measures the number of symbols that are transmitted per unit of time. A symbol typically consists of a fixed number of bits depending on what the symbol is defined as(for example 8bit or 9bit data). The baud rate is measured in symbols per second.

Take an example, where an ascii character 'R' is transmitted over a serial channel every one second.

The binary equivalent is 01010010.

So in this case, the baud rate is 1(one symbol transmitted per second) and the bit rate is 8 (eight bits are transmitted per second).

How to specify 64 bit integers in c

Try an LL suffix on the number, the compiler may be casting it to an intermediate type as part of the parse. See http://gcc.gnu.org/onlinedocs/gcc/Long-Long.html

long long int i2 = 0x0000444400004444LL;

Additionally, the the compiler is discarding the leading zeros, so 0x000044440000 is becoming 0x44440000, which is a perfectly acceptable 32-bit integer (which is why you aren't seeing any warnings prior to f2).

How to check if $_GET is empty?

I would use the following if statement because it is easier to read (and modify in the future)


if(!isset($_GET) || !is_array($_GET) || count($_GET)==0) {
   // empty, let's make sure it's an empty array for further reference
   $_GET=array();
   // or unset it 
   // or set it to null
   // etc...
}

how to access master page control from content page

In Content page you can access the label and set the text such as

Here 'lblStatus' is the your master page label ID

Label lblMasterStatus = (Label)Master.FindControl("lblStatus");

lblMasterStatus.Text  = "Meaasage from content page";

How to make custom error pages work in ASP.NET MVC 4

In web.config add this under system.webserver tag as below,

<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404"/>
  <remove statusCode="500"/>
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound"/>
  <error statusCode="500" responseMode="ExecuteURL"path="/Error/ErrorPage"/>
</httpErrors>

and add a controller as,

public class ErrorController : Controller
{
    //
    // GET: /Error/
    [GET("/Error/NotFound")]
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;

        return View();
    }

    [GET("/Error/ErrorPage")]
    public ActionResult ErrorPage()
    {
        Response.StatusCode = 500;

        return View();
    }
}

and add their respected views, this will work definitely I guess for all.

This solution I found it from: Neptune Century

Password Protect a SQLite DB. Is it possible?

Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.

Excel Validation Drop Down list using VBA

The accepted answer is correct but needs to be wary that this way imposes a 255 character limit. Better to reference an actual worksheet range object.

Parenthesis/Brackets Matching using Stack algorithm

  Check balanced parenthesis or brackets with stack-- 
  var excp = "{{()}[{a+b+b}][{(c+d){}}][]}";
   var stk = [];   
   function bracket_balance(){
      for(var i=0;i<excp.length;i++){
          if(excp[i]=='[' || excp[i]=='(' || excp[i]=='{'){
             stk.push(excp[i]);
          }else if(excp[i]== ']' && stk.pop() != '['){
             return false;
          }else if(excp[i]== '}' && stk.pop() != '{'){

            return false;
          }else if(excp[i]== ')' && stk.pop() != '('){

            return false;
          }
      }

      return true;
   }

  console.log(bracket_balance());
  //Parenthesis are balance then return true else false

How to programmatically take a screenshot on Android?

Note: works only for rooted phone

Programmatically, you can run adb shell /system/bin/screencap -p /sdcard/img.png as below

Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();    

then read img.png as Bitmap and use as your wish.

Calling the base class constructor from the derived class constructor

The base-class constructor is already automatically called by your derived-class constructor. In C++, if the base class has a default constructor (takes no arguments, can be auto-generated by the compiler!), and the derived-class constructor does not invoke another base-class constructor in its initialisation list, the default constructor will be called. I.e. your code is equivalent to:

class PetStore: public Farm
{
public :
    PetStore()
    : Farm()     // <---- Call base-class constructor in initialision list
    {
     idF=0;
    };
private:
    int idF;
    string nameF;
}

Enable 'xp_cmdshell' SQL Server

Right click server -->Facets-->Surface Area Configuration -->XPCmshellEnbled -->true enter image description here

How do I convert an ANSI encoded file to UTF-8 with Notepad++?

Maybe this is not the answer you needed, but I encountered similar problem, so I decided to put it here.

I needed to convert 500 xml files to UTF8 via Notepad++. Why Notepad++? When I used the option "Encode in UTF8" (many other converters use the same logic) it messed up all special characters, so I had to use "Convert to UTF8" explicitly.


Here some simple steps to convert multiple files via Notepad++ without messing up with special characters (for ex. diacritical marks).

  1. Run Notepad++ and then open menu Plugins->Plugin Manager->Show Plugin Manager
  2. Install Python Script. When plugin is installed, restart the application.
  3. Choose menu Plugins->Python Script->New script.
  4. Choose its name, and then past the following code:

convertToUTF8.py

import os
import sys
from Npp import notepad # import it first!

filePathSrc="C:\\Users\\" # Path to the folder with files to convert
for root, dirs, files in os.walk(filePathSrc):
    for fn in files: 
        if fn[-4:] == '.xml': # Specify type of the files
            notepad.open(root + "\\" + fn)      
            notepad.runMenuCommand("Encoding", "Convert to UTF-8")
            # notepad.save()
            # if you try to save/replace the file, an annoying confirmation window would popup.
            notepad.saveAs("{}{}".format(fn[:-4], '_utf8.xml')) 
            notepad.close()

After all, run the script

Input jQuery get old value before onchange and get value after on change

my solution is here

function getVal() {
    var $numInput =  $('input');
    var $inputArr = [];
    for(let i=0; i < $numInput.length ; i++ ) 
       $inputArr[$numInput[i].name] = $numInput[i].value;
    return $inputArr;
}
var $inNum =  getVal();
$('input').on('change', function() {
    // inNum is last Val
    $inNum =  getVal(); 
    // in here we update value of input
    let $val = this.value;      
});

Android Recyclerview GridLayoutManager column spacing

A Kotlin version I made based on the great answer by edwardaa

class RecyclerItemDecoration(private val spanCount: Int, private val spacing: Int) : RecyclerView.ItemDecoration() {

  override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {

    val spacing = Math.round(spacing * parent.context.resources.displayMetrics.density)
    val position = parent.getChildAdapterPosition(view)
    val column = position % spanCount

    outRect.left = spacing - column * spacing / spanCount
    outRect.right = (column + 1) * spacing / spanCount

    outRect.top = if (position < spanCount) spacing else 0
    outRect.bottom = spacing
  }

}

Force download a pdf link using javascript/ajax/jquery

Using Javascript you can download like this in a simple method

var oReq = new XMLHttpRequest();
// The Endpoint of your server 
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);

// Important to use the blob response type
oReq.responseType = "blob";

// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], { 
    type: 'application/pdf' 
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};

oReq.send();

Read the current full URL with React?

Just to add a little further documentation to this page - I have been struggling with this problem for a while.

As said above, the easiest way to get the URL is via window.location.href.

we can then extract parts of the URL through vanilla Javascript by using let urlElements = window.location.href.split('/')

We would then console.log(urlElements) to see the Array of elements produced by calling .split() on the URL.

Once you have found which index in the array you want to access, you can then assigned this to a variable

let urlElelement = (urlElements[0])

And now you can use the value of urlElement, which will be the specific part of your URL, wherever you want.

How to count lines in a document?

count number of lines and store result in variable use this command:

count=$(wc -l < file.txt) echo "Number of lines: $count"

Calling a user defined function in jQuery

jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 


$('#my-form').clear();

Passing route control with optional parameter after root in express?

That would work depending on what client.get does when passed undefined as its first parameter.

Something like this would be safer:

app.get('/:key?', function(req, res, next) {
    var key = req.params.key;
    if (!key) {
        next();
        return;
    }
    client.get(key, function(err, reply) {
        if(client.get(reply)) {
            res.redirect(reply);
        }
        else {
            res.render('index', {
                link: null
            });
        }
    });
});

There's no problem in calling next() inside the callback.

According to this, handlers are invoked in the order that they are added, so as long as your next route is app.get('/', ...) it will be called if there is no key.

How to compare two columns in Excel (from different sheets) and copy values from a corresponding column if the first two columns match?

As kmcamara discovered, this is exactly the kind of problem that VLOOKUP is intended to solve, and using vlookup is arguably the simplest of the alternative ways to get the job done.

In addition to the three parameters for lookup_value, table_range to be searched, and the column_index for return values, VLOOKUP takes an optional fourth argument that the Excel documentation calls the "range_lookup".

Expanding on deathApril's explanation, if this argument is set to TRUE (or 1) or omitted, the table range must be sorted in ascending order of the values in the first column of the range for the function to return what would typically be understood to be the "correct" value. Under this default behavior, the function will return a value based upon an exact match, if one is found, or an approximate match if an exact match is not found.

If the match is approximate, the value that is returned by the function will be based on the next largest value that is less than the lookup_value. For example, if "12AT8003" were missing from the table in Sheet 1, the lookup formulas for that value in Sheet 2 would return '2', since "12AT8002" is the largest value in the lookup column of the table range that is less than "12AT8003". (VLOOKUP's default behavior makes perfect sense if, for example, the goal is to look up rates in a tax table.)

However, if the fourth argument is set to FALSE (or 0), VLOOKUP returns a looked-up value only if there is an exact match, and an error value of #N/A if there is not. It is now the usual practice to wrap an exact VLOOKUP in an IFERROR function in order to catch the no-match gracefully. Prior to the introduction of IFERROR, no matches were checked with an IF function using the VLOOKUP formula once to check whether there was a match, and once to return the actual match value.

Though initially harder to master, deusxmach1na's proposed solution is a variation on a powerful set of alternatives to VLOOKUP that can be used to return values for a column or list to the left of the lookup column, expanded to handle cases where an exact match on more than one criterion is needed, or modified to incorporate OR as well as AND match conditions among multiple criteria.

Repeating kcamara's chosen solution, the VLOOKUP formula for this problem would be:

   =VLOOKUP(A1,Sheet1!A$1:B$600,2,FALSE)

Any way to select without causing locking in MySQL?

You may want to read this page of the MySQL manual. How a table gets locked is dependent on what type of table it is.

MyISAM uses table locks to achieve a very high read speed, but if you have an UPDATE statement waiting, then future SELECTS will queue up behind the UPDATE.

InnoDB tables use row-level locking, and you won't have the whole table lock up behind an UPDATE. There are other kind of locking issues associated with InnoDB, but you might find it fits your needs.

Replacing a character from a certain index

You can also Use below method if you have to replace string between specific index

def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
    try:
       singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
    except Exception as e:
        exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
        BuiltIn.log_to_console(exception)
    return singleLine

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

Correct way to initialize empty slice

Empty slice and nil slice are initialized differently in Go:

var nilSlice []int 
emptySlice1 := make([]int, 0)
emptySlice2 := []int{}

fmt.Println(nilSlice == nil)    // true
fmt.Println(emptySlice1 == nil) // false
fmt.Println(emptySlice2 == nil) // false

As for all three slices, len and cap are 0.

How to uninstall Jenkins?

Run the following commands to completely uninstall Jenkins from MacOS Sierra. You don't need to change anything, just run these commands.

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm /Library/LaunchDaemons/org.jenkins-ci.plist
sudo rm -rf /Applications/Jenkins '/Library/Application Support/Jenkins' /Library/Documentation/Jenkins
sudo rm -rf /Users/Shared/Jenkins
sudo rm -rf /var/log/jenkins
sudo rm -f /etc/newsyslog.d/jenkins.conf
sudo dscl . -delete /Users/jenkins
sudo dscl . -delete /Groups/jenkins
pkgutil --pkgs
grep 'org\.jenkins-ci\.'
xargs -n 1 sudo pkgutil --forget

Salam

Shah

Titlecase all entries into a form_for text field

You don't want to take care of normalizing your data in a view - what if the user changes the data that gets submitted? Instead you could take care of it in the model using the before_save (or the before_validation) callback. Here's an example of the relevant code for a model like yours:

class Place < ActiveRecord::Base   before_save do |place|     place.city = place.city.downcase.titleize     place.country = place.country.downcase.titleize   end end 

You can also check out the Ruby on Rails guide for more info.


To answer you question more directly, something like this would work:

<%= f.text_field :city, :value => (f.object.city ? f.object.city.titlecase : '') %>   

This just means if f.object.city exists, display the titlecase version of it, and if it doesn't display a blank string.

How to remove empty lines with or without whitespace in Python

Using regex:

if re.match(r'^\s*$', line):
    # line is empty (has only the following: \t\n\r and whitespace)

Using regex + filter():

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

As seen on codepad.

Failed to execute 'createObjectURL' on 'URL':

I had the same error for the MediaStream. The solution is set a stream to the srcObject.

From the docs:

Important: If you still have code that relies on createObjectURL() to attach streams to media elements, you need to update your code to simply set srcObject to the MediaStream directly.

Is there a way to instantiate a class by name in Java?

Two ways:

Method 1 - only for classes having a no-arg constructor

If your class has a no-arg constructor, you can get a Class object using Class.forName() and use the newInstance() method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).

For example:

Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();

Method 2

An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor object and call a newInstance() method on this object:

Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);

Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:

  • the JVM can't find or can't load your class
  • the class you're trying to instantiate doesn't have the right sort of constructors
  • the constructor itself threw an exception
  • the constructor you're trying to invoke isn't public
  • a security manager has been installed and is preventing reflection from occurring

Using Tkinter in python to edit the title bar

I found this works:

window = Tk()
window.title('Window')

Maybe this helps?

No submodule mapping found in .gitmodule for a path that's not a submodule

If you have:

  • removed the submodule using a simple rm instead of git rm;
  • removed the reference to the submodule in .gitmodules;
  • removed the reference in .git/config;

And you're still getting the error, what solved it for me was readding back an empty folder, where the submodule used to be. You can do this with:

mkdir -p path/to/your/submodule
touch path/to/your/submodule/.keep

.keep is just an empty file. git commit it and the error should disappear.

force browsers to get latest js and css files in asp.net application

For resolving this issue in my ASP.Net Ajax application, I created an extension and then called in the master page.

For more details, you can go through the link.

How can I quickly sum all numbers in a file?

C++ "one-liner":

#include <iostream>
#include <iterator>
#include <numeric>
using namespace std;

int main() {
    cout << accumulate(istream_iterator<int>(cin), istream_iterator<int>(), 0) << endl;
}

Detect if an element is visible with jQuery

if($('#testElement').is(':visible')){
    //what you want to do when is visible
}

Can I use return value of INSERT...RETURNING in another INSERT?

In line with the answer given by Denis de Bernardy..

If you want id to be returned afterwards as well and want to insert more things into Table2:

with rows as (
INSERT INTO Table1 (name) VALUES ('a_title') RETURNING id
)
INSERT INTO Table2 (val, val2, val3)
SELECT id, 'val2value', 'val3value'
FROM rows
RETURNING val

ASP.NET Web Application Message Box

not really. Server side code is happening on the server--- you can use javascript to display something to the user on the client side, but it obviously will only execute on the client side. This is the nature of a client server web technology. You're basically disconnected from the server when you get your response.

PHP mPDF save file as PDF

The Go trough this link state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

 $upload_dir = public_path(); 
             $filename = $upload_dir.'/testing7.pdf'; 
              $mpdf = new \Mpdf\Mpdf();
              //$test = $mpdf->Image($pro_image, 0, 0, 50, 50);

              $html ='<h1> Project Heading </h1>';
              $mail = ' <p> Project Heading </p> ';
              
              $mpdf->autoScriptToLang = true;
              $mpdf->autoLangToFont = true;
              $mpdf->WriteHTML($mail);

              $mpdf->Output($filename,'F'); 
              $mpdf->debug = true;

Example :

 $mpdf->Output($filename,'F');

Example #2

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');

// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);

How do I convert a float number to a whole number in JavaScript?

If you are using angularjs then simple solution as follows In HTML Template Binding

{{val | number:0}}

it will convert val into integer

go through with this link docs.angularjs.org/api/ng/filter/number

scrollTop jquery, scrolling to div with id?

try this:

$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();

How do I add a .click() event to an image?

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.js"></script> 
<script type="text/javascript" src="jquery-2.1.0.js"></script> 
<script type="text/javascript" >
function openOnImageClick()
{
//alert("Jai Sh Raam");
// document.getElementById("images").src = "fruits.jpg";
 var img = document.createElement('img');
 img.setAttribute('src', 'tiger.jpg');
  img.setAttribute('width', '200');
   img.setAttribute('height', '150');
  document.getElementById("images").appendChild(img);


}


</script>
</head>
<body>

<h1>Screen Shot View</h1>
<p>Click the Tiger to display the Image</p>

<div id="images" >
</div>

<img src="tiger.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />
<img src="Logo1.jpg" width="100" height="50" alt="unfinished bingo card" onclick="openOnImageClick()" />

</body>
</html> 

Running AMP (apache mysql php) on Android

On Google Play, PAW Server is the typical PHP server package ( contain Beanshell code ). You can put your webpages in the "html" folder. However, typical Beanshell code is not very familiar to be edited. On Android device, I recommend you to use SL4A and phpforandroid to build up Perl and PHP Server. Yet, they do not use MySQL as DATA base. You should be familiar with the Scripting Layer for Android (SL4A) platform. See this link for reference

Convert a String to a byte array and then back to the original String

Use [String.getBytes()][1] to convert to bytes and use [String(byte[] data)][2] constructor to convert back to string.

Border Height on CSS

For td elements line-height will successfully allow you to resize the border-height as SPrince mentioned.

For other elements such as list items, you can control the border height with line-height and the height of the actual element with margin-top and margin-bottom.

Here is a working example of both: http://jsfiddle.net/byronj/gLcqu6mg/

An example with list items:

li { 
    list-style: none; 
    padding: 0 10px; 
    display: inline-block;
    border-right: 1px solid #000; 
    line-height: 5px; 
    margin: 20px 0; 
}

<ul>
    <li>cats</li>
    <li>dogs</li>
    <li>birds</li>
    <li>swine!</li>
</ul>

PHP Excel Header

Just try to add exit; at the end of your PHP script.

ORA-00932: inconsistent datatypes: expected - got CLOB

The same error occurs also when doing SELECT DISTINCT ..., <CLOB_column>, ....

If this CLOB column contains values shorter than limit for VARCHAR2 in all the applicable rows you may use to_char(<CLOB_column>) or concatenate results of multiple calls to DBMS_LOB.SUBSTR(<CLOB_column>, ...).

Android soft keyboard covers EditText field

I believe that you can make it scroll by using the trackball, which might be achieved programmatically through selection methods eventually, but it's just an idea. I know that the trackball method typically works, but as for the exact way to do this and make it work from code, I do not sure.
Hope that helps.

log4j: Log output of a specific class to a specific appender

An example:

log4j.rootLogger=ERROR, logfile

log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false

log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n

Escape string Python for MySQL

{!a} applies ascii() and hence escapes non-ASCII characters like quotes and even emoticons. Here is an example

cursor.execute("UPDATE skcript set author='{!a}',Count='{:d}' where url='{!s}'".format(authors),leng,url))

Python3 docs

Java converting Image to BufferedImage

If you use Kotlin, you can add an extension method to Image in the same manner Sri Harsha Chilakapati suggests.

fun Image.toBufferedImage(): BufferedImage {
    if (this is BufferedImage) {
        return this
    }
    val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB)

    val graphics2D = bufferedImage.createGraphics()
    graphics2D.drawImage(this, 0, 0, null)
    graphics2D.dispose()

    return bufferedImage
}

And use it like this:

myImage.toBufferedImage()

How do I clear all options in a dropdown box?

Try

document.getElementsByTagName("Option").length=0

Or maybe look into the removeChild() function.

Or if you use jQuery framework.

$("DropList Option").each(function(){$(this).remove();});

ActionController::UnknownFormat

This problem happened with me and sovled by just add

 respond_to :html, :json

to ApplicationController file

You can Check Devise issues on Github: https://github.com/plataformatec/devise/issues/2667

Enter triggers button click

Pressing enter in a form's text field will, by default, submit the form. If you don't want it to work that way you have to capture the enter key press and consume it like you've done. There is no way around this. It will work this way even if there is no button present in the form.

Create mysql table directly from CSV file using the CSV Storage engine?

If someone is looking for a PHP solution see "PHP_MySQL_wrapper":

$db = new MySQL_wrapper(MySQL_HOST, MySQL_USER, MySQL_PASS, MySQL_DB);
$db->connect(); 

// this sample gets column names from first row of file
//$db->createTableFromCSV('test_files/countrylist.csv', 'csv_to_table_test');

// this sample generates column names 
$db->createTableFromCSV('test_files/countrylist1.csv', 'csv_to_table_test_no_column_names', ',', '"', '\\', 0, array(), 'generate', '\r\n');

/** Create table from CSV file and imports CSV data to Table with possibility to update rows while import.
 * @param   string      $file           - CSV File path
 * @param   string      $table          - Table name
 * @param   string      $delimiter      - COLUMNS TERMINATED BY (Default: ',')
 * @param   string      $enclosure      - OPTIONALLY ENCLOSED BY (Default: '"')
 * @param   string      $escape         - ESCAPED BY (Default: '\')
 * @param   integer     $ignore         - Number of ignored rows (Default: 1)
 * @param   array       $update         - If row fields needed to be updated eg date format or increment (SQL format only @FIELD is variable with content of that field in CSV row) $update = array('SOME_DATE' => 'STR_TO_DATE(@SOME_DATE, "%d/%m/%Y")', 'SOME_INCREMENT' => '@SOME_INCREMENT + 1')
 * @param   string      $getColumnsFrom - Get Columns Names from (file or generate) - this is important if there is update while inserting (Default: file)
 * @param   string      $newLine        - New line delimiter (Default: \n)
 * @return  number of inserted rows or false
 */
// function createTableFromCSV($file, $table, $delimiter = ',', $enclosure = '"', $escape = '\\', $ignore = 1, $update = array(), $getColumnsFrom = 'file', $newLine = '\r\n')

$db->close();

How can I split a text file using PowerShell?

A word of warning about some of the existing answers - they will run very slow for very big files. For a 1.6 GB log file I gave up after a couple of hours, realising it would not finish before I returned to work the next day.

Two issues: the call to Add-Content opens, seeks and then closes the current destination file for every line in the source file. Reading a little of the source file each time and looking for the new lines will also slows things down, but my guess is that Add-Content is the main culprit.

The following variant produces slightly less pleasant output: it will split files in the middle of lines, but it splits my 1.6 GB log in less than a minute:

$from = "C:\temp\large_log.txt"
$rootName = "C:\temp\large_log_chunk"
$ext = "txt"
$upperBound = 100MB


$fromFile = [io.file]::OpenRead($from)
$buff = new-object byte[] $upperBound
$count = $idx = 0
try {
    do {
        "Reading $upperBound"
        $count = $fromFile.Read($buff, 0, $buff.Length)
        if ($count -gt 0) {
            $to = "{0}.{1}.{2}" -f ($rootName, $idx, $ext)
            $toFile = [io.file]::OpenWrite($to)
            try {
                "Writing $count to $to"
                $tofile.Write($buff, 0, $count)
            } finally {
                $tofile.Close()
            }
        }
        $idx ++
    } while ($count -gt 0)
}
finally {
    $fromFile.Close()
}

How to set selected index JComboBox by value

setSelectedItem("banana"). You could have found it yourself by just reading the javadoc.

Edit: since you changed the question, I'll change my answer.

If you want to select the item having the "banana" label, then you have two solutions:

  1. Iterate through the items to find the one (or the index of the one) which has the given label, and then call setSelectedItem(theFoundItem) (or setSelectedIndex(theFoundIndex))
  2. Override equals and hashCode in ComboItem so that two ComboItem instances having the same name are equal, and simply use setSelectedItem(new ComboItem(anyNumber, "banana"));

set serveroutput on in oracle procedure

If you want to execute any procedure then firstly you have to set serveroutput on in the sqldeveloper work environment like.

->  SET SERVEROUTPUT ON;
-> BEGIN
dbms_output.put_line ('Hello World..');
dbms_output.put_line('Its displaying the values only for the Testing purpose');
END;
/

Get current rowIndex of table in jQuery

Since "$(this).parent().index();" and "$(this).parent('table').index();" don't work for me, I use this code instead:

$('td').click(function(){
   var row_index = $(this).closest("tr").index();
   var col_index = $(this).index();
});

SQL: set existing column as Primary Key in MySQL

ALTER TABLE your_table
ADD PRIMARY KEY (Drugid);

IndexError: too many indices for array

The message that you are getting is not for the default Exception of Python:

For a fresh python list, IndexError is thrown only on index not being in range (even docs say so).

>>> l = []
>>> l[1]
IndexError: list index out of range

If we try passing multiple items to list, or some other value, we get the TypeError:

>>> l[1, 2]
TypeError: list indices must be integers, not tuple

>>> l[float('NaN')]
TypeError: list indices must be integers, not float

However, here, you seem to be using matplotlib that internally uses numpy for handling arrays. On digging deeper through the codebase for numpy, we see:

static NPY_INLINE npy_intp
unpack_tuple(PyTupleObject *index, PyObject **result, npy_intp result_n)
{
    npy_intp n, i;
    n = PyTuple_GET_SIZE(index);
    if (n > result_n) {
        PyErr_SetString(PyExc_IndexError,
                        "too many indices for array");
        return -1;
    }
    for (i = 0; i < n; i++) {
        result[i] = PyTuple_GET_ITEM(index, i);
        Py_INCREF(result[i]);
    }
    return n;
}

where, the unpack method will throw an error if it the size of the index is greater than that of the results.

So, Unlike Python which raises a TypeError on incorrect Indexes, Numpy raises the IndexError because it supports multidimensional arrays.

Access localhost from the internet

Open the port where your system is running (sample 8080). Open the port everywhere... Modem, firewalls, etc etc etc.

THen, send your ip + port to the person who will use it.

sample: http://200.200.200.200:8080/mySite/

What is the difference between a data flow diagram and a flow chart?

A flow chart details the processes to follow. A DFD details the flow of data through a system.

In a flow chart, the arrows represent transfer of control (not data) between elements and the elements are instructions or decision (or I/O, etc).

In a DFD, the arrows are actually data transfer between the elements, which are themselves parts of a system.

Wikipedia has a good article on DFDs here.

Calculate mean across dimension in a 2D array

Here is a non-numpy solution:

>>> a = [[40, 10], [50, 11]]
>>> [float(sum(l))/len(l) for l in zip(*a)]
[45.0, 10.5]

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

As written by Dave Butenhof himself:

"The biggest of all the big problems with recursive mutexes is that they encourage you to completely lose track of your locking scheme and scope. This is deadly. Evil. It's the "thread eater". You hold locks for the absolutely shortest possible time. Period. Always. If you're calling something with a lock held simply because you don't know it's held, or because you don't know whether the callee needs the mutex, then you're holding it too long. You're aiming a shotgun at your application and pulling the trigger. You presumably started using threads to get concurrency; but you've just PREVENTED concurrency."

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

How can I make space between two buttons in same div?

if use Bootstrap, you can change with style like: If you want only in one page, then betwen head tags add .btn-group btn{margin-right:1rem;}

If is for all the web site add to css file

Catching an exception while using a Python 'with' statement

from __future__ import with_statement

try:
    with open( "a.txt" ) as f :
        print f.readlines()
except EnvironmentError: # parent of IOError, OSError *and* WindowsError where available
    print 'oops'

If you want different handling for errors from the open call vs the working code you could do:

try:
    f = open('foo.txt')
except IOError:
    print('error')
else:
    with f:
        print f.readlines()

Convert string into integer in bash script - "Leading Zero" number error

Here's an easy way, albeit not the prettiest way to get an int value for a string.

hour=`expr $hour + 0`

Example

bash-3.2$ hour="08"
bash-3.2$ hour=`expr $hour + 0`
bash-3.2$ echo $hour
8

Find the line number where a specific word appears with "grep"

Or You can use

   grep -n . file1 |tail -LineNumberToStartWith|grep regEx

This will take care of numbering the lines in the file

   grep -n . file1 

This will print the last-LineNumberToStartWith

   tail -LineNumberToStartWith

And finally it will grep your desired lines(which will include line number as in orignal file)

grep regEX

Understanding INADDR_ANY for socket programming

To bind socket with localhost, before you invoke the bind function, sin_addr.s_addr field of the sockaddr_in structure should be set properly. The proper value can be obtained either by

my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1")

or by

my_sockaddress.sin_addr.s_addr=htonl(INADDR_LOOPBACK);

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

MySQL INNER JOIN select only one row from second table

SELECT U.*, V.* FROM users AS U 
INNER JOIN (SELECT *
FROM payments
WHERE id IN (
SELECT MAX(id)
FROM payments
GROUP BY user_id
)) AS V ON U.id = V.user_id

This will get it working

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

Get current controller in view

Create base class for all controllers and put here name attribute:

public abstract class MyBaseController : Controller
{
    public abstract string Name { get; }
}

In view

@{
    var controller = ViewContext.Controller as MyBaseController;
    if (controller != null)
    {
       @controller.Name
    }
}

Controller example

 public class SampleController: MyBaseController 
    { 
      public override string Name { get { return "Sample"; } 
    }

How do I convert a column of text URLs into active hyperlinks in Excel?

Easiest way here

  • Highlight the whole column
  • click ''insert''
  • click ''Hyperlink''
  • click ''place in this document''
  • click ok
  • thats all

Java: recommended solution for deep cloning/copying an instance

Since version 2.07 Kryo supports shallow/deep cloning:

Kryo kryo = new Kryo();
SomeClass someObject = ...
SomeClass copy1 = kryo.copy(someObject);
SomeClass copy2 = kryo.copyShallow(someObject);

Kryo is fast, at the and of their page you may find a list of companies which use it in production.

SQL DELETE with JOIN another table for WHERE condition

Try this sample SQL scripts for easy understanding,

CREATE TABLE TABLE1 (REFNO VARCHAR(10))
CREATE TABLE TABLE2 (REFNO VARCHAR(10))

--TRUNCATE TABLE TABLE1
--TRUNCATE TABLE TABLE2

INSERT INTO TABLE1 SELECT 'TEST_NAME'
INSERT INTO TABLE1 SELECT 'KUMAR'
INSERT INTO TABLE1 SELECT 'SIVA'
INSERT INTO TABLE1 SELECT 'SUSHANT'

INSERT INTO TABLE2 SELECT 'KUMAR'
INSERT INTO TABLE2 SELECT 'SIVA'
INSERT INTO TABLE2 SELECT 'SUSHANT'

SELECT * FROM TABLE1
SELECT * FROM TABLE2

DELETE T1 FROM TABLE1 T1 JOIN TABLE2 T2 ON T1.REFNO = T2.REFNO

Your case is:

   DELETE pgc
     FROM guide_category pgc 
LEFT JOIN guide g
       ON g.id_guide = gc.id_guide 
    WHERE g.id_guide IS NULL

Excel - Sum column if condition is met by checking other column in same table

SUMIF didn't worked for me, had to use SUMIFS.

=SUMIFS(TableAmount,TableMonth,"January")

TableAmount is the table to sum the values, TableMonth the table where we search the condition and January, of course, the condition to meet.

Hope this can help someone!

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

FIXED

Give initial height of div and specify height in percentage in your style;

#map {
   height: 100%;
}

<div id="map" style="clear:both; height:200px;"></div>