Programs & Examples On #Bcrypt

BCrypt is an implementation of the Blowfish cipher and a computationally-expensive hash function mostly used for password hashing.

How do you use bcrypt for hashing passwords in PHP?

Here's an updated answer to this old question!

The right way to hash passwords in PHP since 5.5 is with password_hash(), and the right way to verify them is with password_verify(), and this is still true in PHP 8.0. These functions use bcrypt hashes by default, but other stronger algorithms have been added. You can alter the work factor (effectively how "strong" the encryption is) via the password_hash parameters.

However, while it's still plenty strong enough, bcrypt is no longer considered state-of-the-art; a better set of password hash algorithms has arrived called Argon2, with Argon2i, Argon2d, and Argon2id variants. The difference between them (as described here):

Argon2 has one primary variant: Argon2id, and two supplementary variants: Argon2d and Argon2i. Argon2d uses data-depending memory access, which makes it suitable for cryptocurrencies and proof-of-work applications with no threats from side-channel timing attacks. Argon2i uses data-independent memory access, which is preferred for password hashing and password-based key derivation. Argon2id works as Argon2i for the first half of the first iteration over the memory, and as Argon2d for the rest, thus providing both side-channel attack protection and brute-force cost savings due to time-memory tradeoffs.

Argon2i support was added in PHP 7.2, and you request it like this:

$hash = password_hash('mypassword', PASSWORD_ARGON2I);

and Argon2id support was added in PHP 7.3:

$hash = password_hash('mypassword', PASSWORD_ARGON2ID);

No changes are required for verifying passwords since the resulting hash string contains information about what algorithm, salt, and work factors were used when it was created.

Quite separately (and somewhat redundantly), libsodium (added in PHP 7.2) also provides Argon2 hashing via the sodium_crypto_pwhash_str () and sodium_crypto_pwhash_str_verify() functions, which work much the same way as the PHP built-ins. One possible reason for using these is that PHP may sometimes be compiled without libargon2, which makes the Argon2 algorithms unavailable to the password_hash function; PHP 7.2 and higher should always have libsodium enabled, but it may not - but at least there are two ways you can get at that algorithm. Here's how you can create an Argon2id hash with libsodium (even in PHP 7.2, which otherwise lacks Argon2id support)):

$hash = sodium_crypto_pwhash_str(
    'mypassword',
    SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
    SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);

Note that it doesn't allow you to specify a salt manually; this is part of libsodium's ethos – don't allow users to set params to values that might compromise security – for example there is nothing preventing you from passing an empty salt string to PHP's password_hash function; libsodium doesn't let you do anything so silly!

How can bcrypt have built-in salts?

To make things even more clearer,

Registeration/Login direction ->

The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt:

$2a$COST$BASE64

This value is stored eventually.

What the attacker would need to do in order to find the password ? (other direction <- )

In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random. Then he will need to decrypt the cipher text.

What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

The modular crypt format for bcrypt consists of

  • $2$, $2a$ or $2y$ identifying the hashing algorithm and format
  • a two digit value denoting the cost parameter, followed by $
  • a 53 characters long base-64-encoded value (they use the alphabet ., /, 09, AZ, az that is different to the standard Base 64 Encoding alphabet) consisting of:
    • 22 characters of salt (effectively only 128 bits of the 132 decoded bits)
    • 31 characters of encrypted output (effectively only 184 bits of the 186 decoded bits)

Thus the total length is 59 or 60 bytes respectively.

As you use the 2a format, you’ll need 60 bytes. And thus for MySQL I’ll recommend to use the CHAR(60) BINARYor BINARY(60) (see The _bin and binary Collations for information about the difference).

CHAR is not binary safe and equality does not depend solely on the byte value but on the actual collation; in the worst case A is treated as equal to a. See The _bin and binary Collations for more information.

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

I found that I needed to install another version of ruby. So running the command

$ sudo apt-get install ruby1.9.1-dev

and then attempt to install the extension

If you run into issues where it is telling you that you don't have g++ you can run the following command to install it

$ sudo apt-get install g++

How to decrypt hash stored by bcrypt

You simply can't.

bcrypt uses salting, of different rounds, I use 10 usually.

bcrypt.hash(req.body.password,10,function(error,response){ }

This 10 is salting random string into your password.

(413) Request Entity Too Large | uploadReadAheadSize

If you're running into this issue despite trying all of the solutions in this thread, and you're connecting to the service via SSL (e.g. https), this might help:

http://forums.newatlanta.com/messages.cfm?threadid=554611A2-E03F-43DB-92F996F4B6222BC0&#top

To summarize (in case the link dies in the future), if your requests are large enough the certificate negotiation between the client and the service will fail randomly. To keep this from happening, you'll need to enable a certain setting on your SSL bindings. From your IIS server, here are the steps you'll need to take:

  1. Via cmd or powershell, run netsh http show sslcert. This will give you your current configuration. You'll want to save this somehow so you can reference it again later.
  2. You should notice that "Negotiate Client Certificate" is disabled. This is the problem setting; the following steps will demonstrate how to enable it.
  3. Unfortunately there is no way to change existing bindings; you'll have to delete it and re-add it. Run netsh http delete sslcert <ipaddress>:<port> where <ipaddress>:<port> is the IP:port shown in the configuration you saved earlier.
  4. Now you can re-add the binding. You can view the valid parameters for netsh http add sslcert here (MSDN) but in most cases your command will look like this:

netsh http add sslcert ipport=<ipaddress>:<port> appid=<application ID from saved config including the {}> certhash=<certificate hash from saved config> certstorename=<certificate store name from saved config> clientcertnegotiation=enable

If you have multiple SSL bindings, you'll repeat the process for each of them. Hopefully this helps save someone else the hours and hours of headache this issue caused me.

EDIT: In my experience, you can't actually run the netsh http add sslcert command from the command line directly. You'll need to enter the netsh prompt first by typing netsh and then issue your command like http add sslcert ipport=... in order for it to work.

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

Simple PHP solution to this:

if (isset($_POST['aaa'])){
echo '
<script type="text/javascript">
location.reload();
</script>';
}

As the page is reloaded it will update on screen the new data and clear the $_POST ;)

Reading int values from SqlDataReader

Use the GetInt method.

reader.GetInt32(3);

Add alternating row color to SQL Server Reporting services report

My problem was that I wanted all the columns in a row to have the same background. I grouped both by row and by column, and with the top two solutions here I got all the rows in column 1 with a colored background, all the rows in column 2 with a white background, all the rows in column 3 with a colored background, and so on. It's as if RowNumber and bOddRow (of Catch22's solution) pay attention to my column group instead of ignoring that and only alternating with a new row.

What I wanted is for all the columns in row 1 to have a white background, then all the columns in row 2 to have a colored background, then all the columns in row 3 to have a white background, and so on. I got this effect by using the selected answer but instead of passing Nothing to RowNumber, I passed the name of my column group, e.g.

=IIf(RowNumber("MyColumnGroupName") Mod 2 = 0, "AliceBlue", "Transparent")

Thought this might be useful to someone else.

Getting the class name of an instance?

Apart from grabbing the special __name__ attribute, you might find yourself in need of the qualified name for a given class/function. This is done by grabbing the types __qualname__.

In most cases, these will be exactly the same, but, when dealing with nested classes/methods these differ in the output you get. For example:

class Spam:
    def meth(self):
        pass
    class Bar:
        pass

>>> s = Spam()
>>> type(s).__name__ 
'Spam'
>>> type(s).__qualname__
'Spam'
>>> type(s).Bar.__name__       # type not needed here
'Bar'
>>> type(s).Bar.__qualname__   # type not needed here 
'Spam.Bar'
>>> type(s).meth.__name__
'meth'
>>> type(s).meth.__qualname__
'Spam.meth'

Since introspection is what you're after, this is always you might want to consider.

Autocompletion in Vim

You can use a plugin like AutoComplPop to get automatic code completion as you type.

2015 Edit: I personally use YouCompleteMe now.

Copy Paste Values only( xlPasteValues )

Personally, I would shorten it a touch too if all you need is the columns:

For i = LBound(arr1) To UBound(arr1)
    Sheets("SheetA").Columns(arr1(i)).Copy
    Sheets("SheetB").Columns(arr2(i)).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
Next

as from this code snippet, there isnt much point in lastrow or firstrowDB

Can HTML be embedded inside PHP "if" statement?

<?php if($condition) : ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>

By request, here's elseif and else (which you can also find in the docs)

<?php if($condition) : ?>
    <a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
    more html
<?php else : ?>
    even more html
<?php endif; ?>

It's that simple.

The HTML will only be displayed if the condition is satisfied.

How to replace multiple patterns at once with sed?

This might work for you (GNU sed):

sed -r '1{x;s/^/:abbc:bcab/;x};G;s/^/\n/;:a;/\n\n/{P;d};s/\n(ab|bc)(.*\n.*:(\1)([^:]*))/\4\n\2/;ta;s/\n(.)/\1\n/;ta' file

This uses a lookup table which is prepared and held in the hold space (HS) and then appended to each line. An unique marker (in this case \n) is prepended to the start of the line and used as a method to bump-along the search throughout the length of the line. Once the marker reaches the end of the line the process is finished and is printed out the lookup table and markers being discarded.

N.B. The lookup table is prepped at the very start and a second unique marker (in this case :) chosen so as not to clash with the substitution strings.

With some comments:

sed -r '
  # initialize hold with :abbc:bcab
  1 {
    x
    s/^/:abbc:bcab/
    x
  }

  G        # append hold to patt (after a \n)

  s/^/\n/  # prepend a \n

  :a

  /\n\n/ {
    P      # print patt up to first \n
    d      # delete patt & start next cycle
  }

  s/\n(ab|bc)(.*\n.*:(\1)([^:]*))/\4\n\2/
  ta       # goto a if sub occurred

  s/\n(.)/\1\n/  # move one char past the first \n
  ta       # goto a if sub occurred
'

The table works like this:

   **   **   replacement
:abbc:bcab
 **   **     pattern

Int to Char in C#

Although not exactly answering the question as formulated, but if you need or can take the end result as string you can also use

string s = Char.ConvertFromUtf32(56);

which will give you surrogate UTF-16 pairs if needed, protecting you if you are out side of the BMP.

Python matplotlib multiple bars

The trouble with using dates as x-values, is that if you want a bar chart like in your second picture, they are going to be wrong. You should either use a stacked bar chart (colours on top of each other) or group by date (a "fake" date on the x-axis, basically just grouping the data points).

import numpy as np
import matplotlib.pyplot as plt

N = 3
ind = np.arange(N)  # the x locations for the groups
width = 0.27       # the width of the bars

fig = plt.figure()
ax = fig.add_subplot(111)

yvals = [4, 9, 2]
rects1 = ax.bar(ind, yvals, width, color='r')
zvals = [1,2,3]
rects2 = ax.bar(ind+width, zvals, width, color='g')
kvals = [11,12,13]
rects3 = ax.bar(ind+width*2, kvals, width, color='b')

ax.set_ylabel('Scores')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('2011-Jan-4', '2011-Jan-5', '2011-Jan-6') )
ax.legend( (rects1[0], rects2[0], rects3[0]), ('y', 'z', 'k') )

def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.05*h, '%d'%int(h),
                ha='center', va='bottom')

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)

plt.show()

enter image description here

OpenCV in Android Studio

Android Studio 3.4 + OpenCV 4.1

  1. Download the latest OpenCV zip file from here (current newest version is 4.1.0) and unzip it in your workspace or in another folder.

  2. Create new Android Studio project normally. Click File->New->Import Module, navigate to /path_to_unzipped_files/OpenCV-android-sdk/sdk/java, set Module name as opencv, click Next and uncheck all options in the screen.

  3. Enable Project file view mode (default mode is Android). In the opencv/build.gradle file change apply plugin: 'com.android.application' to apply plugin: 'com.android.library' and replace application ID "org.opencv" with

    minSdkVersion 21
    targetSdkVersion 28
    

    (according the values in app/build.gradle). Sync project with Gradle files.

  4. Add this string to the dependencies block in the app/build.gradle file

    dependencies {
        ...
        implementation project(path: ':opencv')
        ...
    }
    
  5. Select again Android file view mode. Right click on app module and goto New->Folder->JNI Folder. Select change folder location and set src/main/jniLibs/.

  6. Select again Project file view mode and copy all folders from /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/libs to app/src/main/jniLibs.

  7. Again in Android file view mode right click on app module and choose Link C++ Project with Gradle. Select Build System ndk-build and path to OpenCV.mk file /path_to_unzipped_files/OpenCV-android-sdk/sdk/native/jni/OpenCV.mk.

    path_to_unzipped_files must not contain any spaces, or you will get error!

