Programs & Examples On #Htdocs

htdocs is the default web server software (Apache) folder visible from Internet.

Where to find htdocs in XAMPP Mac

you installed Xampp-VM (VirtualMachine), simply instead install one of the "normal" installations and everything runs fine.

'module' object has no attribute 'DataFrame'

The code presented here doesn't show this discrepancy, but sometimes I get stuck when invoking dataframe in all lower case.

Switching to camel-case (pd.DataFrame()) cleans up the problem.

Variable's memory size in Python

Regarding the internal structure of a Python long, check sys.int_info (or sys.long_info for Python 2.7).

>>> import sys
>>> sys.int_info
sys.int_info(bits_per_digit=30, sizeof_digit=4)

Python either stores 30 bits into 4 bytes (most 64-bit systems) or 15 bits into 2 bytes (most 32-bit systems). Comparing the actual memory usage with calculated values, I get

>>> import math, sys
>>> a=0
>>> sys.getsizeof(a)
24
>>> a=2**100
>>> sys.getsizeof(a)
40
>>> a=2**1000
>>> sys.getsizeof(a)
160
>>> 24+4*math.ceil(100/30)
40
>>> 24+4*math.ceil(1000/30)
160

There are 24 bytes of overhead for 0 since no bits are stored. The memory requirements for larger values matches the calculated values.

If your numbers are so large that you are concerned about the 6.25% unused bits, you should probably look at the gmpy2 library. The internal representation uses all available bits and computations are significantly faster for large values (say, greater than 100 digits).

Adding image to JFrame

As martijn-courteaux said, create a custom component it's the better option. In C# exists a component called PictureBox and I tried to create this component for Java, here is the code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;

public class JPictureBox extends JComponent {

    private Icon icon = null;
    private final Dimension dimension = new Dimension(100, 100);
    private Image image = null;
    private ImageIcon ii = null;
    private SizeMode sizeMode = SizeMode.STRETCH;
    private int newHeight, newWidth, originalHeight, originalWidth;

    public JPictureBox() {
        JPictureBox.this.setPreferredSize(dimension);
        JPictureBox.this.setOpaque(false);
        JPictureBox.this.setSizeMode(SizeMode.STRETCH);
    }

    @Override
    public void paintComponent(Graphics g) {
        if (ii != null) {
            switch (getSizeMode()) {
                case NORMAL:
                    g.drawImage(image, 0, 0, ii.getIconWidth(), ii.getIconHeight(), null);
                    break;
                case ZOOM:
                    aspectRatio();
                    g.drawImage(image, 0, 0, newWidth, newHeight, null);
                    break;
                case STRETCH:
                    g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
                    break;
                case CENTER:
                    g.drawImage(image, (int) (this.getWidth() / 2) - (int) (ii.getIconWidth() / 2), (int) (this.getHeight() / 2) - (int) (ii.getIconHeight() / 2), ii.getIconWidth(), ii.getIconHeight(), null);
                    break;
                default:
                    g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), null);
            }
        }
    }

    public Icon getIcon() {
        return icon;
    }

    public void setIcon(Icon icon) {
        this.icon = icon;
        ii = (ImageIcon) icon;
        image = ii.getImage();
        originalHeight = ii.getIconHeight();
        originalWidth = ii.getIconWidth();
    }

    public SizeMode getSizeMode() {
        return sizeMode;
    }

    public void setSizeMode(SizeMode sizeMode) {
        this.sizeMode = sizeMode;
    }

    public enum SizeMode {
        NORMAL,
        STRETCH,
        CENTER,
        ZOOM
    }

    private void aspectRatio() {
        if (ii != null) {
            newHeight = this.getHeight();
            newWidth = (originalWidth * newHeight) / originalHeight;
        }
    }

}

If you want to add an image, choose the JPictureBox, after that go to Properties and find "icon" property and select an image. If you want to change the sizeMode property then choose the JPictureBox, after that go to Properties and find "sizeMode" property, you can choose some values:

  • NORMAL value, the image is positioned in the upper-left corner of the JPictureBox.
  • STRETCH value causes the image to stretch or shrink to fit the JPictureBox.
  • ZOOM value causes the image to be stretched or shrunk to fit the JPictureBox; however, the aspect ratio in the original is maintained.
  • CENTER value causes the image to be centered in the client area.

If you want to learn more about this topic, you can check this video.

Also you can see the code on Gitlab or Github.

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

The reason your code doesn't work as expected is that it's actually doing something different from what you think it does.

Let's say you have something like the following:

stepOne()
.then(stepTwo, handleErrorOne)
.then(stepThree, handleErrorTwo)
.then(null, handleErrorThree);

To better understand what's happening, let's pretend this is synchronous code with try/catch blocks:

try {
    try {
        try {
            var a = stepOne();
        } catch(e1) {
            a = handleErrorOne(e1);
        }
        var b = stepTwo(a);
    } catch(e2) {
        b = handleErrorTwo(e2);
    }
    var c = stepThree(b);
} catch(e3) {
    c = handleErrorThree(e3);
}

The onRejected handler (the second argument of then) is essentially an error correction mechanism (like a catch block). If an error is thrown in handleErrorOne, it will be caught by the next catch block (catch(e2)), and so on.

This is obviously not what you intended.

Let's say we want the entire resolution chain to fail no matter what goes wrong:

stepOne()
.then(function(a) {
    return stepTwo(a).then(null, handleErrorTwo);
}, handleErrorOne)
.then(function(b) {
    return stepThree(b).then(null, handleErrorThree);
});

Note: We can leave the handleErrorOne where it is, because it will only be invoked if stepOne rejects (it's the first function in the chain, so we know that if the chain is rejected at this point, it can only be because of that function's promise).

The important change is that the error handlers for the other functions are not part of the main promise chain. Instead, each step has its own "sub-chain" with an onRejected that is only called if the step was rejected (but can not be reached by the main chain directly).

The reason this works is that both onFulfilled and onRejected are optional arguments to the then method. If a promise is fulfilled (i.e. resolved) and the next then in the chain doesn't have an onFulfilled handler, the chain will continue until there is one with such a handler.

This means the following two lines are equivalent:

stepOne().then(stepTwo, handleErrorOne)
stepOne().then(null, handleErrorOne).then(stepTwo)

But the following line is not equivalent to the two above:

stepOne().then(stepTwo).then(null, handleErrorOne)

Angular's promise library $q is based on kriskowal's Q library (which has a richer API, but contains everything you can find in $q). Q's API docs on GitHub could prove useful. Q implements the Promises/A+ spec, which goes into detail on how then and the promise resolution behaviour works exactly.

EDIT:

Also keep in mind that if you want to break out of the chain in your error handler, it needs to return a rejected promise or throw an Error (which will be caught and wrapped in a rejected promise automatically). If you don't return a promise, then wraps the return value in a resolve promise for you.

This means that if you don't return anything, you are effectively returning a resolved promise for the value undefined.

getElementById in React

You may have to perform a diff and put document.getElementById('name') code inside a condition, in case your component is something like this:

// using the new hooks API
function Comp(props) {
  const { isLoading, data } = props;
  useEffect(() => {
    if (data) {
      var name = document.getElementById('name').value;
    }
  }, [data]) // this diff is necessary

  if (isLoading) return <div>isLoading</div>
  return (
    <div id='name'>Comp</div>
  );
}

If diff is not performed then, you will get null.

Force encode from US-ASCII to UTF-8 (iconv)

Short Answer

  • file only guesses at the file encoding and may be wrong (especially in cases where special characters only appear late in large files).
  • you can use hexdump to look at bytes of non-7-bit-ASCII text and compare against code tables for common encodings (ISO 8859-*, UTF-8) to decide for yourself what the encoding is.
  • iconv will use whatever input/output encoding you specify regardless of what the contents of the file are. If you specify the wrong input encoding, the output will be garbled.
  • even after running iconv, file may not report any change due to the limited way in which file attempts to guess at the encoding. For a specific example, see my long answer.
  • 7-bit ASCII (aka US ASCII) is identical at a byte level to UTF-8 and the 8-bit ASCII extensions (ISO 8859-*). So if your file only has 7-bit characters, then you can call it UTF-8, ISO 8859-* or US ASCII because at a byte level they are all identical. It only makes sense to talk about UTF-8 and other encodings (in this context) once your file has characters outside the 7-bit ASCII range.

Long Answer

I ran into this today and came across your question. Perhaps I can add a little more information to help other people who run into this issue.

ASCII

First, the term ASCII is overloaded, and that leads to confusion.

7-bit ASCII only includes 128 characters (00-7F or 0-127 in decimal). 7-bit ASCII is also sometimes referred to as US-ASCII.

ASCII

UTF-8

UTF-8 encoding uses the same encoding as 7-bit ASCII for its first 128 characters. So a text file that only contains characters from that range of the first 128 characters will be identical at a byte level whether encoded with UTF-8 or 7-bit ASCII.

Codepage layout

ISO 8859-* and other ASCII Extensions

The term extended ASCII (or high ASCII) refers to eight-bit or larger character encodings that include the standard seven-bit ASCII characters, plus additional characters.

Extended ASCII

ISO 8859-1 (aka "ISO Latin 1") is a specific 8-bit ASCII extension standard that covers most characters for Western Europe. There are other ISO standards for Eastern European languages and Cyrillic languages. ISO 8859-1 includes characters like Ö, é, ñ and ß for German and Spanish.

"Extension" means that ISO 8859-1 includes the 7-bit ASCII standard and adds characters to it by using the 8th bit. So for the first 128 characters, it is equivalent at a byte level to ASCII and UTF-8 encoded files. However, when you start dealing with characters beyond the first 128, your are no longer UTF-8 equivalent at the byte level, and you must do a conversion if you want your "extended ASCII" file to be UTF-8 encoded.

ISO 8859 and proprietary adaptations

Detecting encoding with file

One lesson I learned today is that we can't trust file to always give correct interpretation of a file's character encoding.

file (command)

The command tells only what the file looks like, not what it is (in the case where file looks at the content). It is easy to fool the program by putting a magic number into a file the content of which does not match it. Thus the command is not usable as a security tool other than in specific situations.

file looks for magic numbers in the file that hint at the type, but these can be wrong, no guarantee of correctness. file also tries to guess the character encoding by looking at the bytes in the file. Basically file has a series of tests that helps it guess at the file type and encoding.

My file is a large CSV file. file reports this file as US ASCII encoded, which is WRONG.

$ ls -lh
total 850832
-rw-r--r--  1 mattp  staff   415M Mar 14 16:38 source-file
$ file -b --mime-type source-file
text/plain
$ file -b --mime-encoding source-file
us-ascii

My file has umlauts in it (ie Ö). The first non-7-bit-ascii doesn't show up until over 100k lines into the file. I suspect this is why file doesn't realize the file encoding isn't US-ASCII.

$ pcregrep -no '[^\x00-\x7F]' source-file | head -n1
102321:?

I'm on a Mac, so using PCRE's grep. With GNU grep you could use the -P option. Alternatively on a Mac, one could install coreutils (via Homebrew or other) in order to get GNU grep.

I haven't dug into the source-code of file, and the man page doesn't discuss the text encoding detection in detail, but I am guessing file doesn't look at the whole file before guessing encoding.

Whatever my file's encoding is, these non-7-bit-ASCII characters break stuff. My German CSV file is ;-separated and extracting a single column doesn't work.

$ cut -d";" -f1 source-file > tmp
cut: stdin: Illegal byte sequence
$ wc -l *
 3081673 source-file
  102320 tmp
 3183993 total

Note the cut error and that my "tmp" file has only 102320 lines with the first special character on line 102321.

Let's take a look at how these non-ASCII characters are encoded. I dump the first non-7-bit-ascii into hexdump, do a little formatting, remove the newlines (0a) and take just the first few.

$ pcregrep -o '[^\x00-\x7F]' source-file | head -n1 | hexdump -v -e '1/1 "%02x\n"'
d6
0a

Another way. I know the first non-7-bit-ASCII char is at position 85 on line 102321. I grab that line and tell hexdump to take the two bytes starting at position 85. You can see the special (non-7-bit-ASCII) character represented by a ".", and the next byte is "M"... so this is a single-byte character encoding.

$ tail -n +102321 source-file | head -n1 | hexdump -C -s85 -n2
00000055  d6 4d                                             |.M|
00000057

In both cases, we see the special character is represented by d6. Since this character is an Ö which is a German letter, I am guessing that ISO 8859-1 should include this. Sure enough, you can see "d6" is a match (ISO/IEC 8859-1).

Important question... how do I know this character is an Ö without being sure of the file encoding? The answer is context. I opened the file, read the text and then determined what character it is supposed to be. If I open it in Vim it displays as an Ö because Vim does a better job of guessing the character encoding (in this case) than file does.

So, my file seems to be ISO 8859-1. In theory I should check the rest of the non-7-bit-ASCII characters to make sure ISO 8859-1 is a good fit... There is nothing that forces a program to only use a single encoding when writing a file to disk (other than good manners).

I'll skip the check and move on to conversion step.

$ iconv -f iso-8859-1 -t utf8 source-file > output-file
$ file -b --mime-encoding output-file
us-ascii

Hmm. file still tells me this file is US ASCII even after conversion. Let's check with hexdump again.

$ tail -n +102321 output-file | head -n1 | hexdump -C -s85 -n2
00000055  c3 96                                             |..|
00000057

Definitely a change. Note that we have two bytes of non-7-bit-ASCII (represented by the "." on the right) and the hex code for the two bytes is now c3 96. If we take a look, seems we have UTF-8 now (c3 96 is the encoding of Ö in UTF-8) UTF-8 encoding table and Unicode characters

But file still reports our file as us-ascii? Well, I think this goes back to the point about file not looking at the whole file and the fact that the first non-7-bit-ASCII characters don't occur until late in the file.

I'll use sed to stick a Ö at the beginning of the file and see what happens.

$ sed '1s/^/Ö\'$'\n/' source-file > test-file
$ head -n1 test-file
Ö
$ head -n1 test-file | hexdump -C
00000000  c3 96 0a                                          |...|
00000003

Cool, we have an umlaut. Note the encoding though is c3 96 (UTF-8). Hmm.

Checking our other umlauts in the same file again:

$ tail -n +102322 test-file | head -n1 | hexdump -C -s85 -n2
00000055  d6 4d                                             |.M|
00000057

ISO 8859-1. Oops! It just goes to show how easy it is to get the encodings screwed up. To be clear, I've managed to create a mix of UTF-8 and ISO 8859-1 encodings in the same file.

Let's try converting our new test file with the umlaut (Ö) at the front and see what happens.

$ iconv -f iso-8859-1 -t utf8 test-file > test-file-converted
$ head -n1 test-file-converted | hexdump -C
00000000  c3 83 c2 96 0a                                    |.....|
00000005
$ tail -n +102322 test-file-converted | head -n1 | hexdump -C -s85 -n2
00000055  c3 96                                             |..|
00000057

Oops. The first umlaut that was UTF-8 was interpreted as ISO 8859-1 since that is what we told iconv. The second umlaut is correctly converted from d6 (ISO 8859-1) to c3 96 (UTF-8).

I'll try again, but this time I will use Vim to do the Ö insertion instead of sed. Vim seemed to detect the encoding better (as "latin1" aka ISO 8859-1) so perhaps it will insert the new Ö with a consistent encoding.

$ vim source-file
$ head -n1 test-file-2
?
$ head -n1 test-file-2 | hexdump -C
00000000  d6 0d 0a                                          |...|
00000003
$ tail -n +102322 test-file-2 | head -n1 | hexdump -C -s85 -n2
00000055  d6 4d                                             |.M|
00000057

It looks good. It looks like ISO 8859-1 for new and old umlauts.

Now the test.

$ file -b --mime-encoding test-file-2
iso-8859-1
$ iconv -f iso-8859-1 -t utf8 test-file-2 > test-file-2-converted
$ file -b --mime-encoding test-file-2-converted
utf-8

Boom! Moral of the story. Don't trust file to always guess your encoding right. It is easy to mix encodings within the same file. When in doubt, look at the hex.

A hack (also prone to failure) that would address this specific limitation of file when dealing with large files would be to shorten the file to make sure that special (non-ascii) characters appear early in the file so file is more likely to find them.

$ first_special=$(pcregrep -o1 -n '()[^\x00-\x7F]' source-file | head -n1 | cut -d":" -f1)
$ tail -n +$first_special source-file > /tmp/source-file-shorter
$ file -b --mime-encoding /tmp/source-file-shorter
iso-8859-1

You could then use (presumably correct) detected encoding to feed as input to iconv to ensure you are converting correctly.

Update

Christos Zoulas updated file to make the amount of bytes looked at configurable. One day turn-around on the feature request, awesome!

http://bugs.gw.com/view.php?id=533 Allow altering how many bytes to read from analyzed files from the command line

The feature was released in file version 5.26.

Looking at more of a large file before making a guess about encoding takes time. However, it is nice to have the option for specific use-cases where a better guess may outweigh additional time and I/O.

Use the following option:

-P, --parameter name=value

    Set various parameter limits.

    Name    Default     Explanation
    bytes   1048576     max number of bytes to read from file

Something like...