To check OpenCV initialization add Toast message in MainActivity onCreate() method:

Toast.makeText(MainActivity.this, String.valueOf(OpenCVLoader.initDebug()), Toast.LENGTH_LONG).show();

If initialization is successful you will see true in Toast message else you will see false.

Why do I get a SyntaxError for a Unicode escape in my file path?

This usually happens in Python 3. One of the common reasons would be that while specifying your file path you need "\\" instead of "\". As in:

filePath = "C:\\User\\Desktop\\myFile"

For Python 2, just using "\" would work.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I had the same error when initializing Spring on startup, using some different library versions, but everything worked when I got my versions in this order in the classpath (the other libraries in the cp were not important):

  1. asm-3.1.jar
  2. cglib-nodep-2.1_3.jar
  3. asm-attrs-1.5.3.jar

How to delete a whole folder and content?

Safest code I know:

private boolean recursiveRemove(File file) {
    if(file == null  || !file.exists()) {
        return false;
    }

    if(file.isDirectory()) {
        File[] list = file.listFiles();

        if(list != null) {

            for(File item : list) {
                recursiveRemove(item);
            }

        }
    }

    if(file.exists()) {
        file.delete();
    }

    return !file.exists();
}

Checks the file exists, handles nulls, checks the directory was actually deleted

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

Every service that is bound in activity must be unbind on app close.

So try using

 onPause(){
   unbindService(YOUR_SERVICE);
   super.onPause();
 }

How to define a two-dimensional array?

Use:

import copy

def ndlist(*args, init=0):
    dp = init
    for x in reversed(args):
        dp = [copy.deepcopy(dp) for _ in range(x)]
    return dp

l = ndlist(1,2,3,4) # 4 dimensional list initialized with 0's
l[0][1][2][3] = 1

I do think NumPy is the way to go. The above is a generic one if you don't want to use NumPy.

How to force a web browser NOT to cache images

From my point of view, disable images caching is a bad idea. At all.

The root problem here is - how to force browser to update image, when it has been updated on a server side.

Again, from my personal point of view, the best solution is to disable direct access to images. Instead access images via server-side filter/servlet/other similar tools/services.

In my case it's a rest service, that returns image and attaches ETag in response. The service keeps hash of all files, if file is changed, hash is updated. It works perfectly in all modern browsers. Yes, it takes time to implement it, but it is worth it.

The only exception - are favicons. For some reasons, it does not work. I could not force browser to update its cache from server side. ETags, Cache Control, Expires, Pragma headers, nothing helped.

In this case, adding some random/version parameter into url, it seems, is the only solution.

Highlight the difference between two strings in PHP

Here is a short function you can use to diff two arrays. It implements the LCS algorithm:

function computeDiff($from, $to)
{
    $diffValues = array();
    $diffMask = array();

    $dm = array();
    $n1 = count($from);
    $n2 = count($to);

    for ($j = -1; $j < $n2; $j++) $dm[-1][$j] = 0;
    for ($i = -1; $i < $n1; $i++) $dm[$i][-1] = 0;
    for ($i = 0; $i < $n1; $i++)
    {
        for ($j = 0; $j < $n2; $j++)
        {
            if ($from[$i] == $to[$j])
            {
                $ad = $dm[$i - 1][$j - 1];
                $dm[$i][$j] = $ad + 1;
            }
            else
            {
                $a1 = $dm[$i - 1][$j];
                $a2 = $dm[$i][$j - 1];
                $dm[$i][$j] = max($a1, $a2);
            }
        }
    }

    $i = $n1 - 1;
    $j = $n2 - 1;
    while (($i > -1) || ($j > -1))
    {
        if ($j > -1)
        {
            if ($dm[$i][$j - 1] == $dm[$i][$j])
            {
                $diffValues[] = $to[$j];
                $diffMask[] = 1;
                $j--;  
                continue;              
            }
        }
        if ($i > -1)
        {
            if ($dm[$i - 1][$j] == $dm[$i][$j])
            {
                $diffValues[] = $from[$i];
                $diffMask[] = -1;
                $i--;
                continue;              
            }
        }
        {
            $diffValues[] = $from[$i];
            $diffMask[] = 0;
            $i--;
            $j--;
        }
    }    

    $diffValues = array_reverse($diffValues);
    $diffMask = array_reverse($diffMask);

    return array('values' => $diffValues, 'mask' => $diffMask);
}

It generates two arrays:

  • values array: a list of elements as they appear in the diff.
  • mask array: contains numbers. 0: unchanged, -1: removed, 1: added.

If you populate an array with characters, it can be used to compute inline difference. Now just a single step to highlight the differences:

function diffline($line1, $line2)
{
    $diff = computeDiff(str_split($line1), str_split($line2));
    $diffval = $diff['values'];
    $diffmask = $diff['mask'];

    $n = count($diffval);
    $pmc = 0;
    $result = '';
    for ($i = 0; $i < $n; $i++)
    {
        $mc = $diffmask[$i];
        if ($mc != $pmc)
        {
            switch ($pmc)
            {
                case -1: $result .= '</del>'; break;
                case 1: $result .= '</ins>'; break;
            }
            switch ($mc)
            {
                case -1: $result .= '<del>'; break;
                case 1: $result .= '<ins>'; break;
            }
        }
        $result .= $diffval[$i];

        $pmc = $mc;
    }
    switch ($pmc)
    {
        case -1: $result .= '</del>'; break;
        case 1: $result .= '</ins>'; break;
    }

    return $result;
}

Eg.:

echo diffline('StackOverflow', 'ServerFault')

Will output:

S<del>tackO</del><ins>er</ins>ver<del>f</del><ins>Fau</ins>l<del>ow</del><ins>t</ins> 

StackOerverfFaulowt

Additional notes:

  • The diff matrix requires (m+1)*(n+1) elements. So you can run into out of memory errors if you try to diff long sequences. In this case diff larger chunks (eg. lines) first, then diff their contents in a second pass.
  • The algorithm can be improved if you trim the matching elements from the beginning and the end, then run the algorithm on the differing middle only. A latter (more bloated) version contains these modifications too.

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

This is due to locking of Mongodb
sudo rm /var/lib/mongodb/mongod.lock
sudo service mongodb restart

SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

I prefer doing a "PAD" to the data. MySql calls it LPAD, but you can work your way around to doing the same thing in SQL Server.

ORDER BY  REPLACE(STR(ColName, 3), SPACE(1), '0') 

This formula will provide leading zeroes based on the Column's length of 3. This functionality is very useful in other situations outside of ORDER BY, so that is why I wanted to provide this option.

Results: 1 becomes 001, and 10 becomes 010, while 100 remains the same.

Check list of words in another string

If your list of words is of substantial length, and you need to do this test many times, it may be worth converting the list to a set and using set intersection to test (with the added benefit that you wil get the actual words that are in both lists):

>>> long_word_list = 'some one long two phrase three about above along after against'
>>> long_word_set = set(long_word_list.split())
>>> set('word along river'.split()) & long_word_set
set(['along'])

No grammar constraints (DTD or XML schema) detected for the document

This may be due to turning off validation in eclipse.

Generating sql insert into for Oracle

Use a SQL function (I'm the author):

Usage:

select fn_gen_inserts('select * from tablename', 'p_new_owner_name', 'p_new_table_name')
from dual;

where:

p_sql            – dynamic query which will be used to export metadata rows
p_new_owner_name – owner name which will be used for generated INSERT
p_new_table_name – table name which will be used for generated INSERT

p_sql in this sample is 'select * from tablename'

You can find original source code here:

Ashish Kumar's script generates individually usable insert statements instead of a SQL block, but supports fewer datatypes.

Why is synchronized block better than synchronized method?

In your case both are equivalent!

Synchronizing a static method is equivalent to a synchronized block on corresponding Class object.

In fact when you declare a synchronized static method lock is obtained on the monitor corresponding to the Class object.

public static synchronized int getCount() {
    // ...
}

is same as

public int getCount() {
    synchronized (ClassName.class) {
        // ...
    }
}

What is an example of the simplest possible Socket.io example?

Edit: I feel it's better for anyone to consult the excellent chat example on the Socket.IO getting started page. The API has been quite simplified since I provided this answer. That being said, here is the original answer updated small-small for the newer API.

Just because I feel nice today:

index.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

app.js

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

If element is not clickable and overlay issue is ocuring we use arguments[0].click().

WebElement ele = driver.findElement(By.xpath("//div[@class='input-group-btn']/input")); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", ele);

How do I programmatically determine operating system in Java?

A small example of what you're trying to achieve would probably be a class similar to what's underneath:

import java.util.Locale;

public class OperatingSystem
{
    private static String OS = System.getProperty("os.name", "unknown").toLowerCase(Locale.ROOT);

    public static boolean isWindows()
    {
        return OS.contains("win");
    }

    public static boolean isMac()
    {
        return OS.contains("mac");
    }

    public static boolean isUnix()
    {
        return OS.contains("nux");
    }
}

This particular implementation is quite reliable and should be universally applicable. Just copy and paste it into your class of choice.

Show an image preview before upload

For background images, make sure to use url()

node.backgroundImage = 'url(' + e.target.result + ')';

How can I ping a server port with PHP?

You don't need any exec or shell_exec hacks to do that, it is possible to do it in PHP. The book 'You want to do WHAT with PHP?' by Kevin Schroeder, show's how.

It uses sockets and the pack() function which lets you read and write binary protocols. What you need to do is to create an ICMP packet, which you can do by using the 'CCnnnA*' format to create your packet.

How to add a second css class with a conditional value in razor MVC 4

This:

    <div class="details @(Model.Details.Count > 0 ? "show" : "hide")">

will render this:

    <div class="details hide">

and is the mark-up I want.

CSS Image size, how to fill, but not stretch?

Building off of @Dominic Green's answer using jQuery, here is a solution that should work for images that are either wider than they are high or higher than they are wide.

http://jsfiddle.net/grZLR/4/

There is probably a more elegant way of doing the JavaScript, but this does work.

function myTest() {
  var imgH = $("#my-img").height();
  var imgW = $("#my-img").width();
  if(imgW > imgH) {
    $(".container img").css("height", "100%");
    var conWidth = $(".container").width();
    var imgWidth = $(".container img").width();
    var gap = (imgWidth - conWidth)/2;
    $(".container img").css("margin-left", -gap);
  } else {
    $(".container img").css("width", "100%");
    var conHeight = $(".container").height();
    var imgHeight = $(".container img").height();
    var gap = (imgHeight - conHeight)/2;
    $(".container img").css("margin-top", -gap);
  }
}
myTest();

Best practice when adding whitespace in JSX

You can use the css property white-space and set it to pre-wrap to the enclosing div element.

div {
     white-space: pre-wrap;
}

How to find the foreach index?

I normally do this when working with associative arrays:

foreach ($assoc_array as $key => $value) {
 //do something
}

This will work fine with non-associative arrays too. $key will be the index value. If you prefer, you can do this too:

foreach ($array as $indx => $value) {
  //do something
}

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

The YouTube URL in src must have and use the embed endpoint instead of watch, so for instance let’s say you want to embed this YouTube video: https://www.youtube.com/watch?v=P6N9782MzFQ (browser's URL).

You should use the embed endpoint, so the URL now should be something like https://www.youtube.com/embed/P6N9782MzFQ. Use this value as the URL in the src attribute inside the iframe tag in your HTML code, for example:

<iframe width="853" height="480" src="https://www.youtube.com/embed/P6N9782MzFQ" frameborder="0" allowfullscreen ng-show="showvideo"></iframe>

So just replace https://www.youtube.com/watch?v= with https://www.youtube.com/embed/ and of course check for your video's ID. In this sample, my video ID is P6N9782MzFQ.

Rails: call another controller action from a controller

Separate these functions from controllers and put them into model file. Then include the model file in your controller.

Constants in Objective-C

If you want to call something like this NSString.newLine; from objective c, and you want it to be static constant, you can create something like this in swift:

public extension NSString {
    @objc public static let newLine = "\n"
}

And you have nice readable constant definition, and available from within a type of your choice while stile bounded to context of type.

how to download file in react js

You can use FileSaver.js to achieve this goal:

const saveFile = () => {
fileSaver.saveAs(
  process.env.REACT_APP_CLIENT_URL + "/resources/cv.pdf",
  "MyCV.pdf"
);

};

<button className="cv" onClick={saveFile}>
    Download File
</button>

How to always show scrollbar

Style your scroll bar Visibility, Color and Thickness like this:

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/recycler_bg"

        <!--Show Scroll Bar-->
        android:fadeScrollbars="false"
        android:scrollbarAlwaysDrawVerticalTrack="true"
        android:scrollbarFadeDuration="50000"

        <!--Scroll Bar thickness-->
        android:scrollbarSize="4dp"

        <!--Scroll Bar Color-->
        android:scrollbarThumbVertical="@color/colorSecondaryText"/>

Hope it help save some time.

What's the effect of adding 'return false' to a click event listener?

Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.

If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.

Most efficient way to map function over numpy array

I believe in newer version( I use 1.13) of numpy you can simply call the function by passing the numpy array to the fuction that you wrote for scalar type, it will automatically apply the function call to each element over the numpy array and return you another numpy array

>>> import numpy as np
>>> squarer = lambda t: t ** 2
>>> x = np.array([1, 2, 3, 4, 5])
>>> squarer(x)
array([ 1,  4,  9, 16, 25])

How to change the button text of <input type="file" />?

Works Perfectly on All Browsers Hope it will work for you too.

HTML:
<input type="file" class="custom-file-input">

CSS:

 .custom-file-input::-webkit-file-upload-button {
  visibility: hidden;
}
.custom-file-input::before {
  content: 'Select some files';
  display: inline-block;
  background: -webkit-linear-gradient(top, #f9f9f9, #e3e3e3);
  border: 1px solid #999;
  border-radius: 3px;
  padding: 5px 8px;
  outline: none;
  white-space: nowrap;
  -webkit-user-select: none;
  cursor: pointer;
  text-shadow: 1px 1px #fff;
  font-weight: 700;
  font-size: 10pt;
}
.custom-file-input:hover::before {
  border-color: black;
}
.custom-file-input:active::before {
  background: -webkit-linear-gradient(top, #e3e3e3, #f9f9f9);
}

Change content: 'Select some files'; with the text you want within ''

IF NOT WORKING WITH firefox then use this instead of input:

<label class="custom-file-input" for="Upload" >
</label>

<input id="Upload" type="file" multiple="multiple" name="_photos" accept="image/*" style="visibility: hidden">

NameError: name 'python' is not defined

It looks like you are trying to start the Python interpreter by running the command python.

However the interpreter is already started. It is interpreting python as a name of a variable, and that name is not defined.

Try this instead and you should hopefully see that your Python installation is working as expected:

print("Hello world!")

Show all tables inside a MySQL database using PHP?

How to get tables

1. SHOW TABLES

mysql> USE test;
Database changed
mysql> SHOW TABLES;
+----------------+
| Tables_in_test |
+----------------+
| t1             |
| t2             |
| t3             |
+----------------+
3 rows in set (0.00 sec)

2. SHOW TABLES IN db_name

mysql> SHOW TABLES IN another_db;
+----------------------+
| Tables_in_another_db |
+----------------------+
| t3                   |
| t4                   |
| t5                   |
+----------------------+
3 rows in set (0.00 sec)

3. Using information schema

mysql> SELECT TABLE_NAME
       FROM information_schema.TABLES
       WHERE TABLE_SCHEMA = 'another_db';
+------------+
| TABLE_NAME |
+------------+
| t3         |
| t4         |
| t5         |
+------------+
3 rows in set (0.02 sec)

to OP

you have fetched just 1 row. fix like this:

while ( $tables = $result->fetch_array())
{
    echo $tmp[0]."<br>";
}

and I think, information_schema would be better than SHOW TABLES

SELECT TABLE_NAME
FROM information_schema.TABLES 
WHERE TABLE_SCHEMA = 'your database name'

while ( $tables = $result->fetch_assoc())
{
    echo $tables['TABLE_NAME']."<br>";
}

What is “assert” in JavaScript?

It probably came with a testing library that some of your code is using. Here's an example of one (chances are it's not the same library as your code is using, but it shows the general idea):

http://chaijs.com/guide/styles/#assert

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

try this

echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";

In python, what is the difference between random.uniform() and random.random()?

random.random() gives you a random floating point number in the range [0.0, 1.0) (so including 0.0, but not including 1.0 which is also known as a semi-open range). random.uniform(a, b) gives you a random floating point number in the range [a, b], (where rounding may end up giving you b).

The implementation of random.uniform() uses random.random() directly:

def uniform(self, a, b):
    "Get a random number in the range [a, b) or [a, b] depending on rounding."
    return a + (b-a) * self.random()

random.uniform(0, 1) is basically the same thing as random.random() (as 1.0 times float value closest to 1.0 still will give you float value closest to 1.0 there is no possibility of a rounding error there).

Multiline strings in VB.NET

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

Error :- java runtime environment JRE or java development kit must be available in order to run eclipse

For mac :

I have added below two commands its working fine!

-vm
/usr/bin
/usr/libexec/java_home --verbose

Example

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

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

Make a link use POST instead of GET

Instead using javascript, you could also use a label sending a hidden form. Very simple and small solution. The label can be anywhere in your html.

_x000D_
_x000D_
<form style="display: none" action="postUrl" method="post">_x000D_
  <button type="submit" id="button_to_link"> </button>_x000D_
</form>_x000D_
<label style="text-decoration: underline" for="button_to_link">  link that posts </label>
_x000D_
_x000D_
_x000D_

Oracle: how to add minutes to a timestamp?

SELECT to_char(sysdate + (1/24/60) * 30, 'dd/mm/yy HH24:MI am') from dual;

simply you can use this with various date format....

Clear Application's Data Programmatically

combine code from 2 answers:

Here is the resulting combined source based answer

private void clearAppData() {
    try {
        // clearing app data
        if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager)getSystemService(ACTIVITY_SERVICE)).clearApplicationUserData(); // note: it has a return value!
        } else {
            String packageName = getApplicationContext().getPackageName();
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("pm clear "+packageName);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } 
}

How could I create a list in c++?

You should really use the standard List class. Unless, of course, this is a homework question, or you want to know how lists are implemented by STL.

You'll find plenty of simple tutorials via google, like this one. If you want to know how linked lists work "under the hood", try searching for C list examples/tutorials rather than C++.

Set 4 Space Indent in Emacs in Text Mode

Add this to your .emacs file:

This will set the width that a tab is displayed to 2 characters (change the number 2 to whatever you want)

(setq default-tab-width 2)

To make sure that emacs is actually using tabs instead of spaces:

(global-set-key (kbd "TAB") 'self-insert-command)

As an aside, the default for emacs when backspacing over a tab is to convert it to spaces and then delete a space. This can be annoying. If you want it to just delete the tab, you can do this:

(setq c-backspace-function 'backward-delete-char)

Enjoy!

How to execute 16-bit installer on 64-bit Win7?

Bottom line at the top: Get newer programs or get an older computer.

The solution is simple. It sucks but it's simple. For old programs keep an old computer up and running. Some times you just can't find the same game experience in the new games as the old ones. Sometimes there are programs that have no new counterparts that do the same thing. You basically have 2 choices at that point. On the bright side. Old computers can run $20 -$100 and that can buy you the whole system; monitor, tower, keyboard, mouse and speakers. If you have the patience to run old programs you should have the patience to find what you are looking for in want ads. I have 4 old computers running; 2 windows 98, 2 windows xp. The my wife and I each have win7 computers.

Sorting arrays in NumPy by column

I suppose this works: a[a[:,1].argsort()]

This indicates the second column of a and sort it based on it accordingly.

Efficiently counting the number of lines of a text file. (200mb+)

There is a faster way I found that does not require looping through the entire file

only on *nix systems, there might be a similar way on windows ...

$file = '/path/to/your.file';

//Get number of lines
$totalLines = intval(exec("wc -l '$file'"));

How do I select elements of an array given condition?

Actually I would do it this way:

L1 is the index list of elements satisfying condition 1;(maybe you can use somelist.index(condition1) or np.where(condition1) to get L1.)

Similarly, you get L2, a list of elements satisfying condition 2;

Then you find intersection using intersect(L1,L2).

You can also find intersection of multiple lists if you get multiple conditions to satisfy.

Then you can apply index in any other array, for example, x.

Convert a JSON string to object in Java ME?

Just make a Json object in java with the following Json String.In your case

{name:"MyNode", width:200, height:100}

if the above is your Json string , just create a Json Object with it.

JsonString ="{name:"MyNode", width:200, height:100}";
JSONObject yourJsonObject = new JSONObject(JsonString);
System.out.println("name=" + yourJsonObject.getString("name"));
System.out.println("width=" + yourJsonObject.getString("width"));

How to define partitioning of DataFrame?

So to start with some kind of answer : ) - You can't

I am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.

Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.

If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments.

Conditional operator in Python?

From Python 2.5 onwards you can do:

value = b if a > 10 else c

Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost:

value = [c, b][a > 10]

There's also another hack using 'and ... or' but it's best to not use it as it has an undesirable behaviour in some situations that can lead to a hard to find bug. I won't even write the hack here as I think it's best not to use it, but you can read about it on Wikipedia if you want.

Using OR in SQLAlchemy

From the tutorial:

from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

Keytool is not recognized as an internal or external command

I finally solved the problem!!! You should first set the jre path to system variables by navigating to::

control panel > System and Security > System > Advanced system settings 

Under System variables click on new

Variable name: KEY_PATH
Variable value: C:\Program Files (x86)\Java\jre1.8.0_171\bin

Where Variable value should be the path to your JDK's bin folder.

Then open command prompt and Change directory to the same JDK's bin folder like this

C:\Program Files (x86)\Java\jre1.8.0_171\bin 

then paste,

keytool -list -v -keystore "C:\Users\user\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android   

NOTE: People are confusing jre and jdk. All I did applied strictly to jre

arranging div one below the other

Set the main div CSS to somthing like:

<style>
    .wrapper{
        display:flex;
        flex-direction: column;
    }
</style>

<div id="wrapper">
        <div id="inner1">This is inner div 1</div>
        <div id="inner2">This is inner div 2</div>
</div>

For more flexbox CSS refer: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Converting bytes to megabytes

BTW: Hard drive manufacturers don't count as authorities on this one!

Oh, yes they do (and the definition they assume from the S.I. is the correct one). On a related issue, see this post on CodingHorror.

how to increase the limit for max.print in R

See ?options:

options(max.print=999999)

Python Requests requests.exceptions.SSLError: [Errno 8] _ssl.c:504: EOF occurred in violation of protocol

Setting verify=False only skips verifying the server certificate, but will not help to resolve SSL protocol errors.

This issue is likely due to SSLv2 being disabled on the web server, but Python 2.x tries to establish a connection with PROTOCOL_SSLv23 by default. This happens at https://github.com/python/cpython/blob/360aa60b2a36f5f6e9e20325efd8d472f7559b1e/Lib/ssl.py#L1057

You can monkey-patch ssl.wrap_socket() in the ssl module by overriding the ssl_version keyword parameter. The following code can be used as-is. Put this at the start of your program before making any requests.

import ssl
from functools import wraps
def sslwrap(func):
    @wraps(func)
    def bar(*args, **kw):
        kw['ssl_version'] = ssl.PROTOCOL_TLSv1
        return func(*args, **kw)
    return bar

ssl.wrap_socket = sslwrap(ssl.wrap_socket)

PHPExcel - creating multiple sheets by iteration

You can write different sheets as follows

$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("creater");
$objPHPExcel->getProperties()->setLastModifiedBy("Middle field");
$objPHPExcel->getProperties()->setSubject("Subject");
$objWorkSheet = $objPHPExcel->createSheet();
$work_sheet_count=3;//number of sheets you want to create
$work_sheet=0;
while($work_sheet<=$work_sheet_count){ 
     if($work_sheet==0){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 1')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==1){
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 2')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     if($work_sheet==2){
         $objWorkSheet = $objPHPExcel->createSheet($work_sheet_count);
         $objWorkSheet->setTitle("Worksheet$work_sheet");
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 3')->getStyle('A1')->getFont()->setBold(true);
         $objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
     }
     $work_sheet++;
}

$filename='file-name'.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cach

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');

java.net.ConnectException: localhost/127.0.0.1:8080 - Connection refused

  1. Add Internet permission in Androidmanifest.xml file

uses-permission android:name="android.permission.INTERNET

  1. Open cmd in windows
  2. type "ipconfig" then press enter
  3. find IPv4 Address. . . . . . . . . . . : 192.168.X.X
  4. use this URL "http://192.168.X.X:your_virtual_server_port/your_service.php"

Enable PHP Apache2

If anyone gets

ERROR: Module phpX.X does not exist!

just install the module for your current php version:

apt-get install libapache2-mod-phpX.X

Where is JAVA_HOME on macOS Mojave (10.14) to Lion (10.7)?

For Mac Yosemite,

JDK 1.7.0_xx is using

$ ls -ltar /usr/bin/java
/System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java

JAVA_HOME

/Library/Java/JavaVirtualMachines/jdk1.7.0_xx.jdk/Contents/Home

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">

Compiling a C++ program with gcc

gcc can actually compile c++ code just fine. The errors you received are linker errors, not compiler errors.

Odds are that if you change the compilation line to be this:

gcc info.C -lstdc++

which makes it link to the standard c++ library, then it will work just fine.

However, you should just make your life easier and use g++.


EDIT:

Rup says it best in his comment to another answer:

[...] gcc will select the correct back-end compiler based on file extension (i.e. will compile a .c as C and a .cc as C++) and links binaries against just the standard C and GCC helper libraries by default regardless of input languages; g++ will also select the correct back-end based on extension except that I think it compiles all C source as C++ instead (i.e. it compiles both .c and .cc as C++) and it includes libstdc++ in its link step regardless of input languages.

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

Just to add up my bit:
Remember, you're gonna need to have at least 2 areas in your MVC application to get the routeValues: { area="" } working; otherwise the area value will be used as a query-string parameter and you link will look like this: /?area=

If you don't have at least 2 areas, you can fix this behavior by:
1. editing the default route in RouteConfig.cs like this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

OR
2. Adding a dummy area to your MVC project.

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

The problem is because of post back happens on submit button click. So while posting data on submit click again write before returning View()

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");

NotificationCenter issue on Swift 3

Notifications appear to have changed again (October 2016).

// Register to receive notification

NotificationCenter.default.addObserver(self, selector: #selector(yourClass.yourMethod), name: NSNotification.Name(rawValue: "yourNotificatioName"), object: nil)

// Post notification

NotificationCenter.default.post(name: NSNotification.Name(rawValue: "yourNotificationName"), object: nil)

Equivalent of typedef in C#

C# supports some inherited covariance for event delegates, so a method like this:

void LowestCommonHander( object sender, EventArgs e ) { ... } 

Can be used to subscribe to your event, no explicit cast required

gcInt.MyEvent += LowestCommonHander;

You can even use lambda syntax and the intellisense will all be done for you:

gcInt.MyEvent += (sender, e) =>
{
    e. //you'll get correct intellisense here
};

What is the recommended way to make a numeric TextField in JavaFX?

If you want to apply the same listener to more than one TextField here is the simplest solution:

TextField txtMinPrice, txtMaxPrice = new TextField();

ChangeListener<String> forceNumberListener = (observable, oldValue, newValue) -> {
    if (!newValue.matches("\\d*"))
      ((StringProperty) observable).set(oldValue);
};

txtMinPrice.textProperty().addListener(forceNumberListener);
txtMaxPrice.textProperty().addListener(forceNumberListener);

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

What is the difference between Class.getResource() and ClassLoader.getResource()?

To answer the question whether there is any caching going on.

I investigated this point further by running a stand-alone Java application that continuously loaded a file from disk using the getResourceAsStream ClassLoader method. I was able to edit the file, and the changes were reflected immediately, i.e., the file was reloaded from disk without caching.

However: I'm working on a project with several maven modules and web projects that have dependencies on each other. I'm using IntelliJ as my IDE to compile and run the web projects.

I noticed that the above seemed to no longer hold true, the reason being that the file that I was being loaded is now baked into a jar and deployed to the depending web project. I only noticed this after trying to change the file in my target folder, to no avail. This made it seem as though there was caching going on.

ASP.Net MVC: How to display a byte array image from model

One way is to add this to a new c# class or HtmlExtensions class

public static class HtmlExtensions
{
    public static MvcHtmlString Image(this HtmlHelper html, byte[] image)
    {
        var img = String.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(image));
        return new MvcHtmlString("<img src='" + img + "' />");
    }
}

then you can do this in any view

@Html.Image(Model.ImgBytes)

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

how to make a full screen div, and prevent size to be changed by content?

<html>
<div style="width:100%; height:100%; position:fixed; left:0;top:0;overflow:hidden;">

</div>
</html>

How do I set the default value for an optional argument in Javascript?

If str is null, undefined or 0, this code will set it to "hai"

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.

Ajax using https on an http page

Try JSONP.

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

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

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

How to replace all occurrences of a string in Javascript?

I just want to share my solution, based on some of the functional features of last versions of JavaScript:

   var str = "Test abc test test abc test test test abc test test abc";

   var result = str.split(' ').reduce((a, b) => {
      return b == 'abc' ? a : a + ' ' + b;   })

  console.warn(result)

Copy a git repo without history

Isn't this exactly what squashing a rebase does? Just squash everything except the last commit and then (force) push it.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Improving on João's and satru's code, I suggest creating a cursor mixin that can be used to build a cursor with an execute that accepts nested iterables and handles them correctly. A better name would be nice, though... For Python3, use str instead of basestring.

from MySQLdb.cursors import Cursor

class BetterExecuteMixin(object):
    """
    This mixin class provides an implementation of the execute method
    that properly handles sequence arguments for use with IN tests.
    Examples:
    execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
    # Notice that when the sequence is the only argument, you still need
    # a surrounding tuple:
    execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
    """

    def execute(self, query, args=None):
        if args is not None:
            try:
                iter(args)
            except TypeError:
                args = (args,)
            else:
                if isinstance(args, basestring):
                    args = (args,)
            real_params = []
            placeholders = []
            for arg in args:
                # sequences that we treat as a single argument
                if isinstance(arg, basestring):
                    real_params.append(arg)
                    placeholders.append('%s')
                    continue
                try:
                    real_params.extend(arg)
                    placeholders.append(','.join(['%s']*len(arg)))
                except TypeError:
                    real_params.append(arg)
                    placeholders.append('%s')
            args = real_params
            query = query % tuple(placeholders)
        return super(BetterExecuteMixin, self).execute(query, args)

class BetterCursor(BetterExecuteMixin, Cursor):
    pass

This can then be used as follows (and it's still backwards compatible!):

import MySQLdb
conn = MySQLdb.connect(user='user', passwd='pass', db='dbname', host='host',
                       cursorclass=BetterCursor)
cursor = conn.cursor()
cursor.execute('SELECT * FROM foo WHERE id IN (%s) AND type=%s', ([1,2,3], 'bar'))
cursor.execute('SELECT * FROM foo WHERE id IN (%s)', ([1,2,3],))
cursor.execute('SELECT * FROM foo WHERE type IN (%s)', (['bar', 'moo'],))
cursor.execute('SELECT * FROM foo WHERE type=%s', 'bar')
cursor.execute('SELECT * FROM foo WHERE type=%s', ('bar',))

how to get docker-compose to use the latest image from repository

I spent half a day with this problem. The reason was that be sure to check where the volume was recorded.

volumes: - api-data:/src/patterns

But the fact is that in this place was the code that we changed. But when updating the docker, the code did not change.

Therefore, if you are checking someone else's code and for some reason you are not updating, check this.

And so in general this approach works:

docker-compose down

docker-compose build

docker-compose up -d

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

I resolved it by giving permission to the user on each of the directories that you're using, like so:

sudo chown user /home/user/git

and so on.

How to import keras from tf.keras in Tensorflow?

Use the keras module from tensorflow like this:

import tensorflow as tf

Import classes

from tensorflow.python.keras.layers import Input, Dense

or use directly

dense = tf.keras.layers.Dense(...)

EDIT Tensorflow 2

from tensorflow.keras.layers import Input, Dense

and the rest stays the same.

ASP.NET MVC passing an ID in an ActionLink to the controller

Doesn't look like you are using the correct overload of ActionLink. Try this:-

<%=Html.ActionLink("Modify Villa", "Modify", new {id = "1"})%>

This assumes your view is under the /Views/Villa folder. If not then I suspect you need:-

<%=Html.ActionLink("Modify Villa", "Modify", "Villa", new {id = "1"}, null)%>

Defining lists as global variables in Python

When you assign a variable (x = ...), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:

x = 0
def f():
    x = 1
f()
print x #=>0

and expect 1. Instead, you need do declare that you intend to use the global x:

x = 0
def f():
    global x
    x = 1
f()
print x #=>1

But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.

Also very important: Member assignment (x.name = ...), item assignment (collection[key] = ...), slice assignment (sliceable[start:end] = ...) and propably more are all method calls as well! And therefore you don't need global to change a global's members or call it methods (even when they mutate the object).

Pull new updates from original GitHub repository into forked GitHub repository

To automatically sync your forked repository with the parent repository, you could use the Pull App on GitHub.

Refer to the Readme for more details.

For advanced setup where you want to preserve your changes done to the forked repository, refer to my answer on a similar question here.

Usage of MySQL's "IF EXISTS"

if exists(select * from db1.table1 where sno=1 )
begin
select * from db1.table1 where sno=1 
end
else if (select * from db2.table1 where sno=1 )
begin
select * from db2.table1 where sno=1 
end
else
begin
print 'the record does not exits'
end

Grep and Python

Adapted from a grep in python.

Accepts a list of filenames via [2:], does no exception handling:

#!/usr/bin/env python
import re, sys, os

for f in filter(os.path.isfile, sys.argv[2:]):
    for line in open(f).readlines():
        if re.match(sys.argv[1], line):
            print line

sys.argv[1] resp sys.argv[2:] works, if you run it as an standalone executable, meaning

chmod +x

first

SQL Inner join more than two tables

Please find inner join for more than 2 table here

Here are 4 table name like

  1. Orders
  2. Customers
  3. Student
  4. Lecturer

So the SQL code would be:

select o.orderid, c.customername, l.lname, s.studadd, s.studmarks 
from orders o 
    inner join customers c on o.customrid = c.customerid 
    inner join lecturer l  on o.customrid = l.id 
    inner join student s   on o.customrid=s.studmarks;

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

The best way is to download an installer package: .pkg on mac. Prefer the latest stable version.

Here is the link: Node.js

This package will eventually overwrite the previous version and set environment variables accordingly. Just run the installer and its done within a few clicks.

How to test if a DataSet is empty?

We can check total three ways.

  1. if(ds != null)
  2. if(ds.Tables.Count > 0 )
  3. if(ds.Tables[0].Rows.Count > 0)

How to take off line numbers in Vi?

Easily Display Line number:

set number flag (to show line number type)

:set nu or :set number

to unset the number flag (hide the line number type)

:set nu!

If you need number every time you start vi/vim, append following line to your ~/.vimrc file:

set number

Open a file at particular location/line number

$ vi +linenumber file.rb
$ vi +300 initlib.rb 

Fixing Sublime Text 2 line endings?

to chnage line endings from LF to CRLF:

open Sublime and follow the steps:-

1 press Ctrl+shift+p then install package name line unify endings

then again press Ctrl+shift+p

2 in the blank input box type "Line unify ending "

3 Hit enter twice

Sublime may freeze for sometimes and as a result will change the line endings from LF to CRLF

Mysql: Select rows from a table that are not in another

SELECT a.* FROM 
FROM tbl_1 a
MINUS
SELECT b.* FROM 
FROM tbl_2 b

Cannot edit in read-only editor VS Code

You are in the "Output" tab instead of the Terminal. The output tab is actually only for you to read from.

enter image description here

Press F5 to begin Debugging and it'll bring you into the Terminal tab.

The terminal is interactive, so you can read output AND type back. It is indeed a console prompt/ terminal (hence its name).

enter image description here

Change the Textbox height?

I know this is a kind of old post, but I found myself in this same issue, and by investigating a bit I found out that the Height of a WinForms TextBox is actually calculated depending on the size of the font it contains, it's just not quite equal to it.

This guy explains how the calculation is done, and how you can set it on your TextBox to get the desired Height.

Cheers!

Angular 2 @ViewChild annotation returns undefined

In my case, I had an input variable setter using the ViewChild, and the ViewChild was inside of an *ngIf directive, so the setter was trying to access it before the *ngIf rendered (it would work fine without the *ngIf, but would not work if it was always set to true with *ngIf="true").

To solve, I used Rxjs to make sure any reference to the ViewChild waited until the view was initiated. First, create a Subject that completes when after view init.

export class MyComponent implements AfterViewInit {
  private _viewInitWaiter$ = new Subject();

  ngAfterViewInit(): void {
    this._viewInitWaiter$.complete();
  }
}

Then, create a function that takes and executes a lambda after the subject completes.

private _executeAfterViewInit(func: () => any): any {
  this._viewInitWaiter$.subscribe(null, null, () => {
    return func();
  })
}

Finally, make sure references to the ViewChild use this function.

@Input()
set myInput(val: any) {
    this._executeAfterViewInit(() => {
        const viewChildProperty = this.viewChild.someProperty;
        ...
    });
}

@ViewChild('viewChildRefName', {read: MyViewChildComponent}) viewChild: MyViewChildComponent;

How to make layout with rounded corners..?

Use CardView to get rounded edges for any layouts. Use card_view:cardCornerRadius="5dp" for cardview to get rounded layout edges.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:card_view="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical">

      <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        card_view:cardCornerRadius="5dp">
          <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                android:padding="15dp"
                android:weightSum="1">

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".3"
                    android:text="@string/quote_code"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight=".7"
                    android:text="@string/quote_details"
                    android:textColor="@color/white"
                    android:textSize="@dimen/text_head_size" />
            </LinearLayout>
       </android.support.v7.widget.CardView>
   </LinearLayout>

.datepicker('setdate') issues, in jQuery

If you would like to support really old browsers you should parse the date string, since using the ISO8601 date format with the Date constructor is not supported pre IE9:

var queryDate = '2009-11-01',
    dateParts = queryDate.match(/(\d+)/g)
    realDate = new Date(dateParts[0], dateParts[1] - 1, dateParts[2]);  
                                    // months are 0-based!
// For >= IE9
var realDate = new Date('2009-11-01');  

$('#datePicker').datepicker({ dateFormat: 'yy-mm-dd' }); // format to show
$('#datePicker').datepicker('setDate', realDate);

Check the above example here.

Executing Shell Scripts from the OS X Dock?

As long as your script is executable and doesn't have any extension you can drag it as-is to the right side (Document side) of the Dock and it will run in a terminal window when clicked instead of opening an editor.

If you want to have an extension (like foo.sh), you can go to the file info window in Finder and change the default application for that particular script from whatever it is (TextEdit, TextMate, whatever default is set on your computer for .sh files) to Terminal. It will then just execute instead of opening in a text editor. Again, you will have to drag it to the right side of the Dock.

What is a callback URL in relation to an API?

It's a mechanism to invoke an API in an asynchrounous way. The sequence is the following

  1. your app invokes the url, passing as parameter the callback url
  2. the api respond with a 20x http code (201 I guess, but refer to the api docs)
  3. the api works on your request for a certain amount of time
  4. the api invokes your app to give you the results, at the callback url address.

So you can invoke the api and tell your user the request is "processing" or "acquired" for example, and then update the status when you receive the response from the api.

Hope it makes sense. -G

max(length(field)) in mysql

Ok, I am not sure what are you using(MySQL, SLQ Server, Oracle, MS Access..) But you can try the code below. It work in W3School example DB. Here try this:

SELECT city, max(length(city)) FROM Customers;

How to set image on QPushButton?

You can also use:

button.setStyleSheet("qproperty-icon: url(:/path/to/images.png);");

Note: This is a little hacky. You should use this only as last resort. Icons should be set from C++ code or Qt Designer.

SELECT only rows that contain only alphanumeric characters in MySQL

Change the REGEXP to Like

SELECT * FROM table_name WHERE column_name like '%[^a-zA-Z0-9]%'

this one works fine

Handling the TAB character in Java

Or you could just perform a trim() on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)

Represent space and tab in XML tag

If you are talking about the issue where multiple and non-space whitespace characters are stripped specifically from attribute values, then yes, encoding them as character references such as &#9; will fix it.

How to wait for a JavaScript Promise to resolve before resuming function?

I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).

Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).