file_to_check="myfile"
bytes_to_scan=$(wc -c < $file_to_check)
file -b --mime-encoding -P bytes=$bytes_to_scan $file_to_check

... it should do the trick if you want to force file to look at the whole file before making a guess. Of course, this only works if you have file 5.26 or newer.

Forcing file to display UTF-8 instead of US-ASCII

Some of the other answers seem to focus on trying to make file display UTF-8 even if the file only contains plain 7-bit ascii. If you think this through you should probably never want to do this.

  1. If a file contains only 7-bit ascii but the file command is saying the file is UTF-8, that implies that the file contains some characters with UTF-8 specific encoding. If that isn't really true, it could cause confusion or problems down the line. If file displayed UTF-8 when the file only contained 7-bit ascii characters, this would be a bug in the file program.
  2. Any software that requires UTF-8 formatted input files should not have any problem consuming plain 7-bit ascii since this is the same on a byte level as UTF-8. If there is software that is using the file command output before accepting a file as input and it won't process the file unless it "sees" UTF-8...well that is pretty bad design. I would argue this is a bug in that program.

If you absolutely must take a plain 7-bit ascii file and convert it to UTF-8, simply insert a single non-7-bit-ascii character into the file with UTF-8 encoding for that character and you are done. But I can't imagine a use-case where you would need to do this. The easiest UTF-8 character to use for this is the Byte Order Mark (BOM) which is a special non-printing character that hints that the file is non-ascii. This is probably the best choice because it should not visually impact the file contents as it will generally be ignored.

Microsoft compilers and interpreters, and many pieces of software on Microsoft Windows such as Notepad treat the BOM as a required magic number rather than use heuristics. These tools add a BOM when saving text as UTF-8, and cannot interpret UTF-8 unless the BOM is present or the file contains only ASCII.

This is key:

or the file contains only ASCII

So some tools on windows have trouble reading UTF-8 files unless the BOM character is present. However this does not affect plain 7-bit ascii only files. I.e. this is not a reason for forcing plain 7-bit ascii files to be UTF-8 by adding a BOM character.

Here is more discussion about potential pitfalls of using the BOM when not needed (it IS needed for actual UTF-8 files that are consumed by some Microsoft apps). https://stackoverflow.com/a/13398447/3616686

Nevertheless if you still want to do it, I would be interested in hearing your use case. Here is how. In UTF-8 the BOM is represented by hex sequence 0xEF,0xBB,0xBF and so we can easily add this character to the front of our plain 7-bit ascii file. By adding a non-7-bit ascii character to the file, the file is no longer only 7-bit ascii. Note that we have not modified or converted the original 7-bit-ascii content at all. We have added a single non-7-bit-ascii character to the beginning of the file and so the file is no longer entirely composed of 7-bit-ascii characters.

$ printf '\xEF\xBB\xBF' > bom.txt # put a UTF-8 BOM char in new file
$ file bom.txt
bom.txt: UTF-8 Unicode text, with no line terminators
$ file plain-ascii.txt  # our pure 7-bit ascii file
plain-ascii.txt: ASCII text
$ cat bom.txt plain-ascii.txt > plain-ascii-with-utf8-bom.txt # put them together into one new file with the BOM first
$ file plain-ascii-with-utf8-bom.txt
plain-ascii-with-utf8-bom.txt: UTF-8 Unicode (with BOM) text

Export specific rows from a PostgreSQL table as INSERT SQL script

You can make view of the table with specifit records and then dump sql file

CREATE VIEW foo AS
SELECT id,name,city FROM nyummy.cimory WHERE city = 'tokyo'

How can I remove a key from a Python dictionary?

You can use a dictionary comprehension to create a new dictionary with that key removed:

>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}

You can delete by conditions. No error if key doesn't exist.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

How to use timer in C?

Here's a solution I used (it needs #include <time.h>):

int msec = 0, trigger = 10; /* 10ms */
clock_t before = clock();

do {
  /*
   * Do something to busy the CPU just here while you drink a coffee
   * Be sure this code will not take more than `trigger` ms
   */

  clock_t difference = clock() - before;
  msec = difference * 1000 / CLOCKS_PER_SEC;
  iterations++;
} while ( msec < trigger );

printf("Time taken %d seconds %d milliseconds (%d iterations)\n",
  msec/1000, msec%1000, iterations);

How to convert a string to lower or upper case in Ruby

In combination with try method, to support nil value:

'string'.try(:upcase)
'string'.try(:capitalize)
'string'.try(:titleize)

Revert to Eclipse default settings