Careful management of promise-based code can control the order of execution for many async operations.

I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff() function, and then attaching a .then() handler to it after calling it:

function kickOff() {
  return new Promise(function(resolve, reject) {
    $("#output").append("start");

    setTimeout(function() {
      resolve();
    }, 1000);
  }).then(function() {
    $("#output").append(" middle");
    return " end";
  });
}

kickOff().then(function(result) {
    // use the result here
    $("#output").append(result);
});

This will return output in a guaranteed order - like this:

start
middle
end

Update in 2018 (three years after this answer was written):

If you either transpile your code or run your code in an environment that supports ES7 features such as async and await, you can now use await to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.

Instead of the ES6 way of doing things:

someFunc().then(someFunc2).then(result => {
    // process result here
}).catch(err => {
    // process error here
});

You can do this:

// returns a promise
async function wrapperFunc() {
    try {
        let r1 = await someFunc();
        let r2 = await someFunc2(r1);
        // now process r2
        return someValue;     // this will be the resolved value of the returned promise
    } catch(e) {
        console.log(e);
        throw e;      // let caller know the promise was rejected with this reason
    }
}

wrapperFunc().then(result => {
    // got final result
}).catch(err => {
    // got error
});

Playing HTML5 video on fullscreen in android webview

Edit: please see my other answer, as you probably don't need this now.

As you said, in API levels 11+ a HTML5VideoFullScreen$VideoSurfaceView is passed. But I don't think you are right when you say that "it doens't have a MediaPlayer".

This is the way to reach the MediaPlayer instance from the HTML5VideoFullScreen$VideoSurfaceView instance using reflection:

@SuppressWarnings("rawtypes")
Class c1 = Class.forName("android.webkit.HTML5VideoFullScreen$VideoSurfaceView");
Field f1 = c1.getDeclaredField("this$0");
f1.setAccessible(true);

@SuppressWarnings("rawtypes")
Class c2 = f1.getType().getSuperclass();
Field f2 = c2.getDeclaredField("mPlayer");
f2.setAccessible(true);

Object ___html5VideoViewInstance = f1.get(focusedChild); // Look at the code in my other answer to this same question to see whats focusedChild

Object ___mpInstance = f2.get(___html5VideoViewInstance); // This is the MediaPlayer instance.

So, now you could set the onCompletion listener of the MediaPlayer instance like this:

OnCompletionListener ocl = new OnCompletionListener()
{
    @Override
    public void onCompletion(MediaPlayer mp)
    {
        // Do stuff
    }
};

Method m1 = f2.getType().getMethod("setOnCompletionListener", new Class[] { Class.forName("android.media.MediaPlayer$OnCompletionListener") });
m1.invoke(___mpInstance, ocl);

The code doesn't fail but I'm not completely sure if that onCompletion listener will really be called or if it could be useful to your situation. But just in case someone would like to try it.

How to update an object in a List<> in C#

This was a new discovery today - after having learned the class/struct reference lesson!

You can use Linq and "Single" if you know the item will be found, because Single returns a variable...

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;

Rotate image with javascript

var angle = 0;
$('#button').on('click', function() {
    angle += 90;
    $('#image').css('transform','rotate(' + angle + 'deg)');
});

Try this code.

Reverse of JSON.stringify?

how about this partial solution?

I wanna store (using a Config node) a global bigobj, with data + methods (as an alternative to importing an external library), used in many function nodes on my flow:

Strange but it works: The global variable 'bigobj':

{
some[]more[]{dx:"here"} , // array of objects with  array of objects. The 'Config' node requires JSON.
.....
 "get_dx": "function( d,p) {  return this.some[d].more[p].dx; }"  // test function
}

i.e. a JSON version of a function.... (all in one line :( )

USE: Inside a function node:

var bigO = global.get("bigobj");

function callJSONMethod(obj, fname, a, b, c, d){
    // see: https://stackoverflow.com/questions/49125059/how-to-pass-parameters-to-an-eval-based-function-injavascript
var wrap = s => "{ return " + obj[fname] + " };" //return the block having function expression
var func = new Function(wrap(obj[fname]));
return func.call( null ).call( obj, a, b, c, d); //invoke the function using arguments
}

msg.payload =callJSONMethod(bigO, "get_dx", 2, 2); 
return msg:

returns "here", unbelieve!

i.e I must add the function callJSONMethod() to any function block using bigobj..... maybe acceptable.

Best regards

Git: How configure KDiff3 as merge tool and diff tool

Well, the problem is that Git can't find KDiff3 in the %PATH%.

In a typical Unix installation all executables reside in several well-known locations (/bin/, /usr/bin/, /usr/local/bin/, etc.), and one can invoke a program by simply typing its name in a shell processor (e.g. cmd.exe :) ).

In Microsoft Windows, programs are usually installed in dedicated paths so you can't simply type kdiff3 in a cmd session and get KDiff3 running.

The hard solution: you should tell Git where to find KDiff3 by specifying the full path to kdiff3.exe. Unfortunately, Git doesn't like spaces in the path specification in its config, so the last time I needed this, I ended up with those ancient "C:\Progra~1...\kdiff3.exe" as if it was late 1990s :)

The simple solution: Edit your computer settings and include the directory with kdiff3.exe in %PATH%. Then test if you can invoke it from cmd.exe by its name and then run Git.

How can I get the image url in a Wordpress theme?

I strongly recommend the following:

<img src="<?php echo get_stylesheet_directory_uri(); ?>/img-folder/your_image.jpg">

It works for almost any file you want to add to your wordpress project, be it image or CSS.

Calling multiple JavaScript functions on a button click

Because you're returning from the first method call, the second doesn't execute.

Try something like

OnClientClick="var b = validateView();ShowDiv1(); return b"

or reverse the situation,

OnClientClick="ShowDiv1();return validateView();"

or if there is a dependency of div1 on the validation routine.

OnClientClick="var b = validateView(); if (b) ShowDiv1(); return b"

What might be best is to encapsulate multiple inline statements into a mini function like so, to simplify the call:

// change logic to suit taste
function clicked()  {
    var b = validateView(); 
    if (b) 
        ShowDiv1()
    return b;
}

and then

OnClientClick="return clicked();"

Applying function with multiple arguments to create a new pandas column

One more dict style clean syntax:

df["new_column"] = df.apply(lambda x: x["A"] * x["B"], axis = 1)

or,

df["new_column"] = df["A"] * df["B"]

ReactNative: how to center text?

You can use two approaches for this...

  1. To make text align center horizontally, apply this Property (textAlign:"center"). Now to make the text align vertically, first check direction of flex. If flexDirection is column apply property (justifyContent:"center") and if flexDirection is row is row apply property (alignItems : "center") .

  2. To Make text align center apply same property (textAlign:"center"). Now to make it align vertically make the hieght of the <Text> </Text> equal to view and then apply property (textAlignVertical: "center")...

Most Probably it will Work...

get current date with 'yyyy-MM-dd' format in Angular 4

Here is the example:

function MethodName($scope)
{
    $scope.date = new Date();
}

You can change the format in view here we have a code

<div ng-app ng-controller="MethodName">
    My current date is {{date | date:'yyyy-MM-dd'}} . 
</div>

I hope it helps.

Parse Json string in C#

Instead of an arraylist or dictionary you can also use a dynamic. Most of the time I use EasyHttp for this, but sure there will by other projects that do the same. An example below:

var http = new HttpClient();
http.Request.Accept = HttpContentTypes.ApplicationJson;
var response = http.Get("url");
var body = response.DynamicBody;
Console.WriteLine("Name {0}", body.AppName.Description);
Console.WriteLine("Name {0}", body.AppName.Value);

On NuGet: EasyHttp

SQL Server AS statement aliased column within WHERE statement

SQL doesn't typically allow you to reference column aliases in WHERE, GROUP BY or HAVING clauses. MySQL does support referencing column aliases in the GROUP BY and HAVING, but I stress that it will cause problems when porting such queries to other databases.

When in doubt, use the actual column name:

SELECT t.lat AS latitude 
  FROM poi_table t
 WHERE t.lat < 500

I added a table alias to make it easier to see what is an actual column vs alias.

Update


A computed column, like the one you see here:

SELECT *, 
       ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) AS distance
  FROM poi_table 
 WHERE distance < 500;

...doesn't change that you can not reference a column alias in the WHERE clause. For that query to work, you'd have to use:

SELECT *, 
       ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) AS distance
  FROM poi_table
 WHERE ( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) ) < 500;

Be aware that using a function on a column (IE: RADIANS(lat)) will render an index useless, if one exists on the column.

How to get item count from DynamoDB?

If you happen to reach here, and you are working with C#, here is the code:

var cancellationToken = new CancellationToken();

var request = new ScanRequest("TableName") {Select = Select.COUNT};

var result = context.Client.ScanAsync(request, cancellationToken).Result;

totalCount = result.Count;

Handling identity columns in an "Insert Into TABLE Values()" statement?

set identity_insert customer on
insert into Customer(id,Name,city,Salary) values(8,'bcd','Amritsar',1234)

where 'customer' is table name

Encrypting & Decrypting a String in C#

Try this class:

public class DataEncryptor
{
    TripleDESCryptoServiceProvider symm;

    #region Factory
    public DataEncryptor()
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
    }
    public DataEncryptor(TripleDESCryptoServiceProvider keys)
    {
        this.symm = keys;
    }

    public DataEncryptor(byte[] key, byte[] iv)
    {
        this.symm = new TripleDESCryptoServiceProvider();
        this.symm.Padding = PaddingMode.PKCS7;
        this.symm.Key = key;
        this.symm.IV = iv;
    }

    #endregion

    #region Properties
    public TripleDESCryptoServiceProvider Algorithm
    {
        get { return symm; }
        set { symm = value; }
    }
    public byte[] Key
    {
        get { return symm.Key; }
        set { symm.Key = value; }
    }
    public byte[] IV
    {
        get { return symm.IV; }
        set { symm.IV = value; }
    }

    #endregion

    #region Crypto

    public byte[] Encrypt(byte[] data) { return Encrypt(data, data.Length); }
    public byte[] Encrypt(byte[] data, int length)
    {
        try
        {
            // Create a MemoryStream.
            var ms = new MemoryStream();

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            var cs = new CryptoStream(ms,
                symm.CreateEncryptor(symm.Key, symm.IV),
                CryptoStreamMode.Write);

            // Write the byte array to the crypto stream and flush it.
            cs.Write(data, 0, length);
            cs.FlushFinalBlock();

            // Get an array of bytes from the 
            // MemoryStream that holds the 
            // encrypted data.
            byte[] ret = ms.ToArray();

            // Close the streams.
            cs.Close();
            ms.Close();

            // Return the encrypted buffer.
            return ret;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string EncryptString(string text)
    {
        return Convert.ToBase64String(Encrypt(Encoding.UTF8.GetBytes(text)));
    }

    public byte[] Decrypt(byte[] data) { return Decrypt(data, data.Length); }
    public byte[] Decrypt(byte[] data, int length)
    {
        try
        {
            // Create a new MemoryStream using the passed 
            // array of encrypted data.
            MemoryStream ms = new MemoryStream(data);

            // Create a CryptoStream using the MemoryStream 
            // and the passed key and initialization vector (IV).
            CryptoStream cs = new CryptoStream(ms,
                symm.CreateDecryptor(symm.Key, symm.IV),
                CryptoStreamMode.Read);

            // Create buffer to hold the decrypted data.
            byte[] result = new byte[length];

            // Read the decrypted data out of the crypto stream
            // and place it into the temporary buffer.
            cs.Read(result, 0, result.Length);
            return result;
        }
        catch (CryptographicException ex)
        {
            Console.WriteLine("A cryptographic error occured: {0}", ex.Message);
        }
        return null;
    }

    public string DecryptString(string data)
    {
        return Encoding.UTF8.GetString(Decrypt(Convert.FromBase64String(data))).TrimEnd('\0');
    }

    #endregion

}

and use it like this:

string message="A very secret message here.";
DataEncryptor keys=new DataEncryptor();
string encr=keys.EncryptString(message);

// later
string actual=keys.DecryptString(encr);

Verify ImageMagick installation

EDIT: The info and script below only applies to iMagick class - which is not added by default with ImageMagick!!!

If I want to know if imagemagick is installed and actually working as a php extension, I paste this snippet into a web accessible file

<?php

error_reporting(E_ALL); 
ini_set( 'display_errors','1');

/* Create a new imagick object */
$im = new Imagick();

/* Create new image. This will be used as fill pattern */
$im->newPseudoImage(50, 50, "gradient:red-black");

/* Create imagickdraw object */
$draw = new ImagickDraw();

/* Start a new pattern called "gradient" */
$draw->pushPattern('gradient', 0, 0, 50, 50);

/* Composite the gradient on the pattern */
$draw->composite(Imagick::COMPOSITE_OVER, 0, 0, 50, 50, $im);

/* Close the pattern */
$draw->popPattern();

/* Use the pattern called "gradient" as the fill */
$draw->setFillPatternURL('#gradient');

/* Set font size to 52 */
$draw->setFontSize(52);

/* Annotate some text */
$draw->annotation(20, 50, "Hello World!");

/* Create a new canvas object and a white image */
$canvas = new Imagick();
$canvas->newImage(350, 70, "white");

/* Draw the ImagickDraw on to the canvas */
$canvas->drawImage($draw);

/* 1px black border around the image */
$canvas->borderImage('black', 1, 1);

/* Set the format to PNG */
$canvas->setImageFormat('png');

/* Output the image */
header("Content-Type: image/png");
echo $canvas;
?>

You should see a hello world graphic:

enter image description here

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

This is wrong. It will just kill the session when the associated client (webbrowser) has not accessed the website for more than 15 minutes. The activity certainly counts, exactly as you initially expected, seeing your attempt to solve this.

The HttpSession#setMaxInactiveInterval() doesn't change much here by the way. It does exactly the same as <session-timeout> in web.xml, with the only difference that you can change/set it programmatically during runtime. The change by the way only affects the current session instance, not globally (else it would have been a static method).


To play around and experience this yourself, try to set <session-timeout> to 1 minute and create a HttpSessionListener like follows:

@WebListener
public class HttpSessionChecker implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent event) {
        System.out.printf("Session ID %s created at %s%n", event.getSession().getId(), new Date());
    }

    public void sessionDestroyed(HttpSessionEvent event) {
        System.out.printf("Session ID %s destroyed at %s%n", event.getSession().getId(), new Date());
    }

}

(if you're not on Servlet 3.0 yet and thus can't use @WebListener, then register in web.xml as follows):

<listener>
    <listener-class>com.example.HttpSessionChecker</listener-class>
</listener>

Note that the servletcontainer won't immediately destroy sessions after exactly the timeout value. It's a background job which runs at certain intervals (e.g. 5~15 minutes depending on load and the servletcontainer make/type). So don't be surprised when you don't see destroyed line in the console immediately after exactly one minute of inactivity. However, when you fire a HTTP request on a timed-out-but-not-destroyed-yet session, it will be destroyed immediately.

See also:

Switching between GCC and Clang/LLVM using CMake

If the default compiler chosen by cmake is gcc and you have installed clang, you can use the easy way to compile your project with clang:

$ mkdir build && cd build
$ CXX=clang++ CC=clang cmake ..
$ make -j2

How can I change Eclipse theme?

Take a look at rogerdudler/eclipse-ui-themes . In the readme there is a link to a file that you need to extract into your eclipse/dropins folder.

When you have done that go to

Window -> Preferences -> General -> Appearance

And change the theme from GTK (or what ever it is currently) to Dark Juno (or Dark).

That will change the UI to a nice dark theme but to get the complete look and feel you can get the Eclipse Color Theme plugin from eclipsecolorthemes.org. The easiest way is to add this update URI to "Help -> Install New Software" and install it from there.

Eclipse Color Themes

This adds a "Color Theme" menu item under

Window -> Preferences -> Appearance

Where you can select from a large range of editor themes. My preferred one to use with PyDev is Wombat. For Java Solarized Dark

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

How do I properly 'printf' an integer and a string in C?

scanf("%s",str) scans only until it finds a whitespace character. With the input "A 1", it will scan only the first character, hence s2 points at the garbage that happened to be in str, since that array wasn't initialised.

session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium

Using Visual Studio

I couldn't resolve the version mismatch by following any of the answers when using Visual Studio, but simply updating the Selenium.WebDriver and Selenium.WebDriver.ChromeDriver nuget packages to the latest versions worked.

I was using Chrome v78, and upgrading chromedriver to v78 still gave the incompatibility error. CAD's answer led me to the solution.

String.equals versus ==

== operator compares the reference of an object in Java. You can use string's equals method .

String s = "Test";
if(s.equals("Test"))
{
    System.out.println("Equal");
}

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.

<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />

Depending on how much traffic you get, this may be the most practical reason for adding the link.

Info on setting up a cookieless domain:

http://www.ravelrumba.com/blog/static-cookieless-domain/

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true
    }

    Or for VS 2017:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
    }
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"

Decorators with parameters?

It is a decorator that can be called in a variety of ways (tested in python3.7):

import functools


def my_decorator(*args_or_func, **decorator_kwargs):

    def _decorator(func):

        @functools.wraps(func)
        def wrapper(*args, **kwargs):

            if not args_or_func or callable(args_or_func[0]):
                # Here you can set default values for positional arguments
                decorator_args = ()
            else:
                decorator_args = args_or_func

            print(
                "Available inside the wrapper:",
                decorator_args, decorator_kwargs
            )

            # ...
            result = func(*args, **kwargs)
            # ...

            return result

        return wrapper

    return _decorator(args_or_func[0]) \
        if args_or_func and callable(args_or_func[0]) else _decorator


@my_decorator
def func_1(arg): print(arg)

func_1("test")
# Available inside the wrapper: () {}
# test


@my_decorator()
def func_2(arg): print(arg)

func_2("test")
# Available inside the wrapper: () {}
# test


@my_decorator("any arg")
def func_3(arg): print(arg)

func_3("test")
# Available inside the wrapper: ('any arg',) {}
# test


@my_decorator("arg_1", 2, [3, 4, 5], kwarg_1=1, kwarg_2="2")
def func_4(arg): print(arg)

func_4("test")
# Available inside the wrapper: ('arg_1', 2, [3, 4, 5]) {'kwarg_1': 1, 'kwarg_2': '2'}
# test

PS thanks to user @norok2 - https://stackoverflow.com/a/57268935/5353484

UPD Decorator for validating arguments and/or result of functions and methods of a class against annotations. Can be used in synchronous or asynchronous version: https://github.com/EvgeniyBurdin/valdec

Getting Class type from String

You can use the forName method of Class:

Class cls = Class.forName(clsName);
Object obj = cls.newInstance();

Changing a specific column name in pandas DataFrame

What about?

df.columns.values[2] = "new_name"

Difference between except: and except Exception as e: in Python

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

Converting PKCS#12 certificate into PEM using OpenSSL

If you need a PEM file without any password you can use this solution.

Just copy and paste the private key and the certificate to the same file and save as .pem.

The file will look like:

-----BEGIN PRIVATE KEY-----
............................
............................
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...........................
...........................
-----END CERTIFICATE-----

That's the only way I found to upload certificates to Cisco devices for HTTPS.

Why doesn't RecyclerView have onItemClickListener()?

Android Recyclerview With onItemClickListener, Why we cant try this is working like ListView only.

Source : Link

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {

private OnItemClickListener mListener;
public interface OnItemClickListener {
    public void onItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
    mListener = listener;
    mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }
    });
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
    View childView = view.findChildViewUnder(e.getX(), e.getY());
    if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
        mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
    }
    return false;
}

@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) {
}

@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

  }
}