I had the same problem. My path back to default was as follows:

  1. Install Eclipse Color Themes Plugin (http://www.eclipsecolorthemes.org/)
  2. Navigate to Window->Preferences
  3. Navigate to General->Appearance->Color Themes
  4. Click Restore Defaults, then click Apply

That should take care of it.

SQLite: How do I save the result of a query as a CSV file?

All the existing answers only work from the sqlite command line, which isn't ideal if you'd like to build a reusable script. Python makes it easy to build a script that can be executed programatically.

import pandas as pd
import sqlite3

conn = sqlite3.connect('your_cool_database.sqlite')

df = pd.read_sql('SELECT * from orders', conn)
df.to_csv('orders.csv', index = False)

You can customize the query to only export part of the sqlite table to the CSV file.

You can also run a single command to export all sqlite tables to CSV files:

for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
    t = table[0]
    df = pd.read_sql('SELECT * from ' + t, conn)
    df.to_csv(t + '_one_command.csv', index = False)

See here for more info.

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

For most of the Maven setup issues something like "Could not find or load main class...", start-with below steps to see if that fixes:

  • Make sure you unzipped the right archive (BINARY archive and not SOURCE archive)
  • Remove all user and system variables related to Maven (ex. M2_HOME,M2_OPTS etc.)
  • Make sure JAVA_HOME system variable is setup (ex. "C:\Program Files\Java\jdk1.8.0_172")
  • Make sure java bin location is added in "path" system variable (ex. "%JAVA_HOME%\bin")
  • Make sure maven bin location is added in "path" system variable (ex. "C:\MyInstalls\apache-maven-3.5.4\bin")

then...

  • Verify java is setup (at commandprompt : java -version)
  • Verify maven is setup (at commandprompt : mvn --version)

How to generate .NET 4.0 classes from xsd?

xsd.exe does not work well when you have circular references (ie a type can own an element of its own type directly or indirectly).

When circular references exist, I use Xsd2Code. Xsd2Code handles circular references well and works within the VS IDE, which is a big plus. It also has a lot of features you can use like generating the serialization/deserialization code. Make sure you turn on the GenerateXMLAttributes if you are generating serialization though (otherwise you'll get exceptions for ordering if not defined on all elements).

Neither works well with the choice feature. you'll end up with lists/collections of object instead of the type you want. I'd recommend avoiding choice in your xsd if possible as this does not serialize/deserialize well into a strongly typed class. If you don't care about this, though, then it's not a problem.

The any feature in xsd2code deserializes as System.Xml.XmlElement which I find really convenient but may be an issue if you want strong typed objects. I often use any when allowing custom config data, so an XmlElement is convenient to pass to another XML deserializer that is custom defined elsewhere.

Execution time of C program

I've found that the usual clock(), everyone recommends here, for some reason deviates wildly from run to run, even for static code without any side effects, like drawing to screen or reading files. It could be because CPU changes power consumption modes, OS giving different priorities, etc...

So the only way to reliably get the same result every time with clock() is to run the measured code in a loop multiple times (for several minutes), taking precautions to prevent the compiler from optimizing it out: modern compilers can precompute the code without side effects running in a loop, and move it out of the loop., like i.e. using random input for each iteration.

After enough samples are collected into an array, one sorts that array, and takes the middle element, called median. Median is better than average, because it throws away extreme deviations, like say antivirus taking up all CPU up or OS doing some update.

Here is a simple utility to measure execution performance of C/C++ code, averaging the values near median: https://github.com/saniv/gauge

I'm myself still looking for a more robust and faster way to measure code. One could probably try running the code in controlled conditions on bare metal without any OS, but that will give unrealistic result, because in reality OS does get involved.

x86 has these hardware performance counters, which including the actual number of instructions executed, but they are tricky to access without OS help, hard to interpret and have their own issues ( http://archive.gamedev.net/archive/reference/articles/article213.html ). Still they could be helpful investigating the nature of the bottle neck (data access or actual computations on that data).

How do I truncate a .NET string?

The .NET Framework has an API to truncate a string like this:

Microsoft.VisualBasic.Strings.Left(string, int);

But in a C# app you'll probably prefer to roll your own than taking a dependency on Microsoft.VisualBasic.dll, whose main raison d'etre is backwards compatibility.

How can I render HTML from another file in a React component?

You can use dangerouslySetInnerHTML to do this:

import React from 'react';
function iframe() {
    return {
        __html: '<iframe src="./Folder/File.html" width="540" height="450"></iframe>'
    }
}


export default function Exercises() {
    return (
        <div>
            <div dangerouslySetInnerHTML={iframe()} />
        </div>)
}

HTML files must be in the public folder

How to set the Default Page in ASP.NET?

If using IIS 7 or IIS 7.5 you can use

<system.webServer>
    <defaultDocument>
        <files>
            <clear />
            <add value="CreateThing.aspx" />
        </files>
    </defaultDocument>
</system.webServer>

https://docs.microsoft.com/en-us/iis/configuration/system.webServer/defaultDocument/

Difference between Role and GrantedAuthority in Spring Security

AFAIK GrantedAuthority and roles are same in spring security. GrantedAuthority's getAuthority() string is the role (as per default implementation SimpleGrantedAuthority).

For your case may be you can use Hierarchical Roles

<bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <constructor-arg ref="roleHierarchy" />
</bean>
<bean id="roleHierarchy"
        class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <property name="hierarchy">
        <value>
            ROLE_ADMIN > ROLE_createSubUsers
            ROLE_ADMIN > ROLE_deleteAccounts 
            ROLE_USER > ROLE_viewAccounts
        </value>
    </property>
</bean>

Not the exact sol you looking for, but hope it helps

Edit: Reply to your comment

Role is like a permission in spring-security. using intercept-url with hasRole provides a very fine grained control of what operation is allowed for which role/permission.

The way we handle in our application is, we define permission (i.e. role) for each operation (or rest url) for e.g. view_account, delete_account, add_account etc. Then we create logical profiles for each user like admin, guest_user, normal_user. The profiles are just logical grouping of permissions, independent of spring-security. When a new user is added, a profile is assigned to it (having all permissible permissions). Now when ever user try to perform some action, permission/role for that action is checked against user grantedAuthorities.

Also the defaultn RoleVoter uses prefix ROLE_, so any authority starting with ROLE_ is considered as role, you can change this default behavior by using a custom RolePrefix in role voter and using it in spring security.

Hashset vs Treeset

Even after 11 years, nobody thought of mentioning a very important difference.

Do you think that if HashSet equals TreeSet then the opposite is true as well? Take a look at this code:

TreeSet<String> treeSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
HashSet<String> hashSet = new HashSet<>();
treeSet.add("a");
hashSet.add("A");
System.out.println(hashSet.equals(treeSet));
System.out.println(treeSet.equals(hashSet));

Try to guess the output and then hover below snippet for seeing what the real output is. Ready? Here you go:

false
true

That's right, they don't hold equivalence relation for a comparator that is inconsistent with equals. The reason for this is that a TreeSet uses a comparator to determine the equivalence while HashSet uses equals. Internally they use HashMap and TreeMap so you should expect this behavior with the mentioned Maps as well.

Originally answered

What's the best practice for primary keys in tables?

I'll be up-front about my preference for natural keys - use them where possible, as they'll make your life of database administration a lot easier. I established a standard in our company that all tables have the following columns:

  • Row ID (GUID)
  • Creator (string; has a default of the current user's name (SUSER_SNAME() in T-SQL))
  • Created (DateTime)
  • Timestamp

Row ID has a unique key on it per table, and in any case is auto-generated per row (and permissions prevent anyone editing it), and is reasonably guaranteed to be unique across all tables and databases. If any ORM systems need a single ID key, this is the one to use.

Meanwhile, the actual PK is, if possible, a natural key. My internal rules are something like:

  • People - use surrogate key, e.g. INT. If it's internal, the Active Directory user GUID is an acceptable choice
  • Lookup tables (e.g. StatusCodes) - use a short CHAR code; it's easier to remember than INTs, and in many cases the paper forms and users will also use it for brevity (e.g. Status = "E" for "Expired", "A" for "Approved", "NADIS" for "No Asbestos Detected In Sample")
  • Linking tables - combination of FKs (e.g. EventId, AttendeeId)

So ideally you end up with a natural, human-readable and memorable PK, and an ORM-friendly one-ID-per-table GUID.

Caveat: the databases I maintain tend to the 100,000s of records rather than millions or billions, so if you have experience of larger systems which contraindicates my advice, feel free to ignore me!

How to send email from Terminal?

If you want to attach a file on Linux

echo 'mail content' | mailx -s 'email subject' -a attachment.txt [email protected]

findViewByID returns null

In my case, I had 2 activites in my project, main.xml and main2.xml. From the beginning, main2 was a copy of main, and everything worked well, until I added new TextView to main2, so the R.id.textview1 became available for the rest of app. Then I tried to fetch it by standard calling:

TextView tv = (TextView) findViewById( R.id.textview1 );

and it was always null. It turned out, that in onCreate constructor I was instantiating not main2, but the other one. I had:

setContentView(R.layout.main);

instead of

setContentView(R.layout.main2);

I noticed this after I arrived here, on the site.

How to use goto statement correctly

There is not 'goto' in the Java world. The main reason was developers realized that complex codes which had goto would lead to making the code really pathetic and it would be almost impossible to enhance or maintain the code.

However this code could be modified a little and using the concept of continue and break we could make the code work.

    import java.util.*;

public class Factorial 
{
    public static void main(String[] args) 
    {
        int x = 1;
        int factValue = 1;
        Scanner userInput = new Scanner(System.in);
        restart: while(true){
        System.out.println("Please enter a nonzero, nonnegative value to be factorialized.");
        int factInput = userInput.nextInt();

        while(factInput<=0)
        {
            System.out.println("Enter a nonzero, nonnegative value to be factorialized.");
            factInput = userInput.nextInt();
        }

        if(x<1)//This is another way of doing what the above while loop does, I just wanted to have some fun.
        {
            System.out.println("The number you entered is not valid. Please try again.");
            continue restart;
        }
        while(x<=factInput)
        {
            factValue*=x;
            x++;
        }
        System.out.println(factInput+"! = "+factValue);
        userInput.close();
        break restart;
}
    }
}

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Running Node.Js on Android

Dory - node.js

Great New Application
No Need to root your Phone and You Can Run your js File From anywere.

  • node.js runtime(run ES2015/ES6, ES2016 javascript and node.js APIs in android)
  • API Documents and instant code run from doc
  • syntax highlighting code editor
  • npm supports
  • linux terminal(toybox 0.7.4). node.js REPL and npm command in shell (add '--no-bin-links' option if you execute npm in /sdcard)
  • StartOnBoot / LiveReload
  • native node.js binary and npm are included. no need to be online.

Update instruction to node js 8 (async await)

  1. Download node.js v8.3.0 arm zip file and unzip.

  2. copy 'node' to android's sdcard(/sdcard or /sdcard/path/to/...)

  3. open the shell(check it out in the app's menu)

  4. cd /data/user/0/io.tmpage.dorynode/files/bin (or, just type cd && cd .. && cd files/bin )

  5. rm node

  6. cp /sdcard/node .

  7. (chmod a+x node

(https://play.google.com/store/apps/details?id=io.tempage.dorynode&hl=en)

open link of google play store in mobile version android

You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.

final String my_package_name = "........."  // <- HERE YOUR PACKAGE NAME!!
String url = "";

try {
    //Check whether Google Play store is installed or not:
    this.getPackageManager().getPackageInfo("com.android.vending", 0);

    url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
    url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}


//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);

Send array with Ajax to PHP script

Encode your data string into JSON.

dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
   $.ajax({
        type: "POST",
        url: "script.php",
        data: {data : jsonString}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

In your PHP

$data = json_decode(stripslashes($_POST['data']));

  // here i would like use foreach:

  foreach($data as $d){
     echo $d;
  }

Note

When you send data via POST, it needs to be as a keyvalue pair.

Thus

data: dataString

is wrong. Instead do:

data: {data:dataString}

Extension gd is missing from your system - laravel composer Update

For Windows : Uncomment this line in your php.ini file

;extension=php_gd2.dll

If the above step doesn't work uncomment the following line as well:

;extension=gd2

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

How to create a file in Android?

Write to a file test.txt:

String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
        fos = new FileOutputStream(filepath);
        byte[] buffer = "This will be writtent in test.txt".getBytes();
        fos.write(buffer, 0, buffer.length);
        fos.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fos != null)
            fos.close();
    }

Read from file test.txt:

String filepath ="/mnt/sdcard/test.txt";        
FileInputStream fis = null;
try {
       fis = new FileInputStream(filepath);
       int length = (int) new File(filepath).length();
       byte[] buffer = new byte[length];
       fis.read(buffer, 0, length);
       fis.close();
    } catch (FileNotFoundException e) {
         e.printStackTrace();
    } catch (IOException e) {
         e.printStackTrace();
    }finally{
        if(fis != null)
            fis.close();
   }

Note: don't forget to add these two permission in AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Getting data posted in between two dates

May this helpful to you.... With Join of Three Tables

public function get_details_beetween_dates()
    {
        $from = $this->input->post('fromdate');
        $to = $this->input->post('todate');

        $this->db->select('users.first_name, users.last_name, users.email, groups.name as designation, dailyinfo.amount as Total_Fine, dailyinfo.date as Date_of_Fine, dailyinfo.desc as Description')
                    ->from('users')
                    ->where('dailyinfo.date >= ',$from)
                    ->where('dailyinfo.date <= ',$to)
                    ->join('users_groups','users.id = users_groups.user_id')
                    ->join('dailyinfo','users.id = dailyinfo.userid')
                    ->join('groups','groups.id = users_groups.group_id');

        /*
        $this->db->select('date, amount, desc')
                 ->from('dailyinfo')
                 ->where('dailyinfo.date >= ',$from)
                 ->where('dailyinfo.date <= ',$to);
        */

        $q = $this->db->get();

        $array['userDetails'] = $q->result();
        return $array;
    }

JVM option -Xss - What does it do exactly?

Each thread has a stack which used for local variables and internal values. The stack size limits how deep your calls can be. Generally this is not something you need to change.

Razor MVC Populating Javascript array with Model Array

If it is a symmetrical (rectangular) array then Try pushing into a single dimension javascript array; use razor to determine the array structure; and then transform into a 2 dimensional array.

// this just sticks them all in a one dimension array of rows * cols
var myArray = new Array();
@foreach (var d in Model.ResultArray)
{
    @:myArray.push("@d");
}

var MyA = new Array();

var rows = @Model.ResultArray.GetLength(0);
var cols = @Model.ResultArray.GetLength(1);

// now convert the single dimension array to 2 dimensions
var NewRow;
var myArrayPointer = 0;

for (rr = 0; rr < rows; rr++)
{
  NewRow = new Array();
  for ( cc = 0; cc < cols; cc++)
  {
    NewRow.push(myArray[myArrayPointer]);
    myArrayPointer++;
  }
  MyA.push(NewRow);
}

Best way to initialize (empty) array in PHP

What you're doing is 100% correct.

In terms of nice naming it's often done that private/protected properties are preceded with an underscore to make it obvious that they're not public. E.g. private $_arr = array() or public $arr = array()

Get random boolean in Java

Have you tried looking at the Java Documentation?

Returns the next pseudorandom, uniformly distributed boolean value from this random number generator's sequence ... the values true and false are produced with (approximately) equal probability.

For example:

import java.util.Random;

Random random = new Random();
random.nextBoolean();

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

Loginto your gmail account https://myaccount.google.com/u/4/security-checkup/4

enter image description here

(See photo) review all locations Google may have blocked for "unknown" or suspicious activity.

Sort arrays of primitive types in descending order

Below is my solution, you can adapt it to your needs.

How does it work? It takes an array of integers as arguments. After that it will create a new array which will contain the same values as the array from the arguments. The reason of doing this is to leave the original array intact.

Once the new array contains the copied data, we sort it by swapping the values until the condition if(newArr[i] < newArr[i+1]) evaluates to false. That means the array is sorted in descending order.

For a thorough explanation check my blog post here.

public static int[] sortDescending(int[] array)
{
    int[] newArr = new int[array.length];

    for(int i = 0; i < array.length; i++)
    {
        newArr[i] = array[i];
    }

    boolean flag = true;
    int tempValue;

    while(flag) 
    {
        flag = false;

        for(int i = 0; i < newArr.length - 1; i++) 
        {
            if(newArr[i] < newArr[i+1])
            {
                tempValue = newArr[i];
                newArr[i] = newArr[i+1];
                newArr[i+1] = tempValue;
                flag = true;
            }
        }
    }

    return newArr;
}

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

converting a javascript string to a html object

var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;

JSON.net: how to deserialize without using the default constructor?

Solution:

public Response Get(string jsonData) {
    var json = JsonConvert.DeserializeObject<modelname>(jsonData);
    var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
    return data;
}

Model:

public class modelname {
    public long parameter{ get; set; }
    public int parameter{ get; set; }
    public int parameter{ get; set; }
    public string parameter{ get; set; }
}

Java 8: Difference between two LocalDateTime in multiple units

Unfortunately, there doesn't seem to be a period class that spans time as well, so you might have to do the calculations on your own.

Fortunately, the date and time classes have a lot of utility methods that simplify that to some degree. Here's a way to calculate the difference although not necessarily the fastest:

LocalDateTime fromDateTime = LocalDateTime.of(1984, 12, 16, 7, 45, 55);
LocalDateTime toDateTime = LocalDateTime.of(2014, 9, 10, 6, 40, 45);

LocalDateTime tempDateTime = LocalDateTime.from( fromDateTime );

long years = tempDateTime.until( toDateTime, ChronoUnit.YEARS );
tempDateTime = tempDateTime.plusYears( years );

long months = tempDateTime.until( toDateTime, ChronoUnit.MONTHS );
tempDateTime = tempDateTime.plusMonths( months );

long days = tempDateTime.until( toDateTime, ChronoUnit.DAYS );
tempDateTime = tempDateTime.plusDays( days );


long hours = tempDateTime.until( toDateTime, ChronoUnit.HOURS );
tempDateTime = tempDateTime.plusHours( hours );

long minutes = tempDateTime.until( toDateTime, ChronoUnit.MINUTES );
tempDateTime = tempDateTime.plusMinutes( minutes );

long seconds = tempDateTime.until( toDateTime, ChronoUnit.SECONDS );

System.out.println( years + " years " + 
        months + " months " + 
        days + " days " +
        hours + " hours " +
        minutes + " minutes " +
        seconds + " seconds.");

//prints: 29 years 8 months 24 days 22 hours 54 minutes 50 seconds.

The basic idea is this: create a temporary start date and get the full years to the end. Then adjust that date by the number of years so that the start date is less then a year from the end. Repeat that for each time unit in descending order.

Finally a disclaimer: I didn't take different timezones into account (both dates should be in the same timezone) and I also didn't test/check how daylight saving time or other changes in a calendar (like the timezone changes in Samoa) affect this calculation. So use with care.

Connecting to Microsoft SQL server using Python

Following Python code worked for me. To check the ODBC connection, I first created a 4 line C# console application as listed below.

Python Code

import pandas as pd
import pyodbc 
cnxn = pyodbc.connect("Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;")
df = pd.read_sql_query('select TOP 10 * from dbo.Table WHERE Patient_Key > 1000', cnxn)
df.head()

Calling a Stored Procedure

 dfProcResult = pd.read_sql_query('exec dbo.usp_GetPatientProfile ?', cnxn, params=['MyParam'] )

C# Program to Check ODBC Connection

    static void Main(string[] args)
    {
        string connectionString = "Driver={SQL Server};Server=serverName;UID=UserName;PWD=Password;Database=RCO_DW;";
        OdbcConnection cn = new OdbcConnection(connectionString);
        cn.Open();
        cn.Close();
    }

List of zeros in python

zeros=[0]*4

you can replace 4 in the above example with whatever number you want.

How to copy Docker images from one host to another without using a repository

You will need to save the Docker image as a tar file:

docker save -o <path for generated tar file> <image name>

Then copy your image to a new system with regular file transfer tools such as cp, scp or rsync(preferred for big files). After that you will have to load the image into Docker:

docker load -i <path to image tar file>

PS: You may need to sudo all commands.

EDIT: You should add filename (not just directory) with -o, for example:

docker save -o c:/myfile.tar centos:16

Java; String replace (using regular expressions)?

"5 * x^3 - 6 * x^1 + 1".replaceAll("\\W*\\*\\W*","").replaceAll("\\^(\\d+)","<sup>$1</sup>");

please note that joining both replacements in a single regex/replacement would be a bad choice because more general expressions such as x^3 - 6 * x would fail.

Better way to cast object to int

Convert.ToInt32(myobject);

This will handle the case where myobject is null and return 0, instead of throwing an exception.

Reason to Pass a Pointer by Reference in C++?

David's answer is correct, but if it's still a little abstract, here are two examples:

  1. You might want to zero all freed pointers to catch memory problems earlier. C-style you'd do:

    void freeAndZero(void** ptr)
    {
        free(*ptr);
        *ptr = 0;
    }
    
    void* ptr = malloc(...);
    
    ...
    
    freeAndZero(&ptr);
    

    In C++ to do the same, you might do:

    template<class T> void freeAndZero(T* &ptr)
    {
        delete ptr;
        ptr = 0;
    }
    
    int* ptr = new int;
    
    ...
    
    freeAndZero(ptr);
    
  2. When dealing with linked-lists - often simply represented as pointers to a next node:

    struct Node
    {
        value_t value;
        Node* next;
    };
    

    In this case, when you insert to the empty list you necessarily must change the incoming pointer because the result is not the NULL pointer anymore. This is a case where you modify an external pointer from a function, so it would have a reference to pointer in its signature:

    void insert(Node* &list)
    {
        ...
        if(!list) list = new Node(...);
        ...
    }
    

There's an example in this question.

Is it possible to program Android to act as physical USB keyboard?

Your Android already identifies with a VID/PID when plugged into a host. It already has an interface for Mass Storage. You would need to hack the driver at a low level to support a 2nd interface for 03:01 HID. Then it would just be a question of pushing scancodes to the modified driver. This wouldn't be simple, but it would be a neat hack. One use would be for typing long random passwords for logins.

OpenCV NoneType object has no attribute shape

It means that somewhere a function which should return a image just returned None and therefore has no shape attribute. Try "print img" to check if your image is None or an actual numpy object.

Maven does not find JUnit tests to run

Many of these answers were quite useful to me in the past, but I would like to add an additional scenario that has cost me some time, as it may help others in the future:

Make sure that the test classes and methods are public.

My problem was that I was using an automatic test class/methods generation feature of my IDE (IntelliJ) and for some reason it created them as package-private. I find this to be easier to miss than one would expect.

Error in Process.Start() -- The system cannot find the file specified

You can't use a filename like iexplore by itself because the path to internet explorer isn't listed in the PATH environment variable for the system or user.

However any path entered into the PATH environment variable allows you to use just the file name to execute it.

System32 isn't special in this regard as any directory can be added to the PATH variable. Each path is simply delimited by a semi-colon.

For example I have c:\ffmpeg\bin\ and c:\nmap\bin\ in my path environment variable, so I can do things like new ProcessStartInfo("nmap", "-foo") or new ProcessStartInfo("ffplay", "-bar")

The actual PATH variable looks like this on my machine.

%SystemRoot%\system32;C:\FFPlay\bin;C:\nmap\bin;

As you can see you can use other system variables, such as %SystemRoot% to build and construct paths in the environment variable.

So - if you add a path like "%PROGRAMFILES%\Internet Explorer;" to your PATH variable you will be able to use ProcessStartInfo("iexplore");

If you don't want to alter your PATH then simply use a system variable such as %PROGRAMFILES% or %SystemRoot% and then expand it when needed in code. i.e.

string path = Environment.ExpandEnvironmentVariables(
       @"%PROGRAMFILES%\Internet Explorer\iexplore.exe");
var info = new ProcessStartInfo(path);

HashMap: One Key, multiple Values

Libraries exist to do this, but the simplest plain Java way is to create a Map of List like this:

Map<Object,ArrayList<Object>> multiMap = new HashMap<>();

connecting MySQL server to NetBeans

check the context.xml file in Web Pages -> META-INF, the username="user" must be the same as the database user, in my case was root, that solved the connection error

Hope helps

Rolling back local and remote git repository by 1 commit

You can also do this:

git reset --hard <commit-hash>
git push -f origin master

and have everyone else who got the latest bad commits reset:

git reset --hard origin/master

How to read first N lines of a file?

Python 2:

with open("datafile") as myfile:
    head = [next(myfile) for x in xrange(N)]
print head

Python 3:

with open("datafile") as myfile:
    head = [next(myfile) for x in range(N)]
print(head)

Here's another way (both Python 2 & 3):

from itertools import islice

with open("datafile") as myfile:
    head = list(islice(myfile, N))
print(head)

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

You should use Java's built in serialization mechanism. To use it, you need to do the following:

  1. Declare the Club class as implementing Serializable:

    public class Club implements Serializable {
        ...
    }
    

    This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

  2. To write your list to a file do the following:

    FileOutputStream fos = new FileOutputStream("t.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(clubs);
    oos.close();
    
  3. To read the list from a file, do the following:

    FileInputStream fis = new FileInputStream("t.tmp");
    ObjectInputStream ois = new ObjectInputStream(fis);
    List<Club> clubs = (List<Club>) ois.readObject();
    ois.close();
    

How to use font-awesome icons from node-modules

I came upon this question having a similar problem and thought I would share another solution:

If you are creating a Javascript application, font awesome icons can also be referenced directly through Javascript:

First, do the steps in this guide:

npm install @fortawesome/fontawesome-svg-core

Then inside your javascript:

import { library, icon } from '@fortawesome/fontawesome-svg-core'
import { faStroopwafel } from '@fortawesome/free-solid-svg-icons'

library.add(faStroopwafel)

const fontIcon= icon({ prefix: 'fas', iconName: 'stroopwafel' })

After the above steps, you can insert the icon inside an HTML node with:

htmlNode.appendChild(fontIcon.node[0]);

You can also access the HTML string representing the icon with:

fontIcon.html

What are enums and why are they useful?

Enum inherits all the methods of Object class and abstract class Enum. So you can use it's methods for reflection, multithreading, serilization, comparable, etc. If you just declare a static constant instead of Enum, you can't. Besides that, the value of Enum can be passed to DAO layer as well.

Here's an example program to demonstrate.

public enum State {

    Start("1"),
    Wait("1"),
    Notify("2"),
    NotifyAll("3"),
    Run("4"),
    SystemInatilize("5"),
    VendorInatilize("6"),
    test,
    FrameworkInatilize("7");

    public static State getState(String value) {
        return State.Wait;
    }

    private String value;
    State test;

    private State(String value) {
        this.value = value;
    }

    private State() {
    }

    public String getValue() {
        return value;
    }

    public void setCurrentState(State currentState) {
        test = currentState;
    }

    public boolean isNotify() {
        return this.equals(Notify);
    }
}

public class EnumTest {

    State test;

    public void setCurrentState(State currentState) {
        test = currentState;
    }

    public State getCurrentState() {
        return test;
    }

    public static void main(String[] args) {
        System.out.println(State.test);
        System.out.println(State.FrameworkInatilize);
        EnumTest test=new EnumTest();
        test.setCurrentState(State.Notify);
        test. stateSwitch();
    }

    public void stateSwitch() {
        switch (getCurrentState()) {
        case Notify:
            System.out.println("Notify");
            System.out.println(test.isNotify());
            break;
        default:
            break;
        }
    }
}

Changing the position of Bootstrap popovers based on the popover's X position in relation to window edge?

I solved my problem in AngularJS as follows:

var configPopOver = {
        animation: 500,
        container: 'body',
        placement: function (context, source) {
                    var elBounding = source.getBoundingClientRect();
                    var pageWidth = angular.element('body')[0].clientWidth
                    var pageHeith = angular.element('body')[0].clientHeith

                    if (elBounding.left > (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "left";
                    }

                    if (elBounding.left < (pageWidth*0.34) && elBounding.width < (pageWidth*0.67)) {
                        return "right";
                    }

                    if (elBounding.top < 110){
                        return "bottom";
                    }

                    return "top";
                },
        html: true
    };

This function do the position of Bootstrap popover float to the best position, based on element position.

What does "Could not find or load main class" mean?

All right, there are many answers already, but no one mentioned the case where file permissions can be the culprit.

When running, a user may not have access to the JAR file or one of the directories of the path. For example, consider:

Jar file in /dir1/dir2/dir3/myjar.jar

User1 who owns the JAR file may do:

# Running as User1
cd /dir1/dir2/dir3/
chmod +r myjar.jar

But it still doesn't work:

# Running as User2
java -cp "/dir1/dir2/dir3:/dir1/dir2/javalibs" MyProgram
Error: Could not find or load main class MyProgram

This is because the running user (User2) does not have access to dir1, dir2, or javalibs or dir3. It may drive someone nuts when User1 can see the files, and can access to them, but the error still happens for User2.

can't start MySql in Mac OS 10.6 Snow Leopard

my apple processor version10.6.3 is error and i can click system preference

Create an empty object in JavaScript with {} or new Object()?

This is essentially the same thing. Use whatever you find more convenient.

How to move div vertically down using CSS

if div.title is a div then put this:

left: 0;
bottom: 0;

Postgres: check if array field contains value?

With ANY operator you can search for only one value.

For example,

select * from mytable where 'Book' = ANY(pub_types);

If you want to search multiple values, you can use @> operator.

For example,

select * from mytable where pub_types @> '{"Journal", "Book"}';

You can specify in which ever order you like.

PHP: How to check if a date is today, yesterday or tomorrow

Pass the date into the function.

            <?php
                function getTheDay($date)
                {
                    $curr_date=strtotime(date("Y-m-d H:i:s"));
                    $the_date=strtotime($date);
                    $diff=floor(($curr_date-$the_date)/(60*60*24));
                    switch($diff)
                    {
                        case 0:
                            return "Today";
                            break;
                        case 1:
                            return "Yesterday";
                            break;
                        default:
                            return $diff." Days ago";
                    }
                }
            ?>

How to make a smooth image rotation in Android?

Try to use more than 360 to avoid restarting.

I use 3600 insted of 360 and this works fine for me:

<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:toDegrees="3600"
    android:interpolator="@android:anim/linear_interpolator"
    android:repeatCount="infinite"
    android:duration="8000"
    android:pivotX="50%"
    android:pivotY="50%" />

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

This issue seems to like the following.

How to resolve repository certificate error in Gradle build

Below steps may help:

1. Add certificate to keystore-

Import some certifications into Android Studio JDK cacerts from Android Studio’s cacerts.

Android Studio’s cacerts may be located in

{your-home-directory}/.AndroidStudio3.0/system/tasks/cacerts

I used the following import command.

$ keytool -importkeystore -v -srckeystore {src cacerts} -destkeystore {dest cacerts}

2. Add modified cacert path to gradle.properties-

systemProp.javax.net.ssl.trustStore={your-android-studio-directory}\\jre\\jre\\lib\\security\\cacerts
systemProp.javax.net.ssl.trustStorePassword=changeit

Ref : https://www.cresco.co.jp/blog/entry/2014//

How and when to use ‘async’ and ‘await’

I think you've picked a bad example with System.Threading.Thread.Sleep

Point of an async Task is to let it execute in background without locking the main thread, such as doing a DownloadFileAsync

System.Threading.Thread.Sleep isn't something that is "being done", it just sleeps, and therefore your next line is reached after 5 seconds ...

Read this article, I think it is a great explanation of async and await concept: http://msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx

How do you set your pythonpath in an already-created virtualenv?

The most elegant solution to this problem is here.

Original answer remains, but this is a messy solution:


If you want to change the PYTHONPATH used in a virtualenv, you can add the following line to your virtualenv's bin/activate file:

export PYTHONPATH="/the/path/you/want"

This way, the new PYTHONPATH will be set each time you use this virtualenv.

EDIT: (to answer @RamRachum's comment)

To have it restored to its original value on deactivate, you could add

export OLD_PYTHONPATH="$PYTHONPATH"

before the previously mentioned line, and add the following line to your bin/postdeactivate script.

export PYTHONPATH="$OLD_PYTHONPATH"

Trying to load local JSON file to show data in a html page using JQuery

I would try to save my object as .txt file and then fetch it like this:

 $.get('yourJsonFileAsString.txt', function(data) {
   console.log( $.parseJSON( data ) );
 }); 

What is the usefulness of PUT and DELETE HTTP request methods?

Using HTTP Request verb such as GET, POST, DELETE, PUT etc... enables you to build RESTful web applications. Read about it here: http://en.wikipedia.org/wiki/Representational_state_transfer

The easiest way to see benefits from this is to look at this example. Every MVC framework has a Router/Dispatcher that maps URL-s to actionControllers. So URL like this: /blog/article/1 would invoke blogController::articleAction($id); Now this Router is only aware of the URL or /blog/article/1/

But if that Router would be aware of whole HTTP Request object instead of just URL, he could have access HTTP Request verb (GET, POST, PUT, DELETE...), and many other useful stuff about current HTTP Request.

That would enable you to configure application so it can accept the same URL and map it to different actionControllers depending on the HTTP Request verb.

For example:

if you want to retrive article 1 you can do this:

GET /blog/article/1 HTTP/1.1

but if you want to delete article 1 you will do this:

DELETE /blog/article/1 HTTP/1.1

Notice that both HTTP Requests have the same URI, /blog/article/1, the only difference is the HTTP Request verb. And based on that verb your router can call different actionController. This enables you to build neat URL-s.

Read this two articles, they might help you:

Symfony 2 - HTTP Fundamentals

Symfony 2 - Routing

These articles are about Symfony 2 framework, but they can help you to figure out how does HTTP Requests and Responses work.

Hope this helps!

How to fix "Referenced assembly does not have a strong name" error?

You can use unsigned assemblies if your assembly is also unsigned.

git: How to ignore all present untracked files?

In case you are not on Unix like OS, this would work on Windows using PowerShell

git status --porcelain | ?{ $_ -match "^\?\? " }| %{$_ -replace "^\?\? ",""} | Add-Content .\.gitignore

However, .gitignore file has to have a new empty line, otherwise it will append text to the last line no matter if it has content.

This might be a better alternative:

$gi=gc .\.gitignore;$res=git status --porcelain|?{ $_ -match "^\?\? " }|%{ $_ -replace "^\?\? ", "" }; $res=$gi+$res; $res | Out-File .\.gitignore

How to deselect a selected UITableView cell?

Based on saikirans solution, I have written this, which helped me. On the .m file:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    if(selectedRowIndex && indexPath.row == selectedRowIndex.row) {

        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        selectedRowIndex = nil;

    }

    else {  self.selectedRowIndex = [indexPath retain];   }

    [tableView beginUpdates];
    [tableView endUpdates];

}

And on the header file:

@property (retain, nonatomic) NSIndexPath* selectedRowIndex;

I am not very experienced either, so double check for memory leaks etc.

What does InitializeComponent() do, and how does it work in WPF?

Looking at the code always helps too. That is, you can actually take a look at the generated partial class (that calls LoadComponent) by doing the following:

  1. Go to the Solution Explorer pane in the Visual Studio solution that you are interested in.
  2. There is a button in the tool bar of the Solution Explorer titled 'Show All Files'. Toggle that button.
  3. Now, expand the obj folder and then the Debug or Release folder (or whatever configuration you are building) and you will see a file titled YourClass.g.cs.

The YourClass.g.cs ... is the code for generated partial class. Again, if you open that up you can see the InitializeComponent method and how it calls LoadComponent ... and much more.

php mail setup in xampp

My favorite smtp server is hMailServer.

It has a nice windows friendly installer and wizard. Hands down the easiest mail server I've ever setup.

It can proxy through your gmail/yahoo/etc account or send email directly.

Once it is installed, email in xampp just works with no config changes.

keyCode values for numeric keypad?

For the people that want a CTRL+C, CTRL-V solution, here you go:

    /**
     * Retrieves the number that was pressed on the keyboard.
     *
     * @param {Event} event The keypress event containing the keyCode.
     * @returns {number|null} a number between 0-9 that was pressed. Returns null if there was no numeric key pressed.
     */
    function getNumberFromKeyEvent(event) {
        if (event.keyCode >= 96 && event.keyCode <= 105) {
            return event.keyCode - 96;
        } else if (event.keyCode >= 48 && event.keyCode <= 57) {
            return event.keyCode - 48;
        }
        return null;
    }

It uses the logic of the first answer.

How to get file name when user select a file via <input type="file" />?

just tested doing this and it seems to work in firefox & IE

<html>
    <head>
        <script type="text/javascript">
            function alertFilename()
            {
                var thefile = document.getElementById('thefile');
                alert(thefile.value);
            }
        </script>
    </head>
    <body>
        <form>
            <input type="file" id="thefile" onchange="alertFilename()" />
            <input type="button" onclick="alertFilename()" value="alert" />
        </form>
    </body>
</html>

MySQL: determine which database is selected?

You can always use STATUS command to get to know Current database & Current User

enter image description here

Is key-value pair available in Typescript?

TypeScript has Map. You can use like:

public myMap = new Map<K,V>([
[k1, v1],
[k2, v2]
]);

myMap.get(key); // returns value
myMap.set(key, value); // import a new data
myMap.has(key); // check data

Populate dropdown select with array using jQuery

A solution is to create your own jquery plugin that take the json map and populate the select with it.

(function($) {     
     $.fn.fillValues = function(options) {
         var settings = $.extend({
             datas : null, 
             complete : null,
         }, options);

         this.each( function(){
            var datas = settings.datas;
            if(datas !=null) {
                $(this).empty();
                for(var key in datas){
                    $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
                }
            }
            if($.isFunction(settings.complete)){
                settings.complete.call(this);
            }
        });

    }

}(jQuery));

You can call it by doing this :

$("#select").fillValues({datas:your_map,});

The advantages is that anywhere you will face the same problem you just call

 $("....").fillValues({datas:your_map,});

Et voila !

You can add functions in your plugin as you like

ASP.NET jQuery Ajax Calling Code-Behind Method

Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).

You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:

$.ajax({
        type: "POST",
        url: "Default.aspx/OnSubmit",
        data: dataValue,                
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
        },
        success: function (result) {
            alert("We returned: " + result);
        }
    });

Change hash without reload in jQuery

You could try catching the onload event. And stopping the propagation dependent on some flag.

var changeHash = false;

$('ul.questions li a').click(function(event) {
    var $this = $(this)
    $('.tab').hide();  //you can improve the speed of this selector.
    $($this.attr('href')).fadeIn('slow');
    StopEvent(event);  //notice I've changed this
    changeHash = true;
    window.location.hash = $this.attr('href');
});

$(window).onload(function(event){
    if (changeHash){
        changeHash = false;
        StopEvent(event);
    }
}

function StopEvent(event){
    event.preventDefault();
    event.stopPropagation();
    if ($.browser.msie) {
        event.originalEvent.keyCode = 0;
        event.originalEvent.cancelBubble = true;
        event.originalEvent.returnValue = false;
    }
}

Not tested, so can't say if it would work

How to delete a file via PHP?

Check your permissions first of all on the file, to make sure you can a) see it from your script, and b) are able to delete it.

You can also use a path calculated from the directory you're currently running the script in, eg:

unlink(dirname(__FILE__) . "/../../public_files/" . $filename);

(in PHP 5.3 I believe you can use the __DIR__ constant instead of dirname() but I've not used it myself yet)

glob exclude pattern

As mentioned by the accepted answer, you can't exclude patterns with glob, so the following is a method to filter your glob result.

The accepted answer is probably the best pythonic way to do things but if you think list comprehensions look a bit ugly and want to make your code maximally numpythonic anyway (like I did) then you can do this (but note that this is probably less efficient than the list comprehension method):

import glob

data_files = glob.glob("path_to_files/*.fits")

light_files = np.setdiff1d( data_files, glob.glob("*BIAS*"))
light_files = np.setdiff1d(light_files, glob.glob("*FLAT*"))

(In my case, I had some image frames, bias frames, and flat frames all in one directory and I just wanted the image frames)

Detect if a jQuery UI dialog box is open

If you want to check if the dialog's open on a particular element you can do this:

if ($('#elem').closest('.ui-dialog').is(':visible')) { 
  // do something
}

Or if you just want to check if the element itself is visible you can do:

if ($('#elem').is(':visible')) { 
  // do something
}

Or...

if ($('#elem:visible').length) { 
  // do something
}

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

How can I extract a number from a string in JavaScript?

Using match function.

var thenum = thestring.match(/\d+$/)[0];
alert(thenum);

jsfiddle

How to assign an exec result to a sql variable?

From the documentation (assuming that you use SQL-Server):

USE AdventureWorks;
GO
DECLARE @returnstatus nvarchar(15);
SET @returnstatus = NULL;
EXEC @returnstatus = dbo.ufnGetSalesOrderStatusText @Status = 2;
PRINT @returnstatus;
GO

So yes, it should work that way.

How can I specify a branch/tag when adding a Git submodule?

(Git 2.22, Q2 2019, has introduced git submodule set-branch --branch aBranch -- <submodule_path>)

Note that if you have an existing submodule which isn't tracking a branch yet, then (if you have git 1.8.2+):

  • Make sure the parent repo knows that its submodule now tracks a branch:

      cd /path/to/your/parent/repo
      git config -f .gitmodules submodule.<path>.branch <branch>
    
  • Make sure your submodule is actually at the latest of that branch:

      cd path/to/your/submodule
      git checkout -b branch --track origin/branch
        # if the master branch already exist:
        git branch -u origin/master master
    

         (with 'origin' being the name of the upstream remote repo the submodule has been cloned from.
         A git remote -v inside that submodule will display it. Usually, it is 'origin')

  • Don't forget to record the new state of your submodule in your parent repo:

      cd /path/to/your/parent/repo
      git add path/to/your/submodule
      git commit -m "Make submodule tracking a branch"
    
  • Subsequent update for that submodule will have to use the --remote option:

      # update your submodule
      # --remote will also fetch and ensure that
      # the latest commit from the branch is used
      git submodule update --remote
    
      # to avoid fetching use
      git submodule update --remote --no-fetch 
    

Note that with Git 2.10+ (Q3 2016), you can use '.' as a branch name:

The name of the branch is recorded as submodule.<name>.branch in .gitmodules for update --remote.
A special value of . is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.

But, as commented by LubosD

With git checkout, if the branch name to follow is ".", it will kill your uncommitted work!
Use git switch instead.

That means Git 2.23 (August 2019) or more.

See "Confused by git checkout"


If you want to update all your submodules following a branch:

    git submodule update --recursive --remote

Note that the result, for each updated submodule, will almost always be a detached HEAD, as Dan Cameron note in his answer.

(Clintm notes in the comments that, if you run git submodule update --remote and the resulting sha1 is the same as the branch the submodule is currently on, it won't do anything and leave the submodule still "on that branch" and not in detached head state.)

To ensure the branch is actually checked out (and that won't modify the SHA1 of the special entry representing the submodule for the parent repo), he suggests:

git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; git switch $branch'

Each submodule will still reference the same SHA1, but if you do make new commits, you will be able to push them because they will be referenced by the branch you want the submodule to track.
After that push within a submodule, don't forget to go back to the parent repo, add, commit and push the new SHA1 for those modified submodules.

Note the use of $toplevel, recommended in the comments by Alexander Pogrebnyak.
$toplevel was introduced in git1.7.2 in May 2010: commit f030c96.

it contains the absolute path of the top level directory (where .gitmodules is).

dtmland adds in the comments:

The foreach script will fail to checkout submodules that are not following a branch.
However, this command gives you both:

 git submodule foreach -q --recursive 'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; [ "$branch" = "" ] && git checkout master || git switch $branch' –

The same command but easier to read:

git submodule foreach -q --recursive \
    'branch="$(git config -f $toplevel/.gitmodules submodule.$name.branch)"; \
     [ "$branch" = "" ] && \
     git checkout master || git switch $branch' –
  

umläute refines dtmland's command with a simplified version in the comments:

git submodule foreach -q --recursive 'git switch $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master)'

multiple lines:

git submodule foreach -q --recursive \
  'git switch \
  $(git config -f $toplevel/.gitmodules submodule.$name.branch || echo master)'

Before Git 2.26 (Q1 2020), a fetch that is told to recursively fetch updates in submodules inevitably produces reams of output, and it becomes hard to spot error messages.

The command has been taught to enumerate submodules that had errors at the end of the operation.

See commit 0222540 (16 Jan 2020) by Emily Shaffer (nasamuffin).
(Merged by Junio C Hamano -- gitster -- in commit b5c71cc, 05 Feb 2020)

fetch: emphasize failure during submodule fetch

Signed-off-by: Emily Shaffer

In cases when a submodule fetch fails when there are many submodules, the error from the lone failing submodule fetch is buried under activity on the other submodules if more than one fetch fell back on fetch-by-oid.
Call out a failure late so the user is aware that something went wrong, and where.

Because fetch_finish() is only called synchronously by run_processes_parallel, mutexing is not required around submodules_with_errors.


Note that, with Git 2.28 (Q3 2020), Rewrite of parts of the scripted "git submodule" Porcelain command continues; this time it is "git submodule set-branch" subcommand's turn.

See commit 2964d6e (02 Jun 2020) by Shourya Shukla (periperidip).
(Merged by Junio C Hamano -- gitster -- in commit 1046282, 25 Jun 2020)

submodule: port subcommand 'set-branch' from shell to C

Mentored-by: Christian Couder
Mentored-by: Kaartic Sivaraam
Helped-by: Denton Liu
Helped-by: Eric Sunshine
Helped-by: Ðoàn Tr?n Công Danh
Signed-off-by: Shourya Shukla

Convert submodule subcommand 'set-branch' to a builtin and call it via git submodule.sh.

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Jest spyOn function called

You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance before trying to spy on the method.

describe('my sweet test', () => {
 it('clicks it', () => {
    const app = shallow(<App />)
    const instance = app.instance()
    const spy = jest.spyOn(instance, 'myClickFunc')

    instance.forceUpdate();    

    const p = app.find('.App-intro')
    p.simulate('click')
    expect(spy).toHaveBeenCalled()
 })
})

Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html

error: passing xxx as 'this' argument of xxx discards qualifiers

Actually the C++ standard (i.e. C++ 0x draft) says (tnx to @Xeo & @Ben Voigt for pointing that out to me):

23.2.4 Associative containers
5 For set and multiset the value type is the same as the key type. For map and multimap it is equal to pair. Keys in an associative container are immutable.
6 iterator of an associative container is of the bidirectional iterator category. For associative containers where the value type is the same as the key type, both iterator and const_iterator are constant iterators. It is unspecified whether or not iterator and const_iterator are the same type.

So VC++ 2008 Dinkumware implementation is faulty.


Old answer:

You got that error because in certain implementations of the std lib the set::iterator is the same as set::const_iterator.

For example libstdc++ (shipped with g++) has it (see here for the entire source code):

typedef typename _Rep_type::const_iterator            iterator;
typedef typename _Rep_type::const_iterator            const_iterator;

And in SGI's docs it states:

iterator       Container  Iterator used to iterate through a set.
const_iterator Container  Const iterator used to iterate through a set. (Iterator and const_iterator are the same type.)

On the other hand VC++ 2008 Express compiles your code without complaining that you're calling non const methods on set::iterators.

Tooltip on image

Using javascript, you can set tooltips for all the images on the page.

_x000D_
_x000D_
<!DOCTYPE html>
<html>
    <body>
    <img src="http://sushmareddy.byethost7.com/dist/img/buffet.png" alt="Food">
    <img src="http://sushmareddy.byethost7.com/dist/img/uthappizza.png" alt="Pizza">
     <script>
     //image objects
     var imageEls = document.getElementsByTagName("img");
     //Iterating
     for(var i=0;i<imageEls.length;i++){
        imageEls[i].title=imageEls[i].alt;
        //OR
        //imageEls[i].title="Title of your choice";
     }
        </script>
    </body>
</html>
_x000D_
_x000D_
_x000D_

How to convert an array of key-value tuples into an object

In my case, all other solutions didn't work, but this one did:

obj = {...arr}

my arr is in a form: [name: "the name", email: "[email protected]"]

JavaScript/regex: Remove text between parentheses

If you need to remove text inside nested parentheses, too, then:

        var prevStr;
        do {
            prevStr = str;
            str = str.replace(/\([^\)\(]*\)/, "");
        } while (prevStr != str);

How to set the Android progressbar's height?

This is the progress bar I have used.

<ProgressBar
     android:padding="@dimen/dimen_5"
     android:layout_below="@+id/txt_chklist_progress"
     android:id="@+id/pb_media_progress"
     style="@style/MyProgressBar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:progress="70"
     android:scaleY="5"
     android:max="100"
     android:progressBackgroundTint="@color/white"
     android:progressTint="@color/green_above_avg" />

And this is my style tag

 <style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressBackgroundTint">@color/white</item>
    <item name="android:progressTint">@color/green_above_avg</item>
</style>

How to print out a variable in makefile

No need to modify the Makefile.

$ cat printvars.mak
print-%:
        @echo '$*=$($*)'

$ cd /to/Makefile/dir
$ make -f ~/printvars.mak -f Makefile print-VARIABLE

How do I generate random number for each row in a TSQL Select?

If you want to generate a random number between 1 and 14 inclusive.

SELECT CONVERT(int, RAND() * (14 - 1) + 1)

OR

SELECT ABS(CHECKSUM(NewId())) % (14 -1) + 1

How to post JSON to a server using C#?

Some different and clean way to achieve this is by using HttpClient like this:

public async Task<HttpResponseMessage> PostResult(string url, ResultObject resultObject)
{
    using (var client = new HttpClient())
    {
        HttpResponseMessage response = new HttpResponseMessage();
        try
        {
            response = await client.PostAsJsonAsync(url, resultObject);
        }
        catch (Exception ex)
        {
            throw ex
        }
        return response;
     }
}

CSS div 100% height

Set the html tag, too. This way no weird position hacks are required.

html, body {height: 100%}

ADB - Android - Getting the name of the current activity

dumpsys window windows gives more detail about the current activity:

adb shell "dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'"
  mCurrentFocus=Window{41d2c970 u0 com.android.launcher/com.android.launcher2.Launcher}
  mFocusedApp=AppWindowToken{4203c170 token=Token{41b77280 ActivityRecord{41b77a28 u0 com.android.launcher/com.android.launcher2.Launcher t3}}}

However in order to find the process ID (e.g. to kill the current activity), use dumpsys activity, and grep on "top-activity":

adb shell "dumpsys activity | grep top-activity"
    Proc # 0: fore  F/A/T  trm: 0 3074:com.android.launcher/u0a8 (top-activity)

adb shell "kill 3074"

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

As to why a 32-bit JVM is used instead of a 64-bit one, the reason is not technical but rather administrative/bureaucratic ...

When I was working for BEA, we found that the average application actually ran slower in a 64-bit JVM, then it did when running in a 32-bit JVM. In some cases, the performance hit was as high as 25% slower. So, unless your application really needs all that extra memory, you were better off setting up more 32-bit servers.

As I recall, the three most common technical justifications for using a 64-bit that BEA professional services personnel ran into were:

  1. The application was manipulating multiple massive images,
  2. The application was doing massive number crunching,
  3. The application had a memory leak, the customer was the prime on a government contract, and they didn't want to take the time and the expense of tracking down the memory leak. (Using a massive memory heap would increase the MTBF and the prime would still get paid)

.

javascript how to create a validation error message without using alert

JavaScript

<script language="javascript">
        var flag=0;
        function username()
        {
            user=loginform.username.value;
            if(user=="")
            {
                document.getElementById("error0").innerHTML="Enter UserID";
                flag=1;
            }
        }   
        function password()
        {
            pass=loginform.password.value;
            if(pass=="")
            {
                document.getElementById("error1").innerHTML="Enter password";   
                flag=1;
            }
        }

        function check(form)
        {
            flag=0;
            username();
            password();
            if(flag==1)
                return false;
            else
                return true;
        }

    </script>

HTML

<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">



                    <div id="error0"></div>
                    <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
               controls">
                    <div id="error1"></div>
                    <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">

                    <button type="submit" class="btn">Sign in</button>
                </div>
            </div>
        </form>

Visual Studio Code: Auto-refresh file changes

VSCode will never refresh the file if you have changes in that file that are not saved to disk. However, if the file is open and does not have changes, it will replace with the changes on disk, that is true.

There is currently no way to disable this behaviour.

JavaScript Infinitely Looping slideshow with delays?

Expanding on Ender's answer, let's explore our options with the improvements from ES2015.


First off, the problem in the asker's code is the fact that setTimeout is asynchronous while loops are synchronous. So the logical flaw is that they wrote multiple calls to an asynchronous function from a synchronous loop, expecting them to execute synchronously.

function slide() {
    var num = 0;
    for (num=0;num<=10;num++) {
        setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
        setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
        setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
        setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
    }
}

What happens in reality, though, is that...

  • The loop "simultaneously" creates 44 async timeouts set to execute 3, 6, 9 and 12 seconds in the future. Asker expected the 44 calls to execute one-after-the-other, but instead, they all execute simultaneously.
  • 3 seconds after the loop finishes, container's marginLeft is set to "-600px" 11 times.
  • 3 seconds after that, marginLeft is set to "-1200px" 11 times.
  • 3 seconds later, "-1800px", 11 times.

And so on.

You could solve this by changing it to:

function setMargin(margin){
    return function(){
        document.querySelector("#container").style.marginLeft = margin;
    };
}

function slide() {
    for (let num = 0; num <= 10; ++num) {
        setTimeout(setMargin("-600px"), + (3000 * (num + 1)));
        setTimeout(setMargin("-1200px"), + (6000 * (num + 1)));
        setTimeout(setMargin("-1800px"), + (9000 * (num + 1)));
        setTimeout(setMargin("0px"), + (12000 * (num + 1)));
    }
}

But that is just a lazy solution that doesn't address the other issues with this implementation. There's a lot of hardcoding and general sloppiness here that ought to be fixed.

Lessons learnt from a decade of experience

As mentioned at the top of this answer, Ender already proposed a solution, but I would like to add on to it, to factor in good practice and modern innovations in the ECMAScript specification.

function format(str, ...args){
    return str.split(/(%)/).map(part => (part == "%") ? (args.shift()) : (part)).join("");
}

function slideLoop(margin, selector){
    const multiplier = -600;
    let contStyle = document.querySelector(selector).style;

    return function(){
        margin = ++margin % 4;
        contStyle.marginLeft = format("%px", margin * multiplier);
    }
}

function slide() {    
    return setInterval(slideLoop(0, "#container"), 3000);
}

Let's go over how this works for the total beginners (note that not all of this is directly related to the question):

format

function format

It's immensely useful to have a printf-like string formatter function in any language. I don't understand why JavaScript doesn't seem to have one.

format(str, ...args)

... is a snazzy feature added in ES6 that lets you do lots of stuff. I believe it's called the spread operator. Syntax: ...identifier or ...array. In a function header, you can use it to specify variable arguments, and it will take every argument at and past the position of said variable argument, and stuff them into an array. You can also call a function with an array like so: args = [1, 2, 3]; i_take_3_args(...args), or you can take an array-like object and transform it into an array: ...document.querySelectorAll("div.someclass").forEach(...). This would not be possible without the spread operator, because querySelectorAll returns an "element list", which isn't a true array.

str.split(/(%)/)

I'm not good at explaining how regex works. JavaScript has two syntaxes for regex. There's the OO way (new RegExp("regex", "gi")) and there's the literal way (/insert regex here/gi). I have a profound hatred for regex because the terse syntax it encourages often does more harm than good (and also because they're extremely non-portable), but there are some instances where regex is helpful, like this one. Normally, if you called split with "%" or /%/, the resulting array would exclude the "%" delimiters from the array. But for the algorithm used here, we need them included. /(%)/ was the first thing I tried and it worked. Lucky guess, I suppose.

.map(...)

map is a functional idiom. You use map to apply a function to a list. Syntax: array.map(function). Function: must return a value and take 1-2 arguments. The first argument will be used to hold each value in the array, while the second will be used to hold the current index in the array. Example: [1,2,3,4,5].map(x => x * x); // returns [1,4,9,16,25]. See also: filter, find, reduce, forEach.

part => ...

This is an alternative form of function. Syntax: argument-list => return-value, e.g. (x, y) => (y * width + x), which is equivalent to function(x, y){return (y * width + x);}.

(part == "%") ? (args.shift()) : (part)

The ?: operator pair is a 3-operand operator called the ternary conditional operator. Syntax: condition ? if-true : if-false, although most people call it the "ternary" operator, since in every language it appears in, it's the only 3-operand operator, every other operator is binary (+, &&, |, =) or unary (++, ..., &, *). Fun fact: some languages (and vendor extensions of languages, like GNU C) implement a two-operand version of the ?: operator with syntax value ?: fallback, which is equivalent to value ? value : fallback, and will use fallback if value evaluates to false. They call it the Elvis Operator.

I should also mention the difference between an expression and an expression-statement, as I realize this may not be intuitive to all programmers. An expression represents a value, and can be assigned to an l-value. An expression can be stuffed inside parentheses and not be considered a syntax error. An expression can itself be an l-value, although most statements are r-values, as the only l-value expressions are those formed from an identifier or (e.g. in C) from a reference/pointer. Functions can return l-values, but don't count on it. Expressions can also be compounded from other, smaller expressions. (1, 2, 3) is an expression formed from three r-value expressions joined by two comma operators. The value of the expression is 3. expression-statements, on the other hand, are statements formed from a single expression. ++somevar is an expression, as it can be used as the r-value in the assignment expression-statement newvar = ++somevar; (the value of the expression newvar = ++somevar, for example, is the value that gets assigned to newvar). ++somevar; is also an expression-statement.

If ternary operators confuse you at all, apply what I just said to the ternary operator: expression ? expression : expression. Ternary operator can form an expression or an expression-statement, so both of these things:

smallest = (a < b) ? (a) : (b);
(valueA < valueB) ? (backup_database()) : (nuke_atlantic_ocean());

are valid uses of the operator. Please don't do the latter, though. That's what if is for. There are cases for this sort of thing in e.g. C preprocessor macros, but we're talking about JavaScript here.

args.shift()

Array.prototype.shift. It's the mirror version of pop, ostensibly inherited from shell languages where you can call shift to move onto the next argument. shift "pops" the first argument out of the array and returns it, mutating the array in the process. The inverse is unshift. Full list:

array.shift()
    [1,2,3] -> [2,3], returns 1
array.unshift(new-element)
    [element, ...] -> [new-element, element, ...]
array.pop()
    [1,2,3] -> [1,2], returns 3
array.push(new-element)
    [..., element] -> [..., element, new-element]

See also: slice, splice

.join("")

Array.prototype.join(string). This function turns an array into a string. Example: [1,2,3].join(", ") -> "1, 2, 3"

slide

return setInterval(slideLoop(0, "#container"), 3000);

First off, we return setInterval's return value so that it may be used later in a call to clearInterval. This is important, because JavaScript won't clean that up by itself. I strongly advise against using setTimeout to make a loop. That is not what setTimeout is designed for, and by doing that, you're reverting to GOTO. Read Dijkstra's 1968 paper, Go To Statement Considered Harmful, to understand why GOTO loops are bad practice.

Second off, you'll notice I did some things differently. The repeating interval is the obvious one. This will run forever until the interval is cleared, and at a delay of 3000ms. The value for the callback is the return value of another function, which I have fed the arguments 0 and "#container". This creates a closure, and you will understand how this works shortly.

slideLoop

function slideLoop(margin, selector)

We take margin (0) and selector ("#container") as arguments. The margin is the initial margin value and the selector is the CSS selector used to find the element we're modifying. Pretty straightforward.

const multiplier = -600;
let contStyle = document.querySelector(selector).style;

I've moved some of the hard coded elements up. Since the margins are in multiples of -600, we have a clearly labeled constant multiplier with that base value.

I've also created a reference to the element's style property via the CSS selector. Since style is an object, this is safe to do, as it will be treated as a reference rather than a copy (read up on Pass By Sharing to understand these semantics).

return function(){
    margin = ++margin % 4;
    contStyle.marginLeft = format("%px", margin * multiplier);
}

Now that we have the scope defined, we return a function that uses said scope. This is called a closure. You should read up on those, too. Understanding JavaScript's admittedly bizarre scoping rules will make the language a lot less painful in the long run.

margin = ++margin % 4;
contStyle.marginLeft = format("%px", margin * multiplier);

Here, we simply increment margin and modulus it by 4. The sequence of values this will produce is 1->2->3->0->1->..., which mimics exactly the behavior from the question without any complicated or hard-coded logic.

Afterwards, we use the format function defined earlier to painlessly set the marginLeft CSS property of the container. It's set to the currnent margin value multiplied by the multiplier, which as you recall was set to -600. -600 -> -1200 -> -1800 -> 0 -> -600 -> ...


There are some important differences between my version and Ender's, which I mentioned in a comment on their answer. I'm gonna go over the reasoning now:

Use document.querySelector(css_selector) instead of document.getElementById(id)

querySelector was added in ES6, if I'm not mistaken. querySelector (returns first found element) and querySelectorAll (returns a list of all found elements) are part of the prototype chain of all DOM elements (not just document), and take a CSS selector, so there are other ways to find an element than just by its ID. You can search by ID (#idname), class (.classname), relationships (div.container div div span, p:nth-child(even)), and attributes (div[name], a[href=https://google.com]), among other things.

Always track setInterval(fn, interval)'s return value so it can later be closed with clearInterval(interval_id)

It's not good design to leave an interval running forever. It's also not good design to write a function that calls itself via setTimeout. That is no different from a GOTO loop. The return value of setInterval should be stored and used to clear the interval when it's no longer needed. Think of it as a form of memory management.

Put the interval's callback into its own formal function for readability and maintainability

Constructs like this

setInterval(function(){
    ...
}, 1000);

Can get clunky pretty easily, especially if you are storing the return value of setInterval. I strongly recommend putting the function outside of the call and giving it a name so that it's clear and self-documenting. This also makes it possible to call a function that returns an anonymous function, in case you're doing stuff with closures (a special type of object that contains the local state surrounding a function).

Array.prototype.forEach is fine.

If state is kept with the callback, the callback should be returned from another function (e.g. slideLoop) to form a closure

You don't want to mush state and callbacks together the way Ender did. This is mess-prone and can become hard to maintain. The state should be in the same function that the anonymous function comes from, so as to clearly separate it from the rest of the world. A better name for slideLoop could be makeSlideLoop, just to make it extra clear.

Use proper whitespace. Logical blocks that do different things should be separated by one empty line

This:

print(some_string);

if(foo && bar)
    baz();

while((some_number = some_fn()) !== SOME_SENTINEL && ++counter < limit)
    ;

quux();

is much easier to read than this:

print(some_string);
if(foo&&bar)baz();
while((some_number=some_fn())!==SOME_SENTINEL&&++counter<limit);
quux();

A lot of beginners do this. Including little 14-year-old me from 2009, and I didn't unlearn that bad habit until probably 2013. Stop trying to crush your code down so small.

Avoid "string" + value + "string" + .... Make a format function or use String.prototype.replace(string/regex, new_string)

Again, this is a matter of readability. This:

format("Hello %! You've visited % times today. Your score is %/% (%%).",
    name, visits, score, maxScore, score/maxScore * 100, "%"
);

is much easier to read than this horrific monstrosity:

"Hello " + name + "! You've visited " + visits + "% times today. " + 
"Your score is " + score + "/" + maxScore + " (" + (score/maxScore * 100) +
"%).",

edit: I'm pleased to point out that I made in error in the above snippet, which in my opinion is a great demonstration of how error-prone this method of string building is.

visits + "% times today"
          ^ whoops

It's a good demonstration because the entire reason I made that error, and didn't notice it for as long as I did(n't), is because the code is bloody hard to read.

Always surround the arguments of your ternary expressions with parens. It aids readability and prevents bugs.

I borrow this rule from the best practices surrounding C preprocessor macros. But I don't really need to explain this one; see for yourself:

let myValue = someValue < maxValue ? someValue * 2 : 0;
let myValue = (someValue < maxValue) ? (someValue * 2) : (0);

I don't care how well you think you understand your language's syntax, the latter will ALWAYS be easier to read than the former, and readability is the the only argument that is necessary. You read thousands of times more code than you write. Don't be a jerk to your future self long-term just so you can pat yourself on the back for being clever in the short term.

How to change the color of winform DataGridview header?

It can be done.

From the designer: Select your DataGridView Open the Properties Navigate to ColumnHeaderDefaultCellStype Hit the button to edit the style.

You can also do it programmatically:

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Purple;

Hope that helps!

Python exit commands - why so many and when should each be used?

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported.

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

Counting the number of non-NaN elements in a numpy ndarray in Python

np.count_nonzero(~np.isnan(data))

~ inverts the boolean matrix returned from np.isnan.

np.count_nonzero counts values that is not 0\false. .sum should give the same result. But maybe more clearly to use count_nonzero

Testing speed:

In [23]: data = np.random.random((10000,10000))

In [24]: data[[np.random.random_integers(0,10000, 100)],:][:, [np.random.random_integers(0,99, 100)]] = np.nan

In [25]: %timeit data.size - np.count_nonzero(np.isnan(data))
1 loops, best of 3: 309 ms per loop

In [26]: %timeit np.count_nonzero(~np.isnan(data))
1 loops, best of 3: 345 ms per loop

In [27]: %timeit data.size - np.isnan(data).sum()
1 loops, best of 3: 339 ms per loop

data.size - np.count_nonzero(np.isnan(data)) seems to barely be the fastest here. other data might give different relative speed results.

Wrapping a react-router Link in an html button

With styled components this can be easily achieved

First Design a styled button

import styled from "styled-components";
import {Link} from "react-router-dom";

const Button = styled.button`
  background: white;
  color:red;
  font-size: 1em;
  margin: 1em;
  padding: 0.25em 1em;
  border: 2px solid red;
  border-radius: 3px;
`
render(
    <Button as={Link} to="/home"> Text Goes Here </Button>
);

check styled component's home for more

How to change the Jupyter start-up folder

cd into the directory or a parent directory (with the intended directory you will work nested in it).

Note it must be a folder (E:\> --- This will not work)

Then just run the command jupyter notebook

Remove all items from RecyclerView

Avoid deleting your items in a for loop and calling notifyDataSetChanged in every iteration. Instead just call the clear method in your list myList.clear(); and then notify your adapter

public void clearData() {
    myList.clear(); // clear list
    mAdapter.notifyDataSetChanged(); // let your adapter know about the changes and reload view.
}

How do I add records to a DataGridView in VB.Net?

I think you should build a dataset/datatable in code and bind the grid to that.

How to edit incorrect commit message in Mercurial?

Well, I used to do this way:

Imagine, you have 500 commits, and your erroneous commit message is in r.498.

hg qimport -r 498:tip
hg qpop -a
joe .hg/patches/498.diff
(change the comment, after the mercurial header)
hg qpush -a
hg qdelete -r qbase:qtip

Implementing a simple file download servlet

Assuming you have access to servlet as below

http://localhost:8080/myapp/download?id=7

I need to create a servlet and register it to web.xml

web.xml

<servlet>
     <servlet-name>DownloadServlet</servlet-name>
     <servlet-class>com.myapp.servlet.DownloadServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>DownloadServlet</servlet-name>
     <url-pattern>/download</url-pattern>
</servlet-mapping>

DownloadServlet.java

public class DownloadServlet extends HttpServlet {


    protected void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

         String id = request.getParameter("id");

         String fileName = "";
         String fileType = "";
         // Find this file id in database to get file name, and file type

         // You must tell the browser the file type you are going to send
         // for example application/pdf, text/plain, text/html, image/jpg
         response.setContentType(fileType);

         // Make sure to show the download dialog
         response.setHeader("Content-disposition","attachment; filename=yourcustomfilename.pdf");

         // Assume file name is retrieved from database
         // For example D:\\file\\test.pdf

         File my_file = new File(fileName);

         // This should send the file to browser
         OutputStream out = response.getOutputStream();
         FileInputStream in = new FileInputStream(my_file);
         byte[] buffer = new byte[4096];
         int length;
         while ((length = in.read(buffer)) > 0){
            out.write(buffer, 0, length);
         }
         in.close();
         out.flush();
    }
}

How can I pass a class member function as a callback?

Necromancing.
I think the answers to date are a little unclear.

Let's make an example:

Supposed you have an array of pixels (array of ARGB int8_t values)

// A RGB image
int8_t* pixels = new int8_t[1024*768*4];

Now you want to generate a PNG. To do so, you call the function toJpeg

bool ok = toJpeg(writeByte, pixels, width, height);

where writeByte is a callback-function

void writeByte(unsigned char oneByte)
{
    fputc(oneByte, output);
}

The problem here: FILE* output has to be a global variable.
Very bad if you're in a multithreaded environment (e.g. a http-server).

So you need some way to make output a non-global variable, while retaining the callback signature.

The immediate solution that springs into mind is a closure, which we can emulate using a class with a member function.

class BadIdea {
private:
    FILE* m_stream;
public:
    BadIdea(FILE* stream)  {
        this->m_stream = stream;
    }

    void writeByte(unsigned char oneByte){
            fputc(oneByte, this->m_stream);
    }

};

And then do

FILE *fp = fopen(filename, "wb");
BadIdea* foobar = new BadIdea(fp);

bool ok = TooJpeg::writeJpeg(foobar->writeByte, image, width, height);
delete foobar;
fflush(fp);
fclose(fp);

However, contrary to expectations, this does not work.

The reason is, C++ member functions are kinda implemented like C# extension functions.

So you have

class/struct BadIdea
{
    FILE* m_stream;
}

and

static class BadIdeaExtensions
{
    public static writeByte(this BadIdea instance, unsigned char oneByte)
    {
         fputc(oneByte, instance->m_stream);
    }

}

So when you want to call writeByte, you need pass not only the address of writeByte, but also the address of the BadIdea-instance.

So when you have a typedef for the writeByte procedure, and it looks like this

typedef void (*WRITE_ONE_BYTE)(unsigned char);

And you have a writeJpeg signature that looks like this

bool writeJpeg(WRITE_ONE_BYTE output, uint8_t* pixels, uint32_t 
 width, uint32_t height))
    { ... }

it's fundamentally impossible to pass a two-address member function to a one-address function pointer (without modifying writeJpeg), and there's no way around it.

The next best thing that you can do in C++, is using a lambda-function:

FILE *fp = fopen(filename, "wb");
auto lambda = [fp](unsigned char oneByte) { fputc(oneByte, fp);  };
bool ok = TooJpeg::writeJpeg(lambda, image, width, height);

However, because lambda is doing nothing different, than passing an instance to a hidden class (such as the "BadIdea"-class), you need to modify the signature of writeJpeg.

The advantage of lambda over a manual class, is that you just need to change one typedef

typedef void (*WRITE_ONE_BYTE)(unsigned char);

to

using WRITE_ONE_BYTE = std::function<void(unsigned char)>; 

And then you can leave everything else untouched.

You could also use std::bind

auto f = std::bind(&BadIdea::writeByte, &foobar);

But this, behind the scene, just creates a lambda function, which then also needs the change in typedef.

So no, there is no way to pass a member function to a method that requires a static function-pointer.

But lambdas are the easy way around, provided that you have control over the source.
Otherwise, you're out of luck.
There's nothing you can do with C++.

Note:
std::function requires #include <functional>

However, since C++ allows you to use C as well, you can do this with libffcall in plain C, if you don't mind linking a dependency.

Download libffcall from GNU (at least on ubuntu, don't use the distro-provided package - it is broken), unzip.

./configure
make
make install

gcc main.c -l:libffcall.a -o ma

main.c:

#include <callback.h>

// this is the closure function to be allocated 
void function (void* data, va_alist alist)
{
     int abc = va_arg_int(alist);

     printf("data: %08p\n", data); // hex 0x14 = 20
     printf("abc: %d\n", abc);

     // va_start_type(alist[, return_type]);
     // arg = va_arg_type(alist[, arg_type]);
     // va_return_type(alist[[, return_type], return_value]);

    // va_start_int(alist);
    // int r = 666;
    // va_return_int(alist, r);
}



int main(int argc, char* argv[])
{
    int in1 = 10;

    void * data = (void*) 20;
    void(*incrementer1)(int abc) = (void(*)()) alloc_callback(&function, data);
    // void(*incrementer1)() can have unlimited arguments, e.g. incrementer1(123,456);
    // void(*incrementer1)(int abc) starts to throw errors...
    incrementer1(123);
    // free_callback(callback);
    return EXIT_SUCCESS;
}

And if you use CMake, add the linker library after add_executable

add_library(libffcall STATIC IMPORTED)
set_target_properties(libffcall PROPERTIES
        IMPORTED_LOCATION /usr/local/lib/libffcall.a)
target_link_libraries(BitmapLion libffcall)

or you could just dynamically link libffcall

target_link_libraries(BitmapLion ffcall)

Note:
You might want to include the libffcall headers and libraries, or create a cmake project with the contents of libffcall.

javascript setTimeout() not working

This line:

setTimeout(startTimer(), startInterval); 

You're invoking startTimer(). Instead, you need to pass it in as a function to be invoked, like so:

setTimeout(startTimer, startInterval);

Shell script to capture Process ID and kill it if exist

This should kill all processes matching the grep that you are permitted to kill.

-9 means "Kill all processes you can kill".

kill -9 $(ps -ef | grep [s]yncapp | awk '{print $2}')

Getting an element from a Set

I know, this has been asked and answered long ago, however if anyone is interested, here is my solution - custom set class backed by HashMap:

http://pastebin.com/Qv6S91n9

You can easily implement all other Set methods.

How to make PopUp window in java

The same answer : JOptionpane with an example :)

package experiments;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class CreateDialogFromOptionPane {

    public static void main(final String[] args) {
        final JFrame parent = new JFrame();
        JButton button = new JButton();

        button.setText("Click me to show dialog!");
        parent.add(button);
        parent.pack();
        parent.setVisible(true);

        button.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                String name = JOptionPane.showInputDialog(parent,
                        "What is your name?", null);
            }
        });
    }
}

enter image description here

Create a tag in a GitHub repository

For creating git tag you can simply run git tag <tagname> command by replacing with the actual name of the tag. Here is a complete tutorial on the basics of managing git tags: https://www.drupixels.com/blog/git-tags-create-push-remote-checkout-and-much-more

The following untracked working tree files would be overwritten by merge, but I don't care

The problem is that you are not tracking the files locally but identical files are tracked remotely so in order to "pull" your system would be forced to overwrite the local files which are not version controlled.

Try running

git add * 
git stash
git pull

This will track all files, remove all of your local changes to those files, and then get the files from the server.

How to check task status in Celery?

for simple tasks, we can use http://flower.readthedocs.io/en/latest/screenshots.html and http://policystat.github.io/jobtastic/ to do the monitoring.

and for complicated tasks, say a task which deals with a lot other modules. We recommend manually record the progress and message on the specific task unit.

Convert seconds to hh:mm:ss in Python

If you need to do this a lot, you can precalculate all possible strings for number of seconds in a day:

try:
    from itertools import product
except ImportError:
    def product(*seqs):
        if len(seqs) == 1:
            for p in seqs[0]:
                yield p,
        else:
            for s in seqs[0]:
                for p in product(*seqs[1:]):
                    yield (s,) + p

hhmmss = []
for (h, m, s) in product(range(24), range(60), range(60)):
    hhmmss.append("%02d:%02d:%02d" % (h, m, s))

Now conversion of seconds to format string is a fast indexed lookup:

print hhmmss[12345]

prints

'03:25:45'

EDIT:

Updated to 2020, removing Py2 compatibility ugliness, and f-strings!

import sys
from itertools import product


hhmmss = [f"{h:02d}:{m:02d}:{s:02d}"
             for h, m, s in product(range(24), range(60), range(60))]

# we can still just index into the list, but define as a function
# for common API with code below
seconds_to_str = hhmmss.__getitem__

print(seconds_to_str(12345))

How much memory does this take? sys.getsizeof of a list won't do, since it will just give us the size of the list and its str refs, but not include the memory of the strs themselves:

# how big is a list of 24*60*60 8-character strs?
list_size = sys.getsizeof(hhmmss) + sum(sys.getsizeof(s) for s in hhmmss)
print("{:,}".format(list_size))

prints:

5,657,616

What if we just had one big str? Every value is exactly 8 characters long, so we can slice into this str and get the correct str for second X of the day:

hhmmss_str = ''.join([f"{h:02d}:{m:02d}:{s:02d}"
                      for h, m, s in product(range(24),
                                             range(60),
                                             range(60))])
def seconds_to_str(n):
    loc = n * 8
    return hhmmss_str[loc: loc+8]

print(seconds_to_str(12345))

Did that save any space?

# how big is a str of 24*60*60*8 characters?
str_size = sys.getsizeof(hhmmss_str)
print("{:,}".format(str_size))

prints:

691,249

Reduced to about this much:

print(str_size / list_size)

prints:

0.12218026108523448

On the performance side, this looks like a classic memory vs. CPU tradeoff:

import timeit

print("\nindex into pre-calculated list")
print(timeit.timeit("hhmmss[6]", '''from itertools import product; hhmmss = [f"{h:02d}:{m:02d}:{s:02d}"
                     for h, m, s in product(range(24),
                                             range(60),
                                             range(60))]'''))
print("\nget slice from pre-calculated str")
print(timeit.timeit("hhmmss_str[6*8:7*8]", '''from itertools import product; hhmmss_str=''.join([f"{h:02d}:{m:02d}:{s:02d}"
                     for h, m, s in product(range(24),
                                             range(60),
                                             range(60))])'''))

print("\nuse datetime.timedelta from stdlib")
print(timeit.timeit("timedelta(seconds=6)", "from datetime import timedelta"))
print("\ninline compute of h, m, s using divmod")
print(timeit.timeit("n=6;m,s=divmod(n,60);h,m=divmod(m,60);f'{h:02d}:{m:02d}:{s:02d}'"))

On my machine I get:

index into pre-calculated list
0.0434853

get slice from pre-calculated str
0.1085147

use datetime.timedelta from stdlib
0.7625738

inline compute of h, m, s using divmod
2.0477764

What's the difference between an Angular component and module

Well, it's too late to post an answer, but I feel my explanation will be easy to understand for beginners with Angular. The following is one of the examples that I give during my presentation.

Consider your angular Application as a building. A building can have N number of apartments in it. An apartment is considered as a module. An Apartment can then have N number of rooms which correspond to the building blocks of an Angular application named components.

Now each apartment (Module)` will have rooms (Components), lifts (Services) to enable larger movement in and out the apartments, wires (Pipes) to transform around and make it useful in the apartments.

You will also have places like swimming pool, tennis court which are being shared by all building residents. So these can be considered as components inside SharedModule.

Basically, the difference is as follows,

Table showing key differences between Module and Component

Follow my slides to understand the building blocks of an Angular application

Here is my session on Building Blocks of Angular for beginners

Assigning a function to a variable

lambda should be useful for this case. For example,

  1. create function y=x+1 y=lambda x:x+1

  2. call the function y(1) then return 2.

ERROR 1130 (HY000): Host '' is not allowed to connect to this MySQL server

Go to PhpMyAdmin, click on desired database, go to Privilages tab and create new user "remote", and give him all privilages and in host field set "Any host" option(%).

Fragments within Fragments

I have an application that I am developing that is laid out similar with Tabs in the Action Bar that launches fragments, some of these Fragments have multiple embedded Fragments within them.

I was getting the same error when I tried to run the application. It seems like if you instantiate the Fragments within the xml layout after a tab was unselected and then reselected I would get the inflator error.

I solved this replacing all the fragments in xml with Linearlayouts and then useing a Fragment manager/ fragment transaction to instantiate the fragments everything seems to working correctly at least on a test level right now.

I hope this helps you out.

Fatal error: Out of memory, but I do have plenty of memory (PHP)

I know it's an old thread, but here's my experience getting it resolved.

My server is a hosted service running Apache.

My script crashed with out of memory at 6Mb, when my limit Was 256Mb - crazy, yeah?

It is being called synchronously via an http callback, from javascript running on my client, and crashed after around 550 calls. After much time wasted with incompetent "Escalated Support" guys, my script now magically runs.

They said all they did was to reset php.ini, but I checked the differences: enter image description here

No changes there that I can see that could have a bearing on an Out of Memory error.

I suspect a memory leak in the web server which my "Escalated Support" guy is hiding under the guise of resetting the php.ini. And, really, I'm not a conspiracy theorist.

javascript date + 7 days

_x000D_
_x000D_
var date = new Date();_x000D_
date.setDate(date.getDate() + 7);_x000D_
_x000D_
console.log(date);
_x000D_
_x000D_
_x000D_

And yes, this also works if date.getDate() + 7 is greater than the last day of the month. See MDN for more information.

What is the Python equivalent of static variables inside a function?

I write a simple function to use static variables:

def Static():
    ### get the func object by which Static() is called.
    from inspect import currentframe, getframeinfo
    caller = currentframe().f_back
    func_name = getframeinfo(caller)[2]
    # print(func_name)
    caller = caller.f_back
    func = caller.f_locals.get(
        func_name, caller.f_globals.get(
            func_name
        )
    )
    
    class StaticVars:
        def has(self, varName):
            return hasattr(self, varName)
        def declare(self, varName, value):
            if not self.has(varName):
                setattr(self, varName, value)

    if hasattr(func, "staticVars"):
        return func.staticVars
    else:
        # add an attribute to func
        func.staticVars = StaticVars()
        return func.staticVars

How to use:

def myfunc(arg):
    if Static().has('test1'):
        Static().test += 1
    else:
        Static().test = 1
    print(Static().test)

    # declare() only takes effect in the first time for each static variable.
    Static().declare('test2', 1)
    print(Static().test2)
    Static().test2 += 1

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I was able to install libc6 2.17 in Debian Wheezy by editing the recommendations in perror's answer:

IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1. Then you can stop x (slim) with sudo /etc/init.d/slim stop

(replace slim with mdm or lightdm or whatever)

Add the following line to the file /etc/apt/sources.list:

deb http://ftp.debian.org/debian experimental main

Should be changed to:

deb http://ftp.debian.org/debian sid main

Then follow the rest of perror's post:

Update your package database:

apt-get update

Install the eglibc package:

apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg

IMPORTANT
After done updating libc6, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main), or else you risk upgrading your whole distro to sid.

Hope this helps. It took me a while to figure out.

How to write a confusion matrix in Python?

A Dependency Free Multiclass Confusion Matrix

# A Simple Confusion Matrix Implementation
def confusionmatrix(actual, predicted, normalize = False):
    """
    Generate a confusion matrix for multiple classification
    @params:
        actual      - a list of integers or strings for known classes
        predicted   - a list of integers or strings for predicted classes
        normalize   - optional boolean for matrix normalization
    @return:
        matrix      - a 2-dimensional list of pairwise counts
    """
    unique = sorted(set(actual))
    matrix = [[0 for _ in unique] for _ in unique]
    imap   = {key: i for i, key in enumerate(unique)}
    # Generate Confusion Matrix
    for p, a in zip(predicted, actual):
        matrix[imap[p]][imap[a]] += 1
    # Matrix Normalization
    if normalize:
        sigma = sum([sum(matrix[imap[i]]) for i in unique])
        matrix = [row for row in map(lambda i: list(map(lambda j: j / sigma, i)), matrix)]
    return matrix

The approach here is to pair up the unique classes found in the actual vector into a 2-dimensional list. From there, we simply iterate through the zipped actual and predicted vectors and populate the counts using the indices to access the matrix positions.

Usage

cm = confusionmatrix(
    [1, 1, 2, 0, 1, 1, 2, 0, 0, 1], # actual
    [0, 1, 1, 0, 2, 1, 2, 2, 0, 2]  # predicted
)

# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]

Note: the actual classes are along the columns and the predicted classes are along the rows.

# Actual
# 0  1  2
  #  #  #   
[[2, 1, 0], # 0
 [0, 2, 1], # 1  Predicted
 [1, 2, 1]] # 2

Class Names Can be Strings or Integers

cm = confusionmatrix(
    ["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
    ["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"]  # predicted
)

# And The Output
print(cm)
[[2, 1, 0], [0, 2, 1], [1, 2, 1]]

You Can Also Return The Matrix With Proportions (Normalization)

cm = confusionmatrix(
    ["B", "B", "C", "A", "B", "B", "C", "A", "A", "B"], # actual
    ["A", "B", "B", "A", "C", "B", "C", "C", "A", "C"], # predicted
    normalize = True
)

# And The Output
print(cm)
[[0.2, 0.1, 0.0], [0.0, 0.2, 0.1], [0.1, 0.2, 0.1]]

A More Robust Solution

Since writing this post, I've updated my library implementation to be a class that uses a confusion matrix representation internally to compute statistics, in addition to pretty printing the confusion matrix itself. See this Gist.

Example Usage

# Actual & Predicted Classes
actual      = ["A", "B", "C", "C", "B", "C", "C", "B", "A", "A", "B", "A", "B", "C", "A", "B", "C"]
predicted   = ["A", "B", "B", "C", "A", "C", "A", "B", "C", "A", "B", "B", "B", "C", "A", "A", "C"]

# Initialize Performance Class
performance = Performance(actual, predicted)

# Print Confusion Matrix
performance.tabulate()

With the output:

===================================
        A?      B?      C?

A?      3       2       1

B?      1       4       1

C?      1       0       4

Note: class? = Predicted, class? = Actual
===================================

And for the normalized matrix:

# Print Normalized Confusion Matrix
performance.tabulate(normalized = True)

With the normalized output:

===================================
        A?      B?      C?

A?      17.65%  11.76%  5.88%

B?      5.88%   23.53%  5.88%

C?      5.88%   0.00%   23.53%

Note: class? = Predicted, class? = Actual
===================================

Naming convention - underscore in C++ and C# variables

It's simply means that it's a member field in the class.

Oracle TNS names not showing when adding new connection to SQL Developer

In Sql Developer, navidate to Tools->preferences->Datababae->advanced->Set Tnsname directory to the directory containing tnsnames.ora

Enable/Disable a dropdownbox in jquery

$("#chkdwn2").change(function() { 
    if (this.checked) $("#dropdown").prop("disabled",'disabled');
}) 

Maximum concurrent connections to MySQL

You might have 10,000 users total, but that's not the same as concurrent users. In this context, concurrent scripts being run.

For example, if your visitor visits index.php, and it makes a database query to get some user details, that request might live for 250ms. You can limit how long those MySQL connections live even further by opening and closing them only when you are querying, instead of leaving it open for the duration of the script.

While it is hard to make any type of formula to predict how many connections would be open at a time, I'd venture the following:

You probably won't have more than 500 active users at any given time with a user base of 10,000 users. Of those 500 concurrent users, there will probably at most be 10-20 concurrent requests being made at a time.

That means, you are really only establishing about 10-20 concurrent requests.

As others mentioned, you have nothing to worry about in that department.

How to get commit history for just one branch?

I think an option for your purposes is git log --online --decorate. This lets you know the checked commit, and the top commits for each branch that you have in your story line. By doing this, you have a nice view on the structure of your repo and the commits associated to a specific branch. I think reading this might help.

No resource found - Theme.AppCompat.Light.DarkActionBar

A simple solution - replace contents this file (/res/values/styles.xml) to this is text:

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

What's the "average" requests per second for a production web application?

You can search "slashdot effect analysis" for graphs of what you would see if some aspect of the site suddenly became popular in the news, e.g. this graph on wiki.

Web-applications that survive tend to be the ones which can generate static pages instead of putting every request through a processing language.

There was an excellent video (I think it might have been on ted.com? I think it might have been by flickr web team? Does someone know the link?) with ideas on how to scale websites beyond the single server, e.g. how to allocate connections amongst the mix of read-only and read-write servers to get best effect for various types of users.

How to get file name from file path in android

The easiest solution is to use Uri.getLastPathSegment():

String filename = uri.getLastPathSegment();

Split string with multiple delimiters in Python

Do a str.replace('; ', ', ') and then a str.split(', ')

How to convert String to Date value in SAS?

This code helps:

data final; set final;

first_date = INPUT(compress(char_date),date9.); format first_date date9.;

run;

I personally have tried it on SAS

Ruby send JSON request

data = {a: {b: [1, 2]}}.to_json
uri = URI 'https://myapp.com/api/v1/resource'
https = Net::HTTP.new uri.host, uri.port
https.use_ssl = true
https.post2 uri.path, data, 'Content-Type' => 'application/json'

What is the difference between private and protected members of C++ classes?

Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.

Missing artifact com.oracle:ojdbc6:jar:11.2.0 in pom.xml

This is the quickest way to solve the problem but it's not recommended because its applicable only for your local system.

Download the jar, comment your previous entry for ojdbc6, and give a new local entry like so:

Previous Entry:

<!-- OJDBC6 Dependency -->
        <!-- <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>1.0</version>
            <scope>runtime</scope>
        </dependency> -->

New Entry:

<dependency>
        <groupId>com.oracle</groupId>
        <artifactId>ojdbc6</artifactId>
        <version>1.0</version>
        <scope>system</scope>
        <systemPath>${project.basedir}/lib/ojdbc6/ojdbc6.jar</systemPath>
        </dependency> 

What is the proper way to display the full InnerException?

To pretty print just the Messages part of deep exceptions, you could do something like this:

public static string ToFormattedString(this Exception exception)
{
    IEnumerable<string> messages = exception
        .GetAllExceptions()
        .Where(e => !String.IsNullOrWhiteSpace(e.Message))
        .Select(e => e.Message.Trim());
    string flattened = String.Join(Environment.NewLine, messages); // <-- the separator here
    return flattened;
}

public static IEnumerable<Exception> GetAllExceptions(this Exception exception)
{
    yield return exception;

    if (exception is AggregateException aggrEx)
    {
        foreach (Exception innerEx in aggrEx.InnerExceptions.SelectMany(e => e.GetAllExceptions()))
        {
            yield return innerEx;
        }
    }
    else if (exception.InnerException != null)
    {
        foreach (Exception innerEx in exception.InnerException.GetAllExceptions())
        {
            yield return innerEx;
        }
    }
}

This recursively goes through all inner exceptions (including the case of AggregateExceptions) to print all Message property contained in them, delimited by line break.

E.g.

var outerAggrEx = new AggregateException(
    "Outer aggr ex occurred.",
    new AggregateException("Inner aggr ex.", new FormatException("Number isn't in correct format.")),
    new IOException("Unauthorized file access.", new SecurityException("Not administrator.")));
Console.WriteLine(outerAggrEx.ToFormattedString());

Outer aggr ex occurred.
Inner aggr ex.
Number isn't in correct format.
Unauthorized file access.
Not administrator.


You will need to listen to other Exception properties for more details. For e.g. Data will have some information. You could do:

foreach (DictionaryEntry kvp in exception.Data)

To get all derived properties (not on base Exception class), you could do:

exception
    .GetType()
    .GetProperties()
    .Where(p => p.CanRead)
    .Where(p => p.GetMethod.GetBaseDefinition().DeclaringType != typeof(Exception));

Detect touch press vs long press vs movement?

This code can distinguish between click and movement (drag, scroll). In onTouchEvent set a flag isOnClick, and initial X, Y coordinates on ACTION_DOWN. Clear the flag on ACTION_MOVE (minding that unintentional movement is often detected which can be solved with a THRESHOLD const).

private float mDownX;
private float mDownY;
private final float SCROLL_THRESHOLD = 10;
private boolean isOnClick;

@Override
public boolean onTouchEvent(MotionEvent ev) {
    switch (ev.getAction() & MotionEvent.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN:
            mDownX = ev.getX();
            mDownY = ev.getY();
            isOnClick = true;
            break;
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            if (isOnClick) {
                Log.i(LOG_TAG, "onClick ");
                //TODO onClick code
            }
            break;
        case MotionEvent.ACTION_MOVE:
            if (isOnClick && (Math.abs(mDownX - ev.getX()) > SCROLL_THRESHOLD || Math.abs(mDownY - ev.getY()) > SCROLL_THRESHOLD)) {
                Log.i(LOG_TAG, "movement detected");
                isOnClick = false;
            }
            break;
        default:
            break;
    }
    return true;
}

For LongPress as suggested above, GestureDetector is the way to go. Check this Q&A:

Detecting a long press with Android

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

Some convenience functions:

public static void silentCloseResultSets(Statement st) {
    try {
        while (!(!st.getMoreResults() && (st.getUpdateCount() == -1))) {}
    } catch (SQLException ignore) {}
}
public static void silentCloseResultSets(Statement ...statements) {
    for (Statement st: statements) silentCloseResultSets(st);
}

Excel formula to reference 'CELL TO THE LEFT'

Instead of writing the very long:

=OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0,-1)

You can simply write:

=OFFSET(*Name of your Cell*,0,-1)

Thus for example you can write into Cell B2:

=OFFSET(B2,0,-1)

to reference to cell B1

Still thanks Jason Young!! I would have never come up with this solution without your answer!

Get div to take up 100% body height, minus fixed-height header and footer

Here's a solution that doesn't use negative margins or calc. Run the snippet below to see the final result.

Explanation

We give the header and the footer a fixed height of 30px and position them absolutely at the top and bottom, respectively. To prevent the content from falling underneath, we use two classes: below-header and above-footer to pad the div above and below with 30px.

All of the content is wrapped in a position: relative div so that the header and footer are at the top/bottom of the content and not the window.

We use the classes fit-to-parent and min-fit-to-parent to make the content fill out the page. This gives us a sticky footer which is at least as low as the window, but hidden if the content is longer than the window.

Inside the header and footer, we use the display: table and display: table-cell styles to give the header and footer some vertical padding without disrupting the shrink-wrap quality of the page. (Giving them real padding can cause the total height of the page to be more than 100%, which causes a scroll bar to appear when it isn't really needed.)

_x000D_
_x000D_
.fit-parent {_x000D_
    height: 100%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.min-fit-parent {_x000D_
    min-height: 100%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.below-header {_x000D_
    padding-top: 30px;_x000D_
}_x000D_
.above-footer {_x000D_
    padding-bottom: 30px;_x000D_
}_x000D_
.header {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    height: 30px;_x000D_
    width: 100%;_x000D_
}_x000D_
.footer {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    height: 30px;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
/* helper classes */_x000D_
_x000D_
.padding-lr-small {_x000D_
    padding: 0 5px;_x000D_
}_x000D_
.relative {_x000D_
    position: relative;_x000D_
}_x000D_
.auto-scroll {_x000D_
  overflow: auto;_x000D_
}_x000D_
/* these two classes work together to create vertical centering */_x000D_
.valign-outer {_x000D_
    display: table;_x000D_
}_x000D_
.valign-inner {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<html class='fit-parent'>_x000D_
  <body class='fit-parent'>_x000D_
<div class='min-fit-parent auto-scroll relative' style='background-color: lightblue'>_x000D_
<div class='header valign-outer' style='background-color: black; color: white;'>_x000D_
        <div class='valign-inner padding-lr-small'>_x000D_
            My webpage_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class='fit-parent above-footer below-header'>_x000D_
        <div class='fit-parent' id='main-inner'>_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class='footer valign-outer' style='background-color: white'>_x000D_
        <div class='valign-inner padding-lr-small'>_x000D_
            &copy; 2005 Old Web Design_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

Did you mean this?

$('#i_file').change( function(event) {
var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',tmppath);       
});

What's the idiomatic syntax for prepending to a short python list?

Lets go over 4 methods

  1. Using insert()
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l.insert(0, 5)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using [] and +
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = [5] + l
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using Slicing
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l[:0] = [5]
>>> l
[5, 0, 1, 2, 3, 4]
>>> 
  1. Using collections.deque.appendleft()
>>> 
>>> from collections import deque
>>> 
>>> l = list(range(5))
>>> l
[0, 1, 2, 3, 4]
>>> l = deque(l)
>>> l.appendleft(5)
>>> l = list(l)
>>> l
[5, 0, 1, 2, 3, 4]
>>> 

START_STICKY and START_NOT_STICKY

The documentation for START_STICKY and START_NOT_STICKY is quite straightforward.

START_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be delivered to the service, it will be called with a null intent object, so you must take care to check for this.

This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a service performing background music playback.

Example: Local Service Sample

START_NOT_STICKY:

If this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), and there are no new start intents to deliver to it, then take the service out of the started state and don't recreate until a future explicit call to Context.startService(Intent). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will not be re-started if there are no pending Intents to deliver.

This mode makes sense for things that want to do some work as a result of being started, but can be stopped when under memory pressure and will explicit start themselves again later to do more work. An example of such a service would be one that polls for data from a server: it could schedule an alarm to poll every N minutes by having the alarm start its service. When its onStartCommand(Intent, int, int) is called from the alarm, it schedules a new alarm for N minutes later, and spawns a thread to do its networking. If its process is killed while doing that check, the service will not be restarted until the alarm goes off.

Example: ServiceStartArguments.java

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

The problem in my case was that the database name was incorrect.
I solved the problem by referring the correct database name in the field as below

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myDatabase</property>

ProgressDialog spinning circle

I was using View.INVISIBLE and View.VISIBLE and the ProgressBar would slowly flash instead of constantly being visible, switched to View.GONE and View.VISIBLE and it works perfectly

How to debug SSL handshake using cURL?

curl probably does have some options for showing more information but for things like this I always use openssl s_client

With the -debug option this gives lots of useful information

Maybe I should add that this also works with non HTTP connections. So if you are doing "https", try the curl commands suggested below. If you aren't or want a second option openssl s_client might be good

Firebase onMessageReceived not called when app in background

When message is received and your app is in background the notification is sent to the extras intent of the main activity.

You can check the extra value in the oncreate() or onresume() function of the main activity.

You can check for the fields like data, table etc ( the one specified in the notification)

for example I sent using data as the key

public void onResume(){
    super.onResume();
    if (getIntent().getStringExtra("data")!=null){
            fromnotification=true;
            Intent i = new Intent(MainActivity.this, Activity2.class);
            i.putExtra("notification","notification");
            startActivity(i);
        }

}

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

Short answer:

There is no difference in semantic.

Specifically, @GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

Further reading:

RequestMapping can be used at class level:

This annotation can be used both at the class and at the method level. In most cases, at the method level applications will prefer to use one of the HTTP method specific variants @GetMapping, @PostMapping, @PutMapping, @DeleteMapping, or @PatchMapping.

while GetMapping only applies to method:

Annotation for mapping HTTP GET requests onto specific handler methods.


https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/GetMapping.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

cannot make a static reference to the non-static field

You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.

How do I check if there are duplicates in a flat list?

I recently answered a related question to establish all the duplicates in a list, using a generator. It has the advantage that if used just to establish 'if there is a duplicate' then you just need to get the first item and the rest can be ignored, which is the ultimate shortcut.

This is an interesting set based approach I adapted straight from moooeeeep:

def getDupes(l):
    seen = set()
    seen_add = seen.add
    for x in l:
        if x in seen or seen_add(x):
            yield x

Accordingly, a full list of dupes would be list(getDupes(etc)). To simply test "if" there is a dupe, it should be wrapped as follows:

def hasDupes(l):
    try:
        if getDupes(l).next(): return True    # Found a dupe
    except StopIteration:
        pass
    return False

This scales well and provides consistent operating times wherever the dupe is in the list -- I tested with lists of up to 1m entries. If you know something about the data, specifically, that dupes are likely to show up in the first half, or other things that let you skew your requirements, like needing to get the actual dupes, then there are a couple of really alternative dupe locators that might outperform. The two I recommend are...

Simple dict based approach, very readable:

def getDupes(c):
    d = {}
    for i in c:
        if i in d:
            if d[i]:
                yield i
                d[i] = False
        else:
            d[i] = True

Leverage itertools (essentially an ifilter/izip/tee) on the sorted list, very efficient if you are getting all the dupes though not as quick to get just the first:

def getDupes(c):
    a, b = itertools.tee(sorted(c))
    next(b, None)
    r = None
    for k, g in itertools.ifilter(lambda x: x[0]==x[1], itertools.izip(a, b)):
        if k != r:
            yield k
            r = k

These were the top performers from the approaches I tried for the full dupe list, with the first dupe occurring anywhere in a 1m element list from the start to the middle. It was surprising how little overhead the sort step added. Your mileage may vary, but here are my specific timed results:

Finding FIRST duplicate, single dupe places "n" elements in to 1m element array

Test set len change :        50 -  . . . . .  -- 0.002
Test in dict        :        50 -  . . . . .  -- 0.002
Test in set         :        50 -  . . . . .  -- 0.002
Test sort/adjacent  :        50 -  . . . . .  -- 0.023
Test sort/groupby   :        50 -  . . . . .  -- 0.026
Test sort/zip       :        50 -  . . . . .  -- 1.102
Test sort/izip      :        50 -  . . . . .  -- 0.035
Test sort/tee/izip  :        50 -  . . . . .  -- 0.024
Test moooeeeep      :        50 -  . . . . .  -- 0.001 *
Test iter*/sorted   :        50 -  . . . . .  -- 0.027

Test set len change :      5000 -  . . . . .  -- 0.017
Test in dict        :      5000 -  . . . . .  -- 0.003 *
Test in set         :      5000 -  . . . . .  -- 0.004
Test sort/adjacent  :      5000 -  . . . . .  -- 0.031
Test sort/groupby   :      5000 -  . . . . .  -- 0.035
Test sort/zip       :      5000 -  . . . . .  -- 1.080
Test sort/izip      :      5000 -  . . . . .  -- 0.043
Test sort/tee/izip  :      5000 -  . . . . .  -- 0.031
Test moooeeeep      :      5000 -  . . . . .  -- 0.003 *
Test iter*/sorted   :      5000 -  . . . . .  -- 0.031

Test set len change :     50000 -  . . . . .  -- 0.035
Test in dict        :     50000 -  . . . . .  -- 0.023
Test in set         :     50000 -  . . . . .  -- 0.023
Test sort/adjacent  :     50000 -  . . . . .  -- 0.036
Test sort/groupby   :     50000 -  . . . . .  -- 0.134
Test sort/zip       :     50000 -  . . . . .  -- 1.121
Test sort/izip      :     50000 -  . . . . .  -- 0.054
Test sort/tee/izip  :     50000 -  . . . . .  -- 0.045
Test moooeeeep      :     50000 -  . . . . .  -- 0.019 *
Test iter*/sorted   :     50000 -  . . . . .  -- 0.055

Test set len change :    500000 -  . . . . .  -- 0.249
Test in dict        :    500000 -  . . . . .  -- 0.145
Test in set         :    500000 -  . . . . .  -- 0.165
Test sort/adjacent  :    500000 -  . . . . .  -- 0.139
Test sort/groupby   :    500000 -  . . . . .  -- 1.138
Test sort/zip       :    500000 -  . . . . .  -- 1.159
Test sort/izip      :    500000 -  . . . . .  -- 0.126
Test sort/tee/izip  :    500000 -  . . . . .  -- 0.120 *
Test moooeeeep      :    500000 -  . . . . .  -- 0.131
Test iter*/sorted   :    500000 -  . . . . .  -- 0.157

Using OR operator in a jquery if statement

The code you wrote will always return true because state cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15).... AND is what you need not OR.

Use $.inArray instead. This returns the index of the element in the array.

JSFIDDLE DEMO

var statesArray = [10, 15, 19]; // list out all

var index = $.inArray(state, statesArray);

if(index == -1) {
    console.log("Not there in array");
    return true;

} else {
    console.log("Found it");
    return false;
}

Assembly Language - How to do Modulo?

If you compute modulo a power of two, using bitwise AND is simpler and generally faster than performing division. If b is a power of two, a % b == a & (b - 1).

For example, let's take a value in register EAX, modulo 64.
The simplest way would be AND EAX, 63, because 63 is 111111 in binary.

The masked, higher digits are not of interest to us. Try it out!

Analogically, instead of using MUL or DIV with powers of two, bit-shifting is the way to go. Beware signed integers, though!

How to find top three highest salary in emp table in oracle?

SELECT * FROM
     (
      SELECT  ename, sal,
      DENSE_RANK() OVER (ORDER BY SAL DESC) EMPRANK
      FROM emp 
     )
    emp1 WHERE emprank <=5

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

For Centos I was missing php-mysql library:

yum install php-mysql

service httpd restart

There is no need to enable any extension in php.ini, it is loaded by default.

Deadly CORS when http://localhost is the origin

Chrome will make requests with CORS from a localhost origin just fine. This isn't a problem with Chrome.

The reason you can't load http://stackoverflow.com is that the Access-Control-Allow-Origin headers weren't allowing your localhost origin.

How do I get the Date & Time (VBS)

There are also separate Time() and Date() functions.

SQLAlchemy: how to filter date field?

from app import SQLAlchemyDB as db

Chance.query.filter(Chance.repo_id==repo_id, 
                    Chance.status=="1", 
                    db.func.date(Chance.apply_time)<=end, 
                    db.func.date(Chance.apply_time)>=start).count()

it is equal to:

select
   count(id)
from
   Chance
where
   repo_id=:repo_id 
   and status='1'
   and date(apple_time) <= end
   and date(apple_time) >= start

wish can help you.

Batch Extract path and filename from a variable

@ECHO OFF
SETLOCAL
set file=C:\Users\l72rugschiri\Desktop\fs.cfg
FOR %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Not really sure what you mean by no "function"

Obviously, change ECHO to SET to set the variables rather thon ECHOing them...

See for documentation for a full list.


ceztko's test case (for reference)

@ECHO OFF
SETLOCAL
set file="C:\Users\ l72rugschiri\Desktop\fs.cfg"
FOR /F "delims=" %%i IN ("%file%") DO (
ECHO filedrive=%%~di
ECHO filepath=%%~pi
ECHO filename=%%~ni
ECHO fileextension=%%~xi
)

Comment : please see comments.

Removing all unused references from a project in Visual Studio projects

You can use Reference Assistant extension from the Visual Studio extension gallery.

Used and works for Visual Studio 2010.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

This problem occurs if there are different jar versions. Especially versions of httpcore and httpclient. Use same versions of httpcore and httpclient.

How to use a keypress event in AngularJS?

I'm a bit late .. but i found a simpler solution using auto-focus .. This could be useful for buttons or other when popping a dialog :

<button auto-focus ng-click="func()">ok</button>

That should be fine if you want to press the button onSpace or Enter clicks .

How to prevent custom views from losing state across screen orientation changes

Easy with kotlin

@Parcelize
class MyState(val superSavedState: Parcelable?, val loading: Boolean) : View.BaseSavedState(superSavedState), Parcelable


class MyView : View {

    var loading: Boolean = false

    override fun onSaveInstanceState(): Parcelable? {
        val superState = super.onSaveInstanceState()
        return MyState(superState, loading)
    }

    override fun onRestoreInstanceState(state: Parcelable?) {
        val myState = state as? MyState
        super.onRestoreInstanceState(myState?.superSaveState ?: state)

        loading = myState?.loading ?: false
        //redraw
    }
}

How can I print the contents of an array horizontally?

The below solution is the simplest one:

Console.WriteLine("[{0}]", string.Join(", ", array));

Output: [1, 2, 3, 4, 5]

Another short solution:

Array.ForEach(array,  val => Console.Write("{0} ", val));

Output: 1 2 3 4 5. Or if you need to add add ,, use the below:

int i = 0;
Array.ForEach(array,  val => Console.Write(i == array.Length -1) ? "{0}" : "{0}, ", val));

Output: 1, 2, 3, 4, 5

HTML Upload MAX_FILE_SIZE does not appear to work

To anyone who had been wonderstruck about some files being easily uploaded and some not, it could be a size issue. I'm sharing this as I was stuck with my PHP code not uploading large files and I kept assuming it wasn't uploading any Excel files. So, if you are using PHP and you want to increase the file upload limit, go to the php.ini file and make the following modifications:

  • upload_max_filesize = 2M

to be changed to

  • upload_max_filesize = 10M

  • post_max_size = 10M

or the size required. Then restart the Apache server and the upload will start magically working. Hope this will be of help to someone.

"Eliminate render-blocking CSS in above-the-fold content"

Please have a look on the following page https://varvy.com/pagespeed/render-blocking-css.html . This helped me to get rid of "Render Blocking CSS". I used the following code in order to remove "Render Blocking CSS". Now in google page speed insight I am not getting issue related with render blocking css.

<!-- loadCSS -->
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/cssrelpreload.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/loadCSS.js"></script>
<script src="https://cdn.rawgit.com/filamentgroup/loadCSS/6b637fe0/src/onloadCSS.js"></script>
<script>
      /*!
      loadCSS: load a CSS file asynchronously.
      */
      function loadCSS(href){
        var ss = window.document.createElement('link'),
            ref = window.document.getElementsByTagName('head')[0];

        ss.rel = 'stylesheet';
        ss.href = href;

        // temporarily, set media to something non-matching to ensure it'll
        // fetch without blocking render
        ss.media = 'only x';

        ref.parentNode.insertBefore(ss, ref);

        setTimeout( function(){
          // set media back to `all` so that the stylesheet applies once it loads
          ss.media = 'all';
        },0);
      }
      loadCSS('styles.css');
    </script>
    <noscript>
      <!-- Let's not assume anything -->
      <link rel="stylesheet" href="styles.css">
    </noscript>

Create own colormap using matplotlib and plot color scale

If you want to automate the creating of a custom divergent colormap commonly used for surface plots, this module combined with @unutbu method worked well for me.

def diverge_map(high=(0.565, 0.392, 0.173), low=(0.094, 0.310, 0.635)):
    '''
    low and high are colors that will be used for the two
    ends of the spectrum. they can be either color strings
    or rgb color tuples
    '''
    c = mcolors.ColorConverter().to_rgb
    if isinstance(low, basestring): low = c(low)
    if isinstance(high, basestring): high = c(high)
    return make_colormap([low, c('white'), 0.5, c('white'), high])

The high and low values can be either string color names or rgb tuples. This is the result using the surface plot demo: enter image description here

What does .pack() do?

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

From Java tutorial

You should also refer to Javadocs any time you need additional information on any Java API

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.

Reference: https://github.com/smebberson/docker-alpine/issues/43

Rails :include vs. :joins

.joins will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again

:includes will eager load the included associations and add them in memory. :includes loads all the included tables attributes. If you call associations on include query result, it will not fire any queries

java.net.URLEncoder.encode(String) is deprecated, what should I use instead?

As an additional reference for the other responses, instead of using "UTF-8" you can use:

HTTP.UTF_8

which is included since Java 4 as part of the org.apache.http.protocol library, which is included also since Android API 1.

Git Push error: refusing to update checked out branch

It's works for me

  1. git config --global receive.denyCurrentBranch updateInstead

  2. git push origin master

Received fatal alert: handshake_failure through SSLHandshakeException

Mine was a TLS version incompatible error.

Previously it was TLSv1 I changed it TLSV1.2 this solved my problem.

Iterate through <select> options

can also Use parameterized each with index and the element.

$('#selectIntegrationConf').find('option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

// this will also work

$('#selectIntegrationConf option').each(function(index,element){
 console.log(index);
 console.log(element.value);
 console.log(element.text);
 });

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

I found this thread while trying to carry out a similar task. In the end, I used

Range("F:F").SpecialCells(xlBlanks).Areas(1)(1).Select

Which works fine as long as there is a blank cell in the intersection of the specified range and the used range of the worksheet.

The areas property is not needed to find the absolute first blank in the range, but is useful for finding subsequent non consecutive blanks.

Include files from parent or other directory

You may interest in using php's inbuilt function realpath(). and passing a constant DIR

for example: $TargetDirectory = realpath(__DIR__."/../.."); //Will take you 2 folder's back

String realpath() :: Returns canonicalized absolute pathname ..

input type="submit" Vs button tag are they interchangeable?

If you are talking about <input type=button>, it won't automatically submit the form

if you are talking about the <button> tag, that's newer and doesn't automatically submit in all browsers.

Bottom line, if you want the form to submit on click in all browsers, use <input type="submit">

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

If you want to modify your List during traversal, then you need to use the Iterator. And then you can use iterator.remove() to remove the elements during traversal.

What is an alternative to execfile in Python 3?

According to the documentation, instead of

execfile("./filename") 

Use

exec(open("./filename").read())

See:

Show animated GIF

Using swing you could simply use a JLabel

 public static void main(String[] args) throws MalformedURLException {

        URL url = new URL("<URL to your Animated GIF>");
        Icon icon = new ImageIcon(url);
        JLabel label = new JLabel(icon);

        JFrame f = new JFrame("Animation");
        f.getContentPane().add(label);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

CSS/HTML: Create a glowing border around an Input Field

SLaks hit the nail on the head but you might want to look over the changes for inputs in CSS3 in general. Rounded corners and box-shadow are both new features in CSS3 and will let you do exactly what you're looking for. One of my personal favorite links for CSS3/HTML5 is http://diveintohtml5.ep.io/ .

CSS Inset Borders

You can do this:

.thing {
  border: 2px solid transparent;
}
.thing:hover {
  border: 2px solid green;
}

React-Native: Application has not been registered error

The issue will also appear when, in index.js, you have named the app differently from the name you gave it for the android/ios package; probably this happened when you've ejected the app. So be sure that when calling AppRegistry.registerComponent('someappname', () => App), someappname is also used for the native packages or viceversa.

Javascript - Append HTML to container element without innerHTML

<div id="Result">
</div>

<script>
for(var i=0; i<=10; i++){
var data = "<b>vijay</b>";
 document.getElementById('Result').innerHTML += data;
}
</script>

assign the data for div with "+=" symbol you can append data including previous html data

Format date and time in a Windows batch script

If you don't exactly need this format:

2009_07_28__08_36_01

Then you could use the following 3 lines of code which uses %date% and %time%:

set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%

Note: The characters / and : are removed and the character . and space is replaced with an underscore.

Example output (taken Wednesday 8/5/15 at 12:49 PM with 50 seconds and 93 milliseconds):

echo %mytimestamp%
Wed_08052015_124950_93

How can I refresh c# dataGridView after update ?

You can use the DataGridView refresh method. But... in a lot of cases you have to refresh the DataGridView from methods running on a different thread than the one where the DataGridView is running. In order to do that you should implement the following method and call it rather than directly typing DataGridView.Refresh():

    private void RefreshGridView()
    {
        if (dataGridView1.InvokeRequired)
        {
            dataGridView1.Invoke((MethodInvoker)delegate ()
            {
                RefreshGridView();
            });
        }
        else
            dataGridView1.Refresh();
    }