And Set this to RecyclerView:

    recyclerView = (RecyclerView)rootView. findViewById(R.id.recyclerView);
    RecyclerView.LayoutManager mLayoutManager = new            LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(mLayoutManager);
    recyclerView.addOnItemTouchListener(
            new RecyclerItemClickListener(getActivity(), new   RecyclerItemClickListener.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    // TODO Handle item click
                    Log.e("@@@@@",""+position);
                }
            })
    );

Making a UITableView scroll when text field is selected

I'm doing something very similar it's generic, no need to compute something specific for your code. Just check the remarks on the code:

In MyUIViewController.h

@interface MyUIViewController: UIViewController <UITableViewDelegate, UITableViewDataSource>
{
     UITableView *myTableView;
     UITextField *actifText;
}

@property (nonatomic, retain) IBOutlet UITableView *myTableView;
@property (nonatomic, retain) IBOutlet UITextField *actifText;

- (IBAction)textFieldDidBeginEditing:(UITextField *)textField;
- (IBAction)textFieldDidEndEditing:(UITextField *)textField;

-(void) keyboardWillHide:(NSNotification *)note;
-(void) keyboardWillShow:(NSNotification *)note;

@end

In MyUIViewController.m

@implementation MyUIViewController

@synthesize myTableView;
@synthesize actifText;

- (void)viewDidLoad 
{
    // Register notification when the keyboard will be show
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillShow:)
                                          name:UIKeyboardWillShowNotification
                                          object:nil];

    // Register notification when the keyboard will be hide
    [[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(keyboardWillHide:)
                                          name:UIKeyboardWillHideNotification
                                          object:nil];
}

// To be link with your TextField event "Editing Did Begin"
//  memoryze the current TextField
- (IBAction)textFieldDidBeginEditing:(UITextField *)textField
{
    self.actifText = textField;
}

// To be link with your TextField event "Editing Did End"
//  release current TextField
- (IBAction)textFieldDidEndEditing:(UITextField *)textField
{
    self.actifText = nil;
}

-(void) keyboardWillShow:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    // Start animation
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Reduce size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height -= keyboardBounds.size.height;
    else 
        frame.size.height -= keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    // Scroll the table view to see the TextField just above the keyboard
    if (self.actifText)
      {
        CGRect textFieldRect = [self.myTableView convertRect:self.actifText.bounds fromView:self.actifText];
        [self.myTableView scrollRectToVisible:textFieldRect animated:NO];
      }

    [UIView commitAnimations];
}

-(void) keyboardWillHide:(NSNotification *)note
{
    // Get the keyboard size
    CGRect keyboardBounds;
    [[note.userInfo valueForKey:UIKeyboardFrameBeginUserInfoKey] getValue: &keyboardBounds];

    // Detect orientation
    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
    CGRect frame = self.myTableView.frame;

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:0.3f];

    // Increase size of the Table view 
    if (orientation == UIInterfaceOrientationPortrait || orientation == UIInterfaceOrientationPortraitUpsideDown)
        frame.size.height += keyboardBounds.size.height;
    else 
        frame.size.height += keyboardBounds.size.width;

    // Apply new size of table view
    self.myTableView.frame = frame;

    [UIView commitAnimations];
}

@end

Swift 1.2+ version:

class ViewController: UIViewController, UITextFieldDelegate {
    @IBOutlet weak var activeText: UITextField!
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillShow:"),
            name: UIKeyboardWillShowNotification,
            object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: Selector("keyboardWillHide:"),
            name: UIKeyboardWillHideNotification,
            object: nil)
    }

    func textFieldDidBeginEditing(textField: UITextField) {
        activeText = textField
    }

    func textFieldDidEndEditing(textField: UITextField) {
        activeText = nil
    }

    func keyboardWillShow(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height -= keyboardSize.height
            tableView.frame = frame
            if activeText != nil {
                let rect = tableView.convertRect(activeText.bounds, fromView: activeText)
                tableView.scrollRectToVisible(rect, animated: false)
            }
            UIView.commitAnimations()
        }
    }

    func keyboardWillHide(note: NSNotification) {
        if let keyboardSize = (note.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
            var frame = tableView.frame
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationBeginsFromCurrentState(true)
            UIView.setAnimationDuration(0.3)
            frame.size.height += keyboardSize.height
            tableView.frame = frame
            UIView.commitAnimations()
        }
    }
}

jQuery UI DatePicker to show month year only

Add one more simple solution

 $(function() {
    $('.monthYearPicker').datepicker({
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'M yy'
    }).focus(function() {
        var thisCalendar = $(this);
        $('.ui-datepicker-calendar').detach();
        $('.ui-datepicker-close').click(function() {
var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
thisCalendar.datepicker('setDate', new Date(year, month, 1));
        });
    });
});

http://jsfiddle.net/tmnasim/JLydp/
Features:

  • display only month/year
  • Adds the month year value to input box only on clicking of Done button
  • No "reopen" behavior when click "Done"
    ------------------------------------
    another solution that work well for datepicker and monthpicker in the same page:(also avoid the bug of mutiple click on previous button in IE, that may occur if we use focus function)
    JS fiddle link

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

C/C++ NaN constant (literal)?

Is this possible to assign a NaN to a double or float in C ...?

Yes, since C99, (C++11) <math.h> offers the below functions:

#include <math.h>
double nan(const char *tagp);
float nanf(const char *tagp);
long double nanl(const char *tagp);

which are like their strtod("NAN(n-char-sequence)",0) counterparts and NAN for assignments.

// Sample C code
uint64_t u64;
double x;
x = nan("0x12345");
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = -strtod("NAN(6789A)",0);
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);
x = NAN;
memcpy(&u64, &x, sizeof u64); printf("(%" PRIx64 ")\n", u64);

Sample output: (Implementation dependent)

(7ff8000000012345)
(fff000000006789a)
(7ff8000000000000)

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

How to take backup of a single table in a MySQL database?

You can either use mysqldump from the command line:

mysqldump -u username -p password dbname tablename > "path where you want to dump"

You can also use MySQL Workbench:

Go to left > Data Export > Select Schema > Select tables and click on Export

Can I obtain method parameter name using Java reflection?

You can retrieve the method with reflection and detect its argument types. Check getParameterTypes().

However, you can't tell the name of the argument used.

ReactJS - How to use comments?

To summarize, JSX doesn't support comments, either html-like or js-like:

<div>
    /* This will be rendered as text */
    // as well as this
    <!-- While this will cause compilation failure -->
</div>

and the only way to add comments "in" JSX is actually to escape into JS and comment in there:

<div>
    {/* This won't be rendered */}
    {// just be sure that your closing bracket is out of comment
    }
</div>

if you don't want to make some nonsense like

<div style={{display:'none'}}>
    actually, there are other stupid ways to add "comments"
    but cluttering your DOM is not a good idea
</div>

Finally, if you do want to create a comment node via React, you have to go much fancier, check out this answer.

How to alter a column and change the default value?

If you want to add a default value for the already created column, this works for me:

ALTER TABLE Persons
ALTER credit SET DEFAULT 0.0;

DIV table colspan: how?

You could always use CSS to simply adjust the width and the height of those elements that you want to do a colspan and rowspan and then simply omit displaying the overlapped DIVs. For example:

<div class = 'td colspan3 rowspan5'> Some data </div>

<style>

 .td
 {
   display: table-cell;
 }

 .colspan3
 {
   width: 300px; /*3 times the standard cell width of 100px - colspan3 */
 }

 .rowspan5
 {
   height: 500px; /* 5 times the standard height of a cell - rowspan5 */
 }

</style>

How do you make div elements display inline?

That's something else then:

_x000D_
_x000D_
div.inline { float:left; }_x000D_
.clearBoth { clear:both; }
_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<div class="inline">1<br />2<br />3</div>_x000D_
<br class="clearBoth" /><!-- you may or may not need this -->
_x000D_
_x000D_
_x000D_

The most efficient way to remove first N elements in a list?

You can use list slicing to archive your goal:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist

Outputs:

[6, 7, 8, 9]

Or del if you only want to use one list:

n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist

Outputs:

[6, 7, 8, 9]

How do I remove  from the beginning of a file?

Open the PHP file under question, in Notepad++.

Click on Encoding at the top and change from "Encoding in UTF-8 without BOM" to just "Encoding in UTF-8". Save and overwrite the file on your server.

How to change the button text for 'Yes' and 'No' buttons in the MessageBox.Show dialog?

I didn't think it would be that simple! go to this link: https://www.codeproject.com/Articles/18399/Localizing-System-MessageBox

Download the source. Take the MessageBoxManager.cs file, add it to your project. Now just register it once in your code (for example in the Main() method inside your Program.cs file) and it will work every time you call MessageBox.Show():

    MessageBoxManager.OK = "Alright";
    MessageBoxManager.Yes = "Yep!";
    MessageBoxManager.No = "Nope";
    MessageBoxManager.Register();

See this answer for the source code here for MessageBoxManager.cs.

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

When using docker-machine, you can copy images between machines mach1 and mach2 with:

docker $(docker-machine config <mach1>) save <image> | docker $(docker-machine config <mach2>) load

And of course you can also stick pv in the middle to get a progess indicator:

docker $(docker-machine config <mach1>) save <image> | pv | docker $(docker-machine config <mach2>) load

You may also omit one of the docker-machine config sub-shells, to use your current default docker-host.

docker save <image> | docker $(docker-machine config <mach>) load

to copy image from current docker-host to mach

or

docker $(docker-machine config <mach>) save <image> | docker load

to copy from mach to current docker-host.

Simple prime number generator in Python

There are some problems:

  • Why do you print out count when it didn't divide by x? It doesn't mean it's prime, it means only that this particular x doesn't divide it
  • continue moves to the next loop iteration - but you really want to stop it using break

Here's your code with a few fixes, it prints out only primes:

import math

def main():
    count = 3
    
    while True:
        isprime = True
        
        for x in range(2, int(math.sqrt(count) + 1)):
            if count % x == 0: 
                isprime = False
                break
        
        if isprime:
            print count
        
        count += 1

For much more efficient prime generation, see the Sieve of Eratosthenes, as others have suggested. Here's a nice, optimized implementation with many comments:

# Sieve of Eratosthenes
# Code by David Eppstein, UC Irvine, 28 Feb 2002
# http://code.activestate.com/recipes/117119/

def gen_primes():
    """ Generate an infinite sequence of prime numbers.
    """
    # Maps composites to primes witnessing their compositeness.
    # This is memory efficient, as the sieve is not "run forward"
    # indefinitely, but only as long as required by the current
    # number being tested.
    #
    D = {}
    
    # The running integer that's checked for primeness
    q = 2
    
    while True:
        if q not in D:
            # q is a new prime.
            # Yield it and mark its first multiple that isn't
            # already marked in previous iterations
            # 
            yield q
            D[q * q] = [q]
        else:
            # q is composite. D[q] is the list of primes that
            # divide it. Since we've reached q, we no longer
            # need it in the map, but we'll mark the next 
            # multiples of its witnesses to prepare for larger
            # numbers
            # 
            for p in D[q]:
                D.setdefault(p + q, []).append(p)
            del D[q]
        
        q += 1

Note that it returns a generator.

Angular update object in object array

updateValue(data){    
     // retriving index from array
     let indexValue = this.items.indexOf(data);
    // changing specific element in array
     this.items[indexValue].isShow =  !this.items[indexValue].isShow;
}

How to add new activity to existing project in Android Studio?

I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.

Unable to start Service Intent

For anyone else coming across this thread I had this issue and was pulling my hair out. I had the service declaration OUTSIDE of the '< application>' end tag DUH!

RIGHT:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>    

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        
</application>

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

WRONG but still compiles without errors:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  ...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity ...>
        ...
    </activity>

</application>

    <service android:name=".Service"/>

    <receiver android:name=".Receiver">
        <intent-filter>
            ...
        </intent-filter>
    </receiver>        

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

Adding multiple columns AFTER a specific column in MySQL

One possibility would be to not bother about reordering the columns in the table and simply modify it by add the columns. Then, create a view which has the columns in the order you want -- assuming that the order is truly important. The view can be easily changed to reflect any ordering that you want. Since I can't imagine that the order would be important for programmatic applications, the view should suffice for those manual queries where it might be important.

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//button[@class='btn btn-primary' and contains(text(), 'Submit')]") private WebElementFacade submitButton;

public void clickOnSubmitButton() {
    submitButton.click();
}   

Encode/Decode URLs in C++

Ordinarily adding '%' to the int value of a char will not work when encoding, the value is supposed to the the hex equivalent. e.g '/' is '%2F' not '%47'.

I think this is the best and concise solutions for both url encoding and decoding (No much header dependencies).

string urlEncode(string str){
    string new_str = "";
    char c;
    int ic;
    const char* chars = str.c_str();
    char bufHex[10];
    int len = strlen(chars);

    for(int i=0;i<len;i++){
        c = chars[i];
        ic = c;
        // uncomment this if you want to encode spaces with +
        /*if (c==' ') new_str += '+';   
        else */if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') new_str += c;
        else {
            sprintf(bufHex,"%X",c);
            if(ic < 16) 
                new_str += "%0"; 
            else
                new_str += "%";
            new_str += bufHex;
        }
    }
    return new_str;
 }

string urlDecode(string str){
    string ret;
    char ch;
    int i, ii, len = str.length();

    for (i=0; i < len; i++){
        if(str[i] != '%'){
            if(str[i] == '+')
                ret += ' ';
            else
                ret += str[i];
        }else{
            sscanf(str.substr(i + 1, 2).c_str(), "%x", &ii);
            ch = static_cast<char>(ii);
            ret += ch;
            i = i + 2;
        }
    }
    return ret;
}

Get changes from master into branch in Git

Scenario :

  • I created a branch from master say branch-1 and pulled it to my local.
  • My Friend created a branch from master say branch-2.
  • He committed some code changes to master.
  • Now I want to take those changes from master branch to my local branch.

Solution

git stash // to save all existing changes in local branch
git checkout master // Switch to master branch from branch-1
git pull // take changes from the master
git checkout branch-1 // switchback to your own branch
git rebase master // merge all the changes and move you git head  forward
git stash apply // reapply all you saved changes 

You can find conflicts on your file after executing "git stash apply". You need to fix it manually and now you are ready to push.

Can't bind to 'ngModel' since it isn't a known property of 'input'

I faced the same problem and the reason was that I was using ngModel in my MenuComponent. I imported my MenuComponent in app.module.ts, but I forgot to declare it.

Error

Declaring the MenuComponent solved my issue. I.e., as shown in the below image:

Solved issue

Best way to replace multiple characters in a string?

>>> string="abc&def#ghi"
>>> for ch in ['&','#']:
...   if ch in string:
...      string=string.replace(ch,"\\"+ch)
...
>>> print string
abc\&def\#ghi

Unix - copy contents of one directory to another

Try this:

cp Folder1/* Folder2/

passing argument to DialogFragment

In my case, none of the code above with bundle-operate works; Here is my decision (I don't know if it is proper code or not, but it works in my case):

public class DialogMessageType extends DialogFragment {
    private static String bodyText;

    public static DialogMessageType addSomeString(String temp){
        DialogMessageType f = new DialogMessageType();
        bodyText = temp;
        return f;
    };

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final String[] choiseArray = {"sms", "email"};
        String title = "Send text via:";
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(title).setItems(choiseArray, itemClickListener);
        builder.setCancelable(true);
        return builder.create();
    }

    DialogInterface.OnClickListener itemClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case 0:
                    prepareToSendCoordsViaSMS(bodyText);
                    dialog.dismiss();
                    break;
                case 1:
                    prepareToSendCoordsViaEmail(bodyText);
                    dialog.dismiss();
                    break;
                default:
                    break;
            }
        }
    };
[...]
}

public class SendObjectActivity extends FragmentActivity {
[...]

DialogMessageType dialogMessageType = DialogMessageType.addSomeString(stringToSend);
dialogMessageType.show(getSupportFragmentManager(),"dialogMessageType");

[...]
}

how to bypass Access-Control-Allow-Origin?

Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?

You would like to send multiple Access-Control-Allow-Origin headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin headers, or to put in multiple origins.

You can solve this by checking the origin, and sending back that one in the header, if it is allowed:

$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
    'http://mysite1.com',
    'https://www.mysite2.com',
    'http://www.mysite2.com',
];

if (in_array($origin, $allowed_domains)) {
    header('Access-Control-Allow-Origin: ' . $origin);
}

Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.

Why is it safer?

Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST requests and post data on someone's facebook - just while they are browsing your website.

Be very cautious when using the ACAO headers!

Execution failed for task :':app:mergeDebugResources'. Android Studio

I had that problem, but it was because my images changed them manually from .JPG to .PNG, so I just changed them with PNG paint and solved the problem

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 can you determine a point is between two other points on a line segment?

Using a more geometric approach, calculate the following distances:

ab = sqrt((a.x-b.x)**2 + (a.y-b.y)**2)
ac = sqrt((a.x-c.x)**2 + (a.y-c.y)**2)
bc = sqrt((b.x-c.x)**2 + (b.y-c.y)**2)

and test whether ac+bc equals ab:

is_on_segment = abs(ac + bc - ab) < EPSILON

That's because there are three possibilities:

  • The 3 points form a triangle => ac+bc > ab
  • They are collinear and c is outside the ab segment => ac+bc > ab
  • They are collinear and c is inside the ab segment => ac+bc = ab

Using the Underscore module with Node.js

The name _ used by the node.js REPL to hold the previous input. Choose another name.

Detect click inside/outside of element with single event handler

In vanilla javaScript - in ES6

_x000D_
_x000D_
(() => {_x000D_
    document.querySelector('.parent').addEventListener('click', event => {_x000D_
        alert(event.target.classList.contains('child') ? 'Child element.' : 'Parent element.');_x000D_
    });_x000D_
})();
_x000D_
.parent {_x000D_
    display: inline-block;_x000D_
    padding: 45px;_x000D_
    background: lightgreen;_x000D_
}_x000D_
.child {_x000D_
    width: 120px;_x000D_
    height:60px;_x000D_
    background: teal;_x000D_
}
_x000D_
<div class="parent">_x000D_
    <div class="child"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

CAST to DECIMAL in MySQL

If you need a lot of decimal numbers, in this example 17, I share with you MySql code:

This is the calculate:

=(9/1147)*100

SELECT TRUNCATE(((CAST(9 AS DECIMAL(30,20))/1147)*100),17);

Why does using an Underscore character in a LIKE filter give me all the results?

Modify your WHERE condition like this:

WHERE mycolumn LIKE '%\_%' ESCAPE '\'

This is one of the ways in which Oracle supports escape characters. Here you define the escape character with the escape keyword. For details see this link on Oracle Docs.

The '_' and '%' are wildcards in a LIKE operated statement in SQL.

The _ character looks for a presence of (any) one single character. If you search by columnName LIKE '_abc', it will give you result with rows having 'aabc', 'xabc', '1abc', '#abc' but NOT 'abc', 'abcc', 'xabcd' and so on.

The '%' character is used for matching 0 or more number of characters. That means, if you search by columnName LIKE '%abc', it will give you result with having 'abc', 'aabc', 'xyzabc' and so on, but no 'xyzabcd', 'xabcdd' and any other string that does not end with 'abc'.

In your case you have searched by '%_%'. This will give all the rows with that column having one or more characters, that means any characters, as its value. This is why you are getting all the rows even though there is no _ in your column values.

Convert Pandas Series to DateTime in a DataFrame

df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])

type(df.<column name>)

example: if you want to convert day which is initially a string to a Timestamp in Pandas

df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])

type(df.day)

The output will be pandas.tslib.Timestamp

Convert digits into words with JavaScript

This is in response to @LordZardeck's comment to @naomik's excellent answer above. Sorry, I would've commented directly but I've never posted before so I don't have the privilege to do so, so I am posting here instead.

Anyhow, I just happened to translate the ES5 version to a more readable form this past weekend so I'm sharing it here. This should be faithful to the original (including the recent edit) and I hope the naming is clear and accurate.

function int_to_words(int) {
  if (int === 0) return 'zero';

  var ONES  = ['','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
  var TENS  = ['','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety'];
  var SCALE = ['','thousand','million','billion','trillion','quadrillion','quintillion','sextillion','septillion','octillion','nonillion'];

  // Return string of first three digits, padded with zeros if needed
  function get_first(str) {
    return ('000' + str).substr(-3);
  }

  // Return string of digits with first three digits chopped off
  function get_rest(str) {
    return str.substr(0, str.length - 3);
  }

  // Return string of triplet convereted to words
  function triplet_to_words(_3rd, _2nd, _1st) {
    return (_3rd == '0' ? '' : ONES[_3rd] + ' hundred ') + (_1st == '0' ? TENS[_2nd] : TENS[_2nd] && TENS[_2nd] + '-' || '') + (ONES[_2nd + _1st] || ONES[_1st]);
  }

  // Add to words, triplet words with scale word
  function add_to_words(words, triplet_words, scale_word) {
    return triplet_words ? triplet_words + (scale_word && ' ' + scale_word || '') + ' ' + words : words;
  }

  function iter(words, i, first, rest) {
    if (first == '000' && rest.length === 0) return words;
    return iter(add_to_words(words, triplet_to_words(first[0], first[1], first[2]), SCALE[i]), ++i, get_first(rest), get_rest(rest));
  }

  return iter('', 0, get_first(String(int)), get_rest(String(int)));
}

When do you use POST and when do you use GET?

HTTP Post data doesn't have a specified limit on the amount of data, where as different browsers have different limits for GET's. The RFC 2068 states:

Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths

Specifically you should the right HTTP constructs for what they're used for. HTTP GET's shouldn't have side-effects and can be safely refreshed and stored by HTTP Proxies, etc.

HTTP POST's are used when you want to submit data against a url resource.

A typical example for using HTTP GET is on a Search, i.e. Search?Query=my+query A typical example for using a HTTP POST is submitting feedback to an online form.

How to select a schema in postgres when using psql?

key word :

SET search_path TO

example :

SET search_path TO your_schema_name;

How to get complete current url for Cakephp

The simplest way I found is it that includes host/path/query and
works in Controllers (Cakephp 3.4):

Cake\View\Helper\UrlHelper::build($this->request->getRequestTarget());

which returns something like this (we use it as login callback url) :

http://192.168.0.57/archive?melkId=12

vue.js 2 how to watch store values from vuex

I think the asker wants to use watch with Vuex.

this.$store.watch(
      (state)=>{
        return this.$store.getters.your_getter
      },
      (val)=>{
       //something changed do something

      },
      {
        deep:true
      }
      );

How to iterate over the keys and values with ng-repeat in AngularJS?

You can do it in your javascript (controller) or in your html (angular view)...

js:

$scope.arr = [];
for ( p in data ) {
  $scope.arr.push(p); 
}

html:

<tr ng-repeat="(k, v) in data">
    <td>{{k}}<input type="text" ng-model="data[k]"></td>
</tr>

I believe the html way is more angular , but you can also do in your controller and retrieve it in your html...

also not a bad idea to look at the Object keys, they give you the an array of the keys if you need them, more info here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Rebase array keys after unsetting elements

Try this:

$array = array_values($array);

Using array_values()

Kill Attached Screen in Linux

You could create a function to kill all existing sessions. take a look at Kill all detached screen sessions

to list all active sessions use screen -r

when listed, select with your mouse the session you are interested in and paste it. like this

screen -r

Change working directory in my current shell context when running Node script

The correct way to change directories is actually with process.chdir(directory). Here's an example from the documentation:

console.log('Starting directory: ' + process.cwd());
try {
  process.chdir('/tmp');
  console.log('New directory: ' + process.cwd());
}
catch (err) {
  console.log('chdir: ' + err);
}

This is also testable in the Node.js REPL:

[monitor@s2 ~]$ node
> process.cwd()
'/home/monitor'
> process.chdir('../');
undefined
> process.cwd();
'/home'

Simplest way to detect keypresses in javascript

Don't over complicate.

  document.addEventListener('keydown', logKey);
    function logKey(e) {
      if (`${e.code}` == "ArrowRight") {
        //code here
      }
          if (`${e.code}` == "ArrowLeft") {
        //code here
      }
          if (`${e.code}` == "ArrowDown") {
        //code here
      }
          if (`${e.code}` == "ArrowUp") {
        //code here
      }
    }

Getting only Month and Year from SQL DATE

For result: "YYYY-MM"

SELECT cast(YEAR(<DateColumn>) as varchar) + '-' + cast(Month(<DateColumn>) as varchar)