Programs & Examples On #Nodesets

Shared folder between MacOSX and Windows on Virtual Box

You should map your virtual network drive in Windows.

  1. Open command prompt in Windows (VirtualBox)
  2. Execute: net use x: \\vboxsvr\<your_shared_folder_name>
  3. You should see new drive X: in My Computer

In your case execute net use x: \\vboxsvr\win7

How to run the sftp command with a password from Bash script?

You can use a Python script with scp and os library to make a system call.

  1. ssh-keygen -t rsa -b 2048 (local machine)
  2. ssh-copy-id user@remote_server_address
  3. create a Python script like:
    import os
    cmd = 'scp user@remote_server_address:remote_file_path local_file_path'
    os.system(cmd)
  1. create a rule in crontab to automate your script
  2. done

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

Adding to this. If you use both INSERT IGNORE and ON DUPLICATE KEY UPDATE in the same statement, the update will still happen if the insert finds a duplicate key. In other words, the update takes precedence over the ignore. However, if the ON DUPLICATE KEY UPDATE clause itself causes a duplicate key error, that error will be ignored.

This can happen if you have more than one unique key, or if your update attempts to violate a foreign key constraint.

CREATE TABLE test 
 (id BIGINT (20) UNSIGNED AUTO_INCREMENT, 
  str VARCHAR(20), 
  PRIMARY KEY(id), 
  UNIQUE(str));

INSERT INTO test (str) VALUES('A'),('B');

/* duplicate key error caused not by the insert, 
but by the update: */
INSERT INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A'; 

/* duplicate key error is suppressed */
INSERT IGNORE INTO test (str) VALUES('B') 
 ON DUPLICATE KEY UPDATE str='A';

Reading/Writing a MS Word file in PHP

this works with vs < office 2007 and its pure PHP, no COM crap, still trying to figure 2007

<?php



/*****************************************************************
This approach uses detection of NUL (chr(00)) and end line (chr(13))
to decide where the text is:
- divide the file contents up by chr(13)
- reject any slices containing a NUL
- stitch the rest together again
- clean up with a regular expression
*****************************************************************/

function parseWord($userDoc) 
{
    $fileHandle = fopen($userDoc, "r");
    $line = @fread($fileHandle, filesize($userDoc));   
    $lines = explode(chr(0x0D),$line);
    $outtext = "";
    foreach($lines as $thisline)
      {
        $pos = strpos($thisline, chr(0x00));
        if (($pos !== FALSE)||(strlen($thisline)==0))
          {
          } else {
            $outtext .= $thisline." ";
          }
      }
     $outtext = preg_replace("/[^a-zA-Z0-9\s\,\.\-\n\r\t@\/\_\(\)]/","",$outtext);
    return $outtext;
} 

$userDoc = "cv.doc";

$text = parseWord($userDoc);
echo $text;


?>

AppFabric installation failed because installer MSI returned with error code : 1603

I finally made it. I was able to install AppFabric for Win Server 2012 R2. I am not really sure what exact change made it worked. I saw and tried many many solutions from various websites but above solution of making changes to Registry - 'HKEY_CLASSES_ROOT'worked (please think twice before making changes to Registry on production environment - this was my demo environment so I just went ahead); I changed the temporary folder path but it did not worked first time. Then I deleted the registry entry and then uninstalled AppFabric 1.1 pre-installed instance from Control panel. Then I tried Installation and it worked. This also restored the Registry entry.

AES Encryption for an NSString on the iPhone

Since you haven't posted any code, it's difficult to know exactly which problems you're encountering. However, the blog post you link to does seem to work pretty decently... aside from the extra comma in each call to CCCrypt() which caused compile errors.

A later comment on that post includes this adapted code, which works for me, and seems a bit more straightforward. If you include their code for the NSData category, you can write something like this: (Note: The printf() calls are only for demonstrating the state of the data at various points — in a real application, it wouldn't make sense to print such values.)

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSString *key = @"my password";
    NSString *secret = @"text to encrypt";

    NSData *plain = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *cipher = [plain AES256EncryptWithKey:key];
    printf("%s\n", [[cipher description] UTF8String]);

    plain = [cipher AES256DecryptWithKey:key];
    printf("%s\n", [[plain description] UTF8String]);
    printf("%s\n", [[[NSString alloc] initWithData:plain encoding:NSUTF8StringEncoding] UTF8String]);

    [pool drain];
    return 0;
}

Given this code, and the fact that encrypted data will not always translate nicely into an NSString, it may be more convenient to write two methods that wrap the functionality you need, in forward and reverse...

- (NSData*) encryptString:(NSString*)plaintext withKey:(NSString*)key {
    return [[plaintext dataUsingEncoding:NSUTF8StringEncoding] AES256EncryptWithKey:key];
}

- (NSString*) decryptData:(NSData*)ciphertext withKey:(NSString*)key {
    return [[[NSString alloc] initWithData:[ciphertext AES256DecryptWithKey:key]
                                  encoding:NSUTF8StringEncoding] autorelease];
}

This definitely works on Snow Leopard, and @Boz reports that CommonCrypto is part of the Core OS on the iPhone. Both 10.4 and 10.5 have /usr/include/CommonCrypto, although 10.5 has a man page for CCCryptor.3cc and 10.4 doesn't, so YMMV.


EDIT: See this follow-up question on using Base64 encoding for representing encrypted data bytes as a string (if desired) using safe, lossless conversions.

How to add 10 minutes to my (String) time?

I used the code below to add a certain time interval to the current time.

    int interval = 30;  
    SimpleDateFormat df = new SimpleDateFormat("HH:mm");
    Calendar time = Calendar.getInstance();

    Log.i("Time ", String.valueOf(df.format(time.getTime())));

    time.add(Calendar.MINUTE, interval);

    Log.i("New Time ", String.valueOf(df.format(time.getTime())));

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Seems to be a typo error in that package of gcc. The solution:

mv /usr/include/c++/4.x/i486-linux-gnu /usr/include/c++/4.x/i686-linux-gnu/64

Error: free(): invalid next size (fast):

I encountered such a situation where code was circumventing STL's api and writing to the array unsafely when someone resizes it. Adding the assert here caught it:

void Logo::add(const QVector3D &v, const QVector3D &n)
{
 GLfloat *p = m_data.data() + m_count;
 *p++ = v.x();
 *p++ = v.y();
 *p++ = v.z();
 *p++ = n.x();
 *p++ = n.y();
 *p++ = n.z();
 m_count += 6;
 Q_ASSERT( m_count <= m_data.size() );
}

How to create our own Listener interface in android?

Create listener interface.

public interface YourCustomListener
{
    public void onCustomClick(View view);
            // pass view as argument or whatever you want.
}

And create method setOnCustomClick in another activity(or fragment) , where you want to apply your custom listener......

  public void setCustomClickListener(YourCustomListener yourCustomListener)
{
    this.yourCustomListener= yourCustomListener;
}

Call this method from your First activity, and pass the listener interface...

How to set a default value with Html.TextBoxFor?

you can try this

<%= Html.TextBoxFor(x => x.Age, new { @Value = "0"}) %>

git stash changes apply to new branch?

If you have some changes on your workspace and you want to stash them into a new branch use this command:

git stash branch branchName

It will make:

  1. a new branch
  2. move changes to this branch
  3. and remove latest stash (Like: git stash pop)

Filename timestamp in Windows CMD batch script getting truncated

for /f "tokens=2-8 delims=.:/ " %%a in ("%date% %time: =0%") do set DateNtime=%%c-%%a-%%b_%%d-%%e-%%f.%%g
echo %DateNtime%

Or, from the command line:

for /f "tokens=2-8 delims=.:/ " %a in ("%date% %time: =0%") do echo %c-%a-%b_%d-%e-%f.%g 

EDIT: As per bryce's non-standard time/date specs. (03-Sep-12 9:06:21.54)

@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-7 delims=.:/- " %%a in ("%date% %time%") do (
  if "%%b"=="Jan" set MM=01
  if "%%b"=="Feb" set MM=02
  if "%%b"=="Mar" set MM=03
  if "%%b"=="Apr" set MM=04
  if "%%b"=="May" set MM=05
  if "%%b"=="Jun" set MM=06
  if "%%b"=="Jul" set MM=07
  if "%%b"=="Aug" set MM=08
  if "%%b"=="Sep" set MM=09
  if "%%b"=="Oct" set MM=10
  if "%%b"=="Nov" set MM=11
  if "%%b"=="Dec" set MM=12
  set HH=0%%d
  set HH=!HH:~-2!
  echo 20%%c-!MM!-%%a_!HH!-%%e-%%f.%%g
)
endlocal

Wrapping a react-router Link in an html button

Many of the solutions have focused on complicating things.

Using withRouter is a really long solution for something as simple as a button that links to somewhere else in the App.

If you are going for S.P.A. (single page application), the easiest answer I have found is to use with the button's equivalent className.

This ensures you are maintaining shared state / context without reloading your entire app as is done with

import { NavLink } from 'react-router-dom'; // 14.6K (gzipped: 5.2 K)

// Where link.{something} is the imported data
<NavLink className={`bx--btn bx--btn--primary ${link.className}`} to={link.href} activeClassName={'active'}>
    {link.label}
</NavLink>

// Simplified version:
<NavLink className={'bx--btn bx--btn--primary'} to={'/myLocalPath'}>
    Button without using withRouter
</NavLink>

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

rolling back to node v10.17.0 fixed the problem to me.

You can use nvm to do so:

https://github.com/nvm-sh/nvm

> nvm install 10.17.0
> nvm use 10.17.0
> node -v
10.17.0

How can I sort an ArrayList of Strings in Java?

Check Collections#sort method. This automatically sorts your list according to natural ordering. You can apply this method on each sublist you obtain using List#subList method.

private List<String> teamsName = new ArrayList<String>();
List<String> subList = teamsName.subList(1, teamsName.size());
Collections.sort(subList);

how to add json library

You can also install simplejson.

If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:

 pip install simplejson

This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".

Matplotlib figure facecolor (background color)

If you want to change background color, try this:

plt.rcParams['figure.facecolor'] = 'white'

"Actual or formal argument lists differs in length"

Say you have defined your class like this:

    @Data
    @AllArgsConstructor(staticName = "of")
    private class Pair<P,Q> {

        public P first;
        public Q second;
    }

So when you will need to create a new instance, it will need to take the parameters and you will provide it like this as defined in the annotation.

Pair<Integer, String> pair = Pair.of(menuItemId, category);

If you define it like this, you will get the error asked for.

Pair<Integer, String> pair = new Pair(menuItemId, category);

MySQL Workbench Dark Theme

Quoting Yoga...

For Mac users, the code_editor.xml file is in MBP HD/ Applications/MySQLWorkbench.app/Contents/Resources/data/

I just discovered by dumbfounded experimentation (i.e. first thing I tried, worked) that if I copy that file to...

/Users/your.username/Library/Application Support/MySQL/Workbench/code_editor.xml

...and then edit it there, it does indeed override. Just worked perfectly for me on Mac OS X Sierra and MySQL Workbench 6.3.

Is it possible that one domain name has multiple corresponding IP addresses?

This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.

SQL How to Select the most recent date item

You haven't specified what the query should return if more than one document is added at the same time, so this query assumes you want all of them returned:

SELECT t.ID,
       t.USER_ID,
       t.DATE_ADDED,
       t.DATE_VIEWED,
       t.DOCUMENT_ID,
       t.URL,
       t.DOCUMENT_TITLE,
       t.DOCUMENT_DATE
FROM (
  SELECT test_table.*,
         RANK()
         OVER (ORDER BY DOCUMENT_DATE DESC) AS the_rank
  FROM   test_table
  WHERE  user_id = value
  )
WHERE the_rank = 1;

This query will only make one pass through the data.

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

One solution for this can be found with find.

$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt

Find has quite a few options, you can get pretty specific on what you include and exclude.

Edit: Adam in the comments noted that this is recursive. find options mindepth and maxdepth can be useful in controlling this.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

Here's a C implementation based on Agoston's Computer Graphics and Geometric Modeling: Implementation and Algorithms p. 304, with H ? [0, 360] and S,V ? [0, 1].

#include <math.h>

typedef struct {
    double r;       // ? [0, 1]
    double g;       // ? [0, 1]
    double b;       // ? [0, 1]
} rgb;

typedef struct {
    double h;       // ? [0, 360]
    double s;       // ? [0, 1]
    double v;       // ? [0, 1]
} hsv;

rgb hsv2rgb(hsv HSV)
{
    rgb RGB;
    double H = HSV.h, S = HSV.s, V = HSV.v,
            P, Q, T,
            fract;

    (H == 360.)?(H = 0.):(H /= 60.);
    fract = H - floor(H);

    P = V*(1. - S);
    Q = V*(1. - S*fract);
    T = V*(1. - S*(1. - fract));

    if      (0. <= H && H < 1.)
        RGB = (rgb){.r = V, .g = T, .b = P};
    else if (1. <= H && H < 2.)
        RGB = (rgb){.r = Q, .g = V, .b = P};
    else if (2. <= H && H < 3.)
        RGB = (rgb){.r = P, .g = V, .b = T};
    else if (3. <= H && H < 4.)
        RGB = (rgb){.r = P, .g = Q, .b = V};
    else if (4. <= H && H < 5.)
        RGB = (rgb){.r = T, .g = P, .b = V};
    else if (5. <= H && H < 6.)
        RGB = (rgb){.r = V, .g = P, .b = Q};
    else
        RGB = (rgb){.r = 0., .g = 0., .b = 0.};

    return RGB;
}

CodeIgniter - File upload required validation

  1. set a rule to check the file name (if the form is multipart)

    $this->form_validation->set_rules('upload_file[name]', 'Upload file', 'required', 'No upload image :(');

  2. overwrite the $_POST array as follows:

    $_POST['upload_file'] = $_FILES['upload_file']

  3. and then do:

    $this->form_validation->run()

How can I delete all of my Git stashes at once?

I wanted to keep a few recent stashes, but delete everything else.

Because all stashes get renumbered when you drop one, this is actually easy to do with while. To delete all stashes older than stash@{19}:

while git stash drop 'stash@{20}'; do true; done

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The reason for the exception is that and implicitly calls bool. First on the left operand and (if the left operand is True) then on the right operand. So x and y is equivalent to bool(x) and bool(y).

However the bool on a numpy.ndarray (if it contains more than one element) will throw the exception you have seen:

>>> import numpy as np
>>> arr = np.array([1, 2, 3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

The bool() call is implicit in and, but also in if, while, or, so any of the following examples will also fail:

>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> if arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> while arr: pass
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> arr or arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

There are more functions and statements in Python that hide bool calls, for example 2 < x < 10 is just another way of writing 2 < x and x < 10. And the and will call bool: bool(2 < x) and bool(x < 10).

The element-wise equivalent for and would be the np.logical_and function, similarly you could use np.logical_or as equivalent for or.

For boolean arrays - and comparisons like <, <=, ==, !=, >= and > on NumPy arrays return boolean NumPy arrays - you can also use the element-wise bitwise functions (and operators): np.bitwise_and (& operator)

>>> np.logical_and(arr > 1, arr < 3)
array([False,  True, False], dtype=bool)

>>> np.bitwise_and(arr > 1, arr < 3)
array([False,  True, False], dtype=bool)

>>> (arr > 1) & (arr < 3)
array([False,  True, False], dtype=bool)

and bitwise_or (| operator):

>>> np.logical_or(arr <= 1, arr >= 3)
array([ True, False,  True], dtype=bool)

>>> np.bitwise_or(arr <= 1, arr >= 3)
array([ True, False,  True], dtype=bool)

>>> (arr <= 1) | (arr >= 3)
array([ True, False,  True], dtype=bool)

A complete list of logical and binary functions can be found in the NumPy documentation:

document.getElementById('btnid').disabled is not working in firefox and chrome

Try setting the disabled attribute directly:

if ( someCondition == true ) {
   document.getElementById('btn1').setAttribute('disabled', 'disabled');
} else {
   document.getElementById('btn1').removeAttribute('disabled');
}

compareTo() vs. equals()

Equals can be more efficient then compareTo.

If the length of the character sequences in String doesn't match there is no way the Strings are equal so rejection can be much faster.

Moreover if it is same object (identity equality rather then logical equality), it will also be more efficient.

If they also implemented hashCode caching it could be even faster to reject non-equals in case their hashCode's doesn't match.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

For Jest 24.9+ we just need to add --testTimeout in the command line

--testTimeout= 10000 // timeout of 10s

The default timeout value is 5000. This will be applicable for all test cases.

or if you want to give timeout to particular function only then you can use this syntax while declaring the test case.

test(name, fn, timeout)

example

test('example', async () => {
  

}, 10000); // timeout of 10s (default is 5000)

How to keep keys/values in same order as declared?

Another alternative is to use Pandas dataframe as it guarantees the order and the index locations of the items in a dict-like structure.

How many threads is too many?

As many threads as the CPU cores is what I've heard very often.

How do I format axis number format to thousands with a comma in matplotlib?

You can use matplotlib.ticker.funcformatter

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


def func(x, pos):  # formatter function takes tick label and tick position
    s = '%d' % x
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()

enter image description here

What is the worst real-world macros/pre-processor abuse you've ever come across?

When I first came across macros in C they had me stumped for days. Below is what I was faced with. I imagine it makes perfect sense to C experts and is super efficient however for me to try and work out what exactly was going on meant cutting and pasting all the different macros together until the whole function could be viewed. Surely that's not good practice?! What's wrong with using a plain old function?!

#define AST_LIST_MOVE_CURRENT(newhead, field) do { \
typeof ((newhead)->first) __list_cur = __new_prev; \
AST_LIST_REMOVE_CURRENT(field); \
AST_LIST_INSERT_TAIL((newhead), __list_cur, field); \
} while (0) 

Don't change link color when a link is clicked

just give

a{
color:blue
}

even if its is visited it will always be blue

Connecting to remote URL which requires authentication using Java

i did that this way you need to do this just copy paste it be happy

    HttpURLConnection urlConnection;
    String url;
 //   String data = json;
    String result = null;
    try {
        String username ="[email protected]";
        String password = "12345678";

        String auth =new String(username + ":" + password);
        byte[] data1 = auth.getBytes(UTF_8);
        String base64 = Base64.encodeToString(data1, Base64.NO_WRAP);
        //Connect
        urlConnection = (HttpURLConnection) ((new URL(urlBasePath).openConnection()));
        urlConnection.setDoOutput(true);
        urlConnection.setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestProperty("Authorization", "Basic "+base64);
        urlConnection.setRequestProperty("Accept", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setConnectTimeout(10000);
        urlConnection.connect();
        JSONObject obj = new JSONObject();

        obj.put("MobileNumber", "+97333746934");
        obj.put("EmailAddress", "[email protected]");
        obj.put("FirstName", "Danish");
        obj.put("LastName", "Hussain");
        obj.put("Country", "BH");
        obj.put("Language", "EN");
        String data = obj.toString();
        //Write
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(data);
        writer.close();
        outputStream.close();
        int responseCode=urlConnection.getResponseCode();
        if (responseCode == HttpsURLConnection.HTTP_OK) {
            //Read
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

        String line = null;
        StringBuilder sb = new StringBuilder();

        while ((line = bufferedReader.readLine()) != null) {
            sb.append(line);
        }

        bufferedReader.close();
        result = sb.toString();

        }else {
        //    return new String("false : "+responseCode);
        new String("false : "+responseCode);
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

How do you Encrypt and Decrypt a PHP String?

Historical Note: This was written at the time of PHP4. This is what we call "legacy code" now.

I have left this answer for historical purposes - but some of the methods are now deprecated, DES encryption method is not a recommended practice, etc.

I have not updated this code for two reasons: 1) I no longer work with encryption methods by hand in PHP, and 2) this code still serves the purpose it was intended for: to demonstrate the minimum, simplistic concept of how encryption can work in PHP.

If you find a similarly simplistic, "PHP encryption for dummies" kind of source that can get people started in 10-20 lines of code or less, let me know in comments.

Beyond that, please enjoy this Classic Episode of early-era PHP4 minimalistic encryption answer.


Ideally you have - or can get - access to the mcrypt PHP library, as its certainly popular and very useful a variety of tasks. Here's a run down of the different kinds of encryption and some example code: Encryption Techniques in PHP

//Listing 3: Encrypting Data Using the mcrypt_ecb Function 

<?php 
echo("<h3> Symmetric Encryption </h3>"); 
$key_value = "KEYVALUE"; 
$plain_text = "PLAINTEXT"; 
$encrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $plain_text, MCRYPT_ENCRYPT); 
echo ("<p><b> Text after encryption : </b>"); 
echo ( $encrypted_text ); 
$decrypted_text = mcrypt_ecb(MCRYPT_DES, $key_value, $encrypted_text, MCRYPT_DECRYPT); 
echo ("<p><b> Text after decryption : </b>"); 
echo ( $decrypted_text ); 
?> 

A few warnings:

1) Never use reversible, or "symmetric" encryption when a one-way hash will do.

2) If the data is truly sensitive, like credit card or social security numbers, stop; you need more than any simple chunk of code will provide, but rather you need a crypto library designed for this purpose and a significant amount of time to research the methods necessary. Further, the software crypto is probably <10% of security of sensitive data. It's like rewiring a nuclear power station - accept that the task is dangerous and difficult and beyond your knowledge if that's the case. The financial penalties can be immense, so better to use a service and ship responsibility to them.

3) Any sort of easily implementable encryption, as listed here, can reasonably protect mildly important information that you want to keep from prying eyes or limit exposure in the case of accidental/intentional leak. But seeing as how the key is stored in plain text on the web server, if they can get the data they can get the decryption key.

Be that as it may, have fun :)

How to restore SQL Server 2014 backup in SQL Server 2008

Please use SQL Server Data Tools from SQL Server Integration Services (Transfer Database Task) as here: https://stackoverflow.com/a/27777823/2127493

How to find Control in TemplateField of GridView?

Try this:

foreach(GridViewRow row in GridView1.Rows) {
    if(row.RowType == DataControlRowType.DataRow) {
        HyperLink myHyperLink = row.FindControl("myHyperLinkID") as HyperLink;
    }
}

If you are handling RowDataBound event, it's like this:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if(e.Row.RowType == DataControlRowType.DataRow)
    {
        HyperLink myHyperLink = e.Row.FindControl("myHyperLinkID") as HyperLink;
    }
}

SQL - Rounding off to 2 decimal places

Could you not cast your result as numeric(x,2)? Where x <= 38

select 
    round(630/60.0,2), 
    cast(round(630/60.0,2) as numeric(36,2))

Returns

10.500000   10.50

In Excel, sum all values in one column in each row where another column is a specific value

If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:

=SUMIF(B:B,"No",A:A)

or

=SUMIFS(A:A,B:B,"No")

Here is an example that will display the amounts paid and outstanding for a small set of sample data.

 A         B            C                   D
 Amount    Reimbursed?  Total Paid:         =SUMIF(B:B,"Yes",A:A)
 $100      Yes          Total Outstanding:  =SUMIF(B:B,"No",A:A)
 $200      No           
 $300      No
 $400      Yes
 $500      No

Result of Excel calculations

Unable to start Genymotion Virtual Device - Virtualbox Host Only Ethernet Adapter Failed to start

Try this one. it works for me. :)

I also disabled Hyper-V to makes mine work.

Genymotion FAQ

To date, VirtualBox is not yet fully compatible with Windows 10. As Genymotion relies on the use of VirtualBox in the background, some problems may arise. If you have any troubles running Genymotion on Windows 10, we first recommend that you put VirtualBox in a clean state. To do so:

  1. Uninstall VirtualBox.Reboot your computer if prompted by the installer.
  2. Install the version of VirtualBox recommended for Windows 10 Reboot your computer if prompted by the installer.
  3. Open VirtualBox and go to File > Preferences > Network.
  4. Remove all existing host-only networks by clicking Description 1.
  5. Start Genymotion a first time.
  6. In the event of a failure, start Genymotion a second time.

If Genymotion still doesn’t run, you can manually configure a host-only network:

  1. Open VirtualBox and go to File > Preferences > Network.
  2. Add a new host-only network by clicking Description 1.
  3. Edit its configuration by clicking Description 1.
  4. In the Adapter tab, set the following values: IPv4 Address: 192.168.56.1 IPv4 Network Mask: 255.255.255.0
  5. In the DHCP Server tab, set the following values: Check Enable Server. Server Address: 192.168.56.100 Server Mask: 255.255.255.0 Lower Address Bound: 192.168.56.101 Upper Address Bound: 192.168.56.254

Set an environment variable in git bash

Creating a .bashrc file in your home directory also works. That way you don't have to copy your .bash_profile every time you install a new version of git bash.

HTML: Is it possible to have a FORM tag in each TABLE ROW in a XHTML valid way?

I'd say you can, although it doesn't validate and Firefox will re-arrange the code (so what you see in 'View generated source' when using Web Developer may well surprise). I'm no expert, but putting

<form action="someexecpage.php" method="post">

just ahead of the

<tr>

and then using

</tr></form>

at the end of the row certainly gives the functionality (tested in Firefox, Chrome and IE7-9). Working for me, even if the number of validation errors it produced was a new personal best/worst! No problems seen as a consequence, and I have a fairly heavily styled table. I guess you may have a dynamically produced table, as I do, which is why parsing the table rows is a bit non-obvious for us mortals. So basically, open the form at the beginning of the row and close it just after the end of the row.

TSQL: How to convert local time to UTC? (SQL Server 2008)

While a few of these answers will get you in the ballpark, you cannot do what you're trying to do with arbitrary dates for SqlServer 2005 and earlier because of daylight savings time. Using the difference between the current local and current UTC will give me the offset as it exists today. I have not found a way to determine what the offset would have been for the date in question.

That said, I know that SqlServer 2008 provides some new date functions that may address that issue, but folks using an earlier version need to be aware of the limitations.

Our approach is to persist UTC and perform the conversion on the client side where we have more control over the conversion's accuracy.

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

Set Background cell color in PHPExcel

function cellColor($cells,$color){
    global $objPHPExcel;

    $objPHPExcel->getActiveSheet()->getStyle($cells)->getFill()->applyFromArray(array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'startcolor' => array(
             'rgb' => $color
        )
    ));
}

cellColor('B5', 'F28A8C');
cellColor('G5', 'F28A8C');
cellColor('A7:I7', 'F28A8C');
cellColor('A17:I17', 'F28A8C');
cellColor('A30:Z30', 'F28A8C');

enter image description here

How to test if string exists in file with Bash?

Easiest and simplest way would be:

isInFile=$(cat file.txt | grep -c "string")


if [ $isInFile -eq 0 ]; then
   #string not contained in file
else
   #string is in file at least once
fi

grep -c will return the count of how many times the string occurs in the file.

How to convert an Array to a Set in Java

private Map<Integer, Set<Integer>> nobreaks = new HashMap();
nobreaks.put(1, new HashSet(Arrays.asList(new int[]{2, 4, 5})));
System.out.println("expected size is 3: " +nobreaks.get(1).size());

the output is

expected size is 3: 1

change it to

nobreaks.put(1, new HashSet(Arrays.asList( 2, 4, 5 )));

the output is

expected size is 3: 3

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

selecting an entire row based on a variable excel vba

One needs to make sure the space between the variables and '&' sign. Check the image. (Red one showing invalid commands)

Error

The correct solution is

Dim copyToRow: copyToRow = 5      
Rows(copyToRow & ":" & copyToRow).Select

How to convert hex to rgb using Java?

The other day I'd been solving the similar issue and found convenient to convert hex color string to int array [alpha, r, g, b]:

 /**
 * Hex color string to int[] array converter
 *
 * @param hexARGB should be color hex string: #AARRGGBB or #RRGGBB
 * @return int[] array: [alpha, r, g, b]
 * @throws IllegalArgumentException
 */

public static int[] hexStringToARGB(String hexARGB) throws IllegalArgumentException {

    if (!hexARGB.startsWith("#") || !(hexARGB.length() == 7 || hexARGB.length() == 9)) {

        throw new IllegalArgumentException("Hex color string is incorrect!");
    }

    int[] intARGB = new int[4];

    if (hexARGB.length() == 9) {
        intARGB[0] = Integer.valueOf(hexARGB.substring(1, 3), 16); // alpha
        intARGB[1] = Integer.valueOf(hexARGB.substring(3, 5), 16); // red
        intARGB[2] = Integer.valueOf(hexARGB.substring(5, 7), 16); // green
        intARGB[3] = Integer.valueOf(hexARGB.substring(7), 16); // blue
    } else hexStringToARGB("#FF" + hexARGB.substring(1));

    return intARGB;
}

Copy struct to struct in C

For simple structures you can either use memcpy like you do, or just assign from one to the other:

RTCclk = RTCclkBuffert;

The compiler will create code to copy the structure for you.


An important note about the copying: It's a shallow copy, just like with memcpy. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.

VBA for clear value in specific range of cell and protected cell from being wash away formula

You could define a macro containing the following code:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.ClearContents
end sub

Running the macro would select the range A5:x50 on the active worksheet and clear all the contents of the cells within that range.

To leave your formulas intact use the following instead:

Sub DeleteA5X50()   
    Range("A5:X50").Select
    Selection.SpecialCells(xlCellTypeConstants, 23).Select
    Selection.ClearContents
end sub

This will first select the overall range of cells you are interested in clearing the contents from and will then further limit the selection to only include cells which contain what excel considers to be 'Constants.'

You can do this manually in excel by selecting the range of cells, hitting 'f5' to bring up the 'Go To' dialog box and then clicking on the 'Special' button and choosing the 'Constants' option and clicking 'Ok'.

Check if a Bash array contains a value

If you need performance, you don't want to loop over your whole array every time you search.

In this case, you can create an associative array (hash table, or dictionary) that represents an index of that array. I.e. it maps each array element into its index in the array:

make_index () {
  local index_name=$1
  shift
  local -a value_array=("$@")
  local i
  # -A means associative array, -g means create a global variable:
  declare -g -A ${index_name}
  for i in "${!value_array[@]}"; do
    eval ${index_name}["${value_array[$i]}"]=$i
  done
}

Then you can use it like this:

myarray=('a a' 'b b' 'c c')
make_index myarray_index "${myarray[@]}"

And test membership like so:

member="b b"
# the "|| echo NOT FOUND" below is needed if you're using "set -e"
test "${myarray_index[$member]}" && echo FOUND || echo NOT FOUND

Or also:

if [ "${myarray_index[$member]}" ]; then 
  echo FOUND
fi

Notice that this solution does the right thing even if the there are spaces in the tested value or in the array values.

As a bonus, you also get the index of the value within the array with:

echo "<< ${myarray_index[$member]} >> is the index of $member"

Eclipse 3.5 Unable to install plugins

I also faced the same problem while working with eclips Neon. It got fixed after editing the .ini file with following content:

>    -Dhttp.proxyPort=8080

>    -Dhttp.proxyHost=myproxy

>    -Dhttp.proxyUser=mydomain\myusername

>    -Dhttp.proxyPassword=mypassword

>    -Dhttp.nonProxyHosts=localhost|127.0.0.1

>    -Djava.net.preferIPv4Stack=true

Note: Sometime it may also caused due to the issue with your Network configuration and device. So conform first that your windows firewall is allowing to connect your eclips to the outer world (internet). (Turn off the windows firewall for the instance of time that your computer take to install the file).

How to add Button over image using CSS?

You need to give relative or absolute or fixed positioning to your container (#shop) and set its zIndex to say 100.

You also need to give say relative positioning to your elements with the class content and lower zIndex say 97.

Do the above-mentioned with your images too and set their zIndex to 91.

And then position your button higher by setting its position to absolute and zIndex to 95

See the DEMO

HTML

<div id="shop">

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

 <div class="content"> Counter-Strike 1.6 Steam 

     <img src="http://www.openvms.org/images/samples/130x130.gif">

         <a href="#"><span class='span'><span></a>

     </div>

  </div>

CSS

#shop{
    background-image: url("images/shop_bg.png");
    background-repeat: repeat-x;    
    height:121px;
    width: 984px;
    margin-left: 20px;
    margin-top: 13px;
    position:relative;
    z-index:100
}

#shop .content{    
    width: 182px; /*328 co je 1/3 - 20margin left*/
    height: 121px;
    line-height: 20px;
    margin-top: 0px;
    margin-left: 9px;
    margin-right:0px;
    display:inline-block;
    position:relative;
    z-index:97

}

img{

    position:relative;
    z-index:91

}

.span{

    width:70px;
    height:40px;
    border:1px solid red;
    position:absolute;
    z-index:95;
    right:60px;
    bottom:-20px;

}

How to detect the screen resolution with JavaScript?

You can also get the WINDOW width and height, avoiding browser toolbars and... (not just screen size).

To do this, use: window.innerWidth and window.innerHeight properties. See it at w3schools.

In most cases it will be the best way, in example, to display a perfectly centred floating modal dialog. It allows you to calculate positions on window, no matter which resolution orientation or window size is using the browser.

Firebase (FCM) how to get token

Settings.Secure.getString(getContentResolver(),
                     Settings.Secure.ANDROID_ID);

How to read string from keyboard using C?

#include<stdio.h>

int main()
{
    char str[100];
    scanf("%[^\n]s",str);
    printf("%s",str);
    return 0;
}

input: read the string
ouput: print the string

This code prints the string with gaps as shown above.

Inject service in app.config

Alex provided the correct reason for not being able to do what you're trying to do, so +1. But you are encountering this issue because you're not quite using resolves how they're designed.

resolve takes either the string of a service or a function returning a value to be injected. Since you're doing the latter, you need to pass in an actual function:

resolve: {
  data: function (dbService) {
    return dbService.getData();
  }
}

When the framework goes to resolve data, it will inject the dbService into the function so you can freely use it. You don't need to inject into the config block at all to accomplish this.

Bon appetit!

How to plot all the columns of a data frame in R

The ggplot2 package takes a little bit of learning, but the results look really nice, you get nice legends, plus many other nice features, all without having to write much code.

require(ggplot2)
require(reshape2)
df <- data.frame(time = 1:10,
                 a = cumsum(rnorm(10)),
                 b = cumsum(rnorm(10)),
                 c = cumsum(rnorm(10)))
df <- melt(df ,  id.vars = 'time', variable.name = 'series')

# plot on same grid, each series colored differently -- 
# good if the series have same scale
ggplot(df, aes(time,value)) + geom_line(aes(colour = series))

# or plot on different plots
ggplot(df, aes(time,value)) + geom_line() + facet_grid(series ~ .)

enter image description here enter image description here

Get index of a row of a pandas dataframe as an integer

The nature of wanting to include the row where A == 5 and all rows upto but not including the row where A == 8 means we will end up using iloc (loc includes both ends of slice).

In order to get the index labels we use idxmax. This will return the first position of the maximum value. I run this on a boolean series where A == 5 (then when A == 8) which returns the index value of when A == 5 first happens (same thing for A == 8).

Then I use searchsorted to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc.

i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]

enter image description here


numpy

you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.

def find_between(df, col, v1, v2):
    vals = df[col].values
    mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
    idx = df.index.values
    i1, i2 = idx.searchsorted([mx1, mx2])
    return df.iloc[i1:i2]

find_between(df, 'A', 5, 8)

enter image description here


timing
enter image description here

Fast way to get the min/max values among properties of object

// Sorted
let Sorted = Object.entries({ "a":4, "b":0.5 , "c":0.35, "d":5 }).sort((prev, next) => prev[1] - next[1])
>> [ [ 'c', 0.35 ], [ 'b', 0.5 ], [ 'a', 4 ], [ 'd', 5 ] ]


//Min:
Sorted.shift()
>> [ 'c', 0.35 ]

// Max:
Sorted.pop()
>> [ 'd', 5 ]

PHPMailer AddAddress()

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddAddress($email, $name);
}

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Disable future dates after today in Jquery Ui Datepicker

In my case, I have given this attribute to the input tag

data-date-start-date="0d" data-date-end-date="0d"

Javascript seconds to minutes and seconds

strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.

When creating a new Date, each optional argument is positional as follows:

new Date(year, month, day, hours, minutes, seconds, milliseconds);

So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:

var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)

You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.

var mm_ss_str = strftime("%M:%S", date);
=> "02:30"

In one line, it would look like:

var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"

Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:

# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"

# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"

And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.

var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"

Hope this helps.

How to open a link in new tab (chrome) using Selenium WebDriver?

I checked with below code and it works fine for me. I found answer from here.

    driver = new ChromeDriver();
    driver.manage().window().maximize();
            
    String baseUrl = "http://www.google.co.uk/";
    driver.get(baseUrl);
    driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

    ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1)); //switches to new tab
    driver.get("https://www.facebook.com");
    
    driver.switchTo().window(tabs.get(0)); // switch back to main screen        
    driver.get("https://www.news.google.com");

What does ':' (colon) do in JavaScript?

var o = {
    r: 'some value',
    t: 'some other value'
};

is functionally equivalent to

var o = new Object();
o.r = 'some value';
o.t = 'some other value';

Project with path ':mypath' could not be found in root project 'myproject'

It's not enough to have just compile project("xy") dependency. You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).

Create a settings.gradle file in the root of your project and add this:

include ':progressfragment'

to that file. Then sync Gradle and it should work.

Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.

Take a char input from the Scanner

import java.util.Scanner;

public class Test { 
    public static void main(String[] args) {
 
        Scanner reader = new Scanner(System.in);
        char c = reader.next(".").charAt(0);

    }
}

To get only one character char c = reader.next(".").charAt(0);

Finding diff between current and last version

Difference between last but one commit and last commit (plus current state, if any):

git diff HEAD~

or even (easier to type)

git diff @~

where @ is the synonim for HEAD of current branch and ~ means "give me the parent of mentioned revision".

How to create a DataFrame from a text file in Spark

You can read a file to have an RDD and then assign schema to it. Two common ways to creating schema are either using a case class or a Schema object [my preferred one]. Follows the quick snippets of code that you may use.

Case Class approach

case class Test(id:String,name:String)
val myFile = sc.textFile("file.txt")
val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

Schema Approach

import org.apache.spark.sql.types._
val schemaString = "id name"
val fields = schemaString.split(" ").map(fieldName => StructField(fieldName, StringType, nullable=true))
val schema = StructType(fields)

val dfWithSchema = sparkSess.read.option("header","false").schema(schema).csv("file.txt")
dfWithSchema.show()

The second one is my preferred approach since case class has a limitation of max 22 fields and this will be a problem if your file has more than 22 fields!

How to show google.com in an iframe?

The reason for this is, that Google is sending an "X-Frame-Options: SAMEORIGIN" response header. This option prevents the browser from displaying iFrames that are not hosted on the same domain as the parent page.

See: Mozilla Developer Network - The X-Frame-Options response header

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

Even though utf8_decode is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace on the field on the table. To correct the bad encoded characters from OP :

update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")

Where <table> is the name of the mysql table and <field> is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.

Remember to backup your table before trying to replace any characters with SQL!

[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]

How can multiple rows be concatenated into one in Oracle without creating a stored procedure?

Easy:

SELECT question_id, wm_concat(element_id) as elements
FROM   questions
GROUP BY question_id;

Pesonally tested on 10g ;-)

From http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php

How to combine multiple inline style objects?

Object.assign() is an easy solution, but the (currently) top answer's usage of it — while just fine for making stateless components, will cause problems for the OP's desired objective of merging two state objects.

With two arguments, Object.assign() will actually mutate the first object in-place, affecting future instantiations.

Ex:

Consider two possible style configs for a box:

var styles =  {
  box: {backgroundColor: 'yellow', height: '100px', width: '200px'},
  boxA: {backgroundColor: 'blue'},
};

So we want all our boxes to have default 'box' styles, but want to overwrite some with a different color:

// this will be yellow
<div style={styles.box}></div>

// this will be blue
<div style={Object.assign(styles.box, styles.boxA)}></div>

// this SHOULD be yellow, but it's blue.
<div style={styles.box}></div>

Once Object.assign() executes, the 'styles.box' object is changed for good.

The solution is to pass an empty object to Object.assign(). In so doing, you're telling the method to produce a NEW object with the objects you pass it. Like so:

// this will be yellow
<div style={styles.box}></div>

// this will be blue
<div style={Object.assign({}, styles.box, styles.boxA)}></div>

// a beautiful yellow
<div style={styles.box}></div>

This notion of objects mutating in-place is critical for React, and proper use of Object.assign() is really helpful for using libraries like Redux.

What to put in a python module docstring?

Think about somebody doing help(yourmodule) at the interactive interpreter's prompt — what do they want to know? (Other methods of extracting and displaying the information are roughly equivalent to help in terms of amount of information). So if you have in x.py:

"""This module does blah blah."""

class Blah(object):
  """This class does blah blah."""

then:

>>> import x; help(x)

shows:

Help on module x:

NAME
    x - This module does blah blah.

FILE
    /tmp/x.py

CLASSES
    __builtin__.object
        Blah

    class Blah(__builtin__.object)
     |  This class does blah blah.
     |  
     |  Data and other attributes defined here:
     |  
     |  __dict__ = <dictproxy object>
     |      dictionary for instance variables (if defined)
     |  
     |  __weakref__ = <attribute '__weakref__' of 'Blah' objects>
     |      list of weak references to the object (if defined)

As you see, the detailed information on the classes (and functions too, though I'm not showing one here) is already included from those components' docstrings; the module's own docstring should describe them very summarily (if at all) and rather concentrate on a concise summary of what the module as a whole can do for you, ideally with some doctested examples (just like functions and classes ideally should have doctested examples in their docstrings).

I don't see how metadata such as author name and copyright / license helps the module's user — it can rather go in comments, since it could help somebody considering whether or not to reuse or modify the module.

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

Java Long primitive type maximum limit

Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

It will start from -9,223,372,036,854,775,808

Long.MIN_VALUE.

When to use LinkedList over ArrayList in Java?

Algorithm           ArrayList   LinkedList
seek front            O(1)         O(1)
seek back             O(1)         O(1)
seek to index         O(1)         O(N)
insert at front       O(N)         O(1)
insert at back        O(1)         O(1)
insert after an item  O(N)         O(1)

Algorithms: Big-Oh Notation (archived)

ArrayLists are good for write-once-read-many or appenders, but bad at add/remove from the front or middle.

How to tell Jackson to ignore a field during serialization if its value is null?

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String bar;
}

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

A more complete example is available in my answer to How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson.

Where can I find Android source code online?

Everything is mirrored on omapzoom.org. Some of the code is also mirrored on github.

Contacts is here for example.

Since December 2019, you can use the new official public code search tool for AOSP: cs.android.com. There's also the Android official source browser (based on Gitiles) has a web view of many of the different parts that make up android. Some of the projects (such as Kernel) have been removed and it now only points you to clonable git repositories.

To get all the code locally, you can use the repo helper program, or you can just clone individual repositories.

And others:

How do I call a function inside of another function?

_x000D_
_x000D_
function function_one() {_x000D_
    function_two(); // considering the next alert, I figured you wanted to call function_two first_x000D_
    alert("The function called 'function_one' has been called.");_x000D_
}_x000D_
_x000D_
function function_two() {_x000D_
    alert("The function called 'function_two' has been called.");_x000D_
}_x000D_
_x000D_
function_one();
_x000D_
_x000D_
_x000D_

A little bit more context: this works in JavaScript because of a language feature called "variable hoisting" - basically, think of it like variable/function declarations are put at the top of the scope (more info).

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

Finding duplicate integers in an array and display how many times they occurred

static void printRepeating(int []arr, int size) { int i;

    Console.Write("The repeating" +  
                   " elements are : "); 

    for (i = 0; i < size; i++) 
    { 
        if (arr[ Math.Abs(arr[i])] >= 0) 
            arr[ Math.Abs(arr[i])] = 
                -arr[ Math.Abs(arr[i])]; 
        else
            Console.Write(Math.Abs(arr[i]) + " "); 
    }          
}  

justify-content property isn't working

I had a further issue that foxed me for a while when theming existing code from a CMS. I wanted to use flexbox with justify-content:space-between but the left and right elements weren't flush.

In that system the items were floated and the container had a :before and/or an :after to clear floats at beginning or end. So setting those sneaky :before and :after elements to display:none did the trick.

Find records with a date field in the last 24 hours

SELECT * FROM news WHERE date > DATEADD(d,-1,GETDATE())

Get last 5 characters in a string

str.Substring(str.Length - 5)

Tokenizing strings in C

Here's an example of strtok usage, keep in mind that strtok is destructive of its input string (and therefore can't ever be used on a string constant

char *p = strtok(str, " ");
while(p != NULL) {
    printf("%s\n", p);
    p = strtok(NULL, " ");
}

Basically the thing to note is that passing a NULL as the first parameter to strtok tells it to get the next token from the string it was previously tokenizing.

Can I calculate z-score with R?

if x is a vector with raw scores then scale(x) is a vector with standardized scores.

Or manually: (x-mean(x))/sd(x)

Swift add icon/image in UITextField

for Swift 3.0 add image on leftside of textField

textField.leftView = UIImageView(image: "small-calendar")
textField.leftView?.frame = CGRect(x: 0, y: 5, width: 20 , height:20)
textField.leftViewMode = .always

jQuery form input select by id

For example like this:

var value = $("#a").find("#b").val()

Cloning an Object in Node.js

You can also use this clone library to deep clone objects.

 npm install --save clone
const clone = require('clone');

const clonedObject = clone(sourceObject);

Hosting a Maven repository on github

You can use JitPack (free for public Git repositories) to expose your GitHub repository as a Maven artifact. Its very easy. Your users would need to add this to their pom.xml:

  1. Add repository:
<repository>
    <id>jitpack.io</id>
    <url>https://jitpack.io</url>
</repository>
  1. Add dependency:
<dependency>
    <groupId>com.github.User</groupId>
    <artifactId>Repo name</artifactId>
    <version>Release tag</version>
</dependency>

As answered elsewhere the idea is that JitPack will build your GitHub repo and will serve the jars. The requirement is that you have a build file and a GitHub release.

The nice thing is that you don't have to handle deployment and uploads. Since you didn't want to maintain your own artifact repository its a good match for your needs.

VBA code to set date format for a specific column as "yyyy-mm-dd"

Use the range's NumberFormat property to force the format of the range like this:

Sheet1.Range("A2", "A50000").NumberFormat = "yyyy-mm-dd"

Calculate difference between two dates (number of days)?

First declare a class that will return later:

public void date()
{
    Datetime startdate;
    Datetime enddate;
    Timespan remaindate;

    startdate = DateTime.Parse(txtstartdate.Text).Date;
    enddate = DateTime.Parse(txtenddate.Text).Date;

    remaindate = enddate - startdate;

    if (remaindate != null)
    {
        lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
    }
    else
    {
        lblmsg.Text = "correct your code again.";
    }
}

protected void btncal_Click(object sender, EventArgs e)
{
    date();
}

Use a button control to call the above class. Here is an example:

Conversion failed when converting from a character string to uniqueidentifier

this fails:

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

this works

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

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

How to apply a function to two columns of Pandas dataframe

Here's an example using apply on the dataframe, which I am calling with axis = 1.

Note the difference is that instead of trying to pass two values to the function f, rewrite the function to accept a pandas Series object, and then index the Series to get the values needed.

In [49]: df
Out[49]: 
          0         1
0  1.000000  0.000000
1 -0.494375  0.570994
2  1.000000  0.000000
3  1.876360 -0.229738
4  1.000000  0.000000

In [50]: def f(x):    
   ....:  return x[0] + x[1]  
   ....:  

In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]: 
0    1.000000
1    0.076619
2    1.000000
3    1.646622
4    1.000000

Depending on your use case, it is sometimes helpful to create a pandas group object, and then use apply on the group.

GROUP_CONCAT ORDER BY

The group_concat supports its own order by clause

http://mahmudahsan.wordpress.com/2008/08/27/mysql-the-group_concat-function/

So you should be able to write:

SELECT li.clientid, group_concat(li.views order by views) AS views,
group_concat(li.percentage order by percentage) 
FROM table_views GROUP BY client_id

Callback when CSS3 transition finishes

For anyone that this might be handy for, here is a jQuery dependent function I had success with for applying a CSS animation via a CSS class, then getting a callback from afterwards. It may not work perfectly since I had it being used in a Backbone.js App, but maybe useful.

var cssAnimate = function(cssClass, callback) {
    var self = this;

    // Checks if correct animation has ended
    var setAnimationListener = function() {
        self.one(
            "webkitAnimationEnd oanimationend msAnimationEnd animationend",
            function(e) {
                if(
                    e.originalEvent.animationName == cssClass &&
                    e.target === e.currentTarget
                ) {
                    callback();
                } else {
                    setAnimationListener();
                }
            }
        );
    }

    self.addClass(cssClass);
    setAnimationListener();
}

I used it kinda like this

cssAnimate.call($("#something"), "fadeIn", function() {
    console.log("Animation is complete");
    // Remove animation class name?
});

Original idea from http://mikefowler.me/2013/11/18/page-transitions-in-backbone/

And this seems handy: http://api.jqueryui.com/addClass/


Update

After struggling with the above code and other options, I would suggest being very cautious with any listening for CSS animation ends. With multiple animations going on, this can get messy very fast for event listening. I would strongly suggest an animation library like GSAP for every animation, even the small ones.

How do you find out the type of an object (in Swift)?

If you simply need to check whether the variable is of type X, or that it conforms to some protocol, then you can use is, or as? as in the following:

var unknownTypeVariable = …

if unknownTypeVariable is <ClassName> {
    //the variable is of type <ClassName>
} else {
    //variable is not of type <ClassName>
}

This is equivalent of isKindOfClass in Obj-C.

And this is equivalent of conformsToProtocol, or isMemberOfClass

var unknownTypeVariable = …

if let myClass = unknownTypeVariable as? <ClassName or ProtocolName> {
    //unknownTypeVarible is of type <ClassName or ProtocolName>
} else {
    //unknownTypeVariable is not of type <ClassName or ProtocolName>
}

Check if a value exists in pandas dataframe index

df = pandas.DataFrame({'g':[1]}, index=['isStop'])

#df.loc['g']

if 'g' in df.index:
    print("find g")

if 'isStop' in df.index:
    print("find a") 

How to pretty print XML from Java?

Hmmm... faced something like this and it is a known bug ... just add this OutputProperty ..

transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT, "8");

Hope this helps ...

select records from postgres where timestamp is in certain range

Another option to make PostgreSQL use an index for your original query, is to create an index on the expression you are using:

create index arrival_year on reservations ( extract(year from arrival) );

That will open PostgreSQL with the possibility to use an index for

select * 
FROM reservations 
WHERE extract(year from arrival) = 2012;

Note that the expression in the index must be exactly the same expression as used in the where clause to make this work.

Passing arguments to C# generic new() of templated type

Object initializer

If your constructor with the parameter isn't doing anything besides setting a property, you can do this in C# 3 or better using an object initializer rather than calling a constructor (which is impossible, as has been mentioned):

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
       tabListItems.Add(new T() { YourPropertyName = listItem } ); // Now using object initializer
   } 
   ...
}

Using this, you can always put any constructor logic in the default (empty) constructor, too.

Activator.CreateInstance()

Alternatively, you could call Activator.CreateInstance() like so:

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
        object[] args = new object[] { listItem };
        tabListItems.Add((T)Activator.CreateInstance(typeof(T), args)); // Now using Activator.CreateInstance
   } 
   ...
}

Note that Activator.CreateInstance can have some performance overhead that you may want to avoid if execution speed is a top priority and another option is maintainable to you.

Configuring user and password with Git Bash

If the git bash is not working properly due to recently changed password.

You could open the Git GUI, and clone from there. It will ask for password, once entered, you can close the GIT GUI window.

Now the git bash will work perfectly.

Saving binary data as file using JavaScript from a browser

To do this task download.js library can be used. Here is an example from library docs:

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

No String-argument constructor/factory method to deserialize from String value ('')

Try setting mapper.configure(DeserializationConfig.Feature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)

or

mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

depending on your Jackson version.

Scroll to bottom of div with Vue.js

I tried the accepted solution and it didn't work for me. I use the browser debugger and found out the actual height that should be used is the clientHeight BUT you have to put this into the updated() hook for the whole solution to work.

data(){
return {
  conversation: [
    {
    }
  ]
 },
mounted(){
 EventBus.$on('msg-ctr--push-msg-in-conversation', textMsg => {
  this.conversation.push(textMsg)
  // Didn't work doing scroll here
 })
},
updated(){              <=== PUT IT HERE !!
  var elem = this.$el
  elem.scrollTop = elem.clientHeight;
},

How to convert Calendar to java.sql.Date in Java?

stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));

Form Validation With Bootstrap (jQuery)

Check this library, it's completable with booth bootstrap 3 and bootstrap 4

jQuery

<form>
    <div class="form-group">
        <input class="form-control" data-validator="required|min:4|max:10">
    </div>
</form>

Javascript

$(document).on('blur', '[data-validator]', function () {
    new Validator($(this));
});

How to convert SecureString to System.String?

I derived from This answer by sclarke81. I like his answer and I'm using the derivative but sclarke81's has a bug. I don't have reputation so I can't comment. The problem seems small enough that it didn't warrant another answer and I could edit it. So I did. It got rejected. So now we have another answer.

sclarke81 I hope you see this (in finally):

Marshal.Copy(new byte[length], 0, insecureStringPointer, length);

should be:

Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);

And the full answer with the bug fix:


    /// 
    /// Allows a decrypted secure string to be used whilst minimising the exposure of the
    /// unencrypted string.
    /// 
    /// Generic type returned by Func delegate.
    /// The string to decrypt.
    /// 
    /// Func delegate which will receive the decrypted password as a string object
    /// 
    /// Result of Func delegate
    /// 
    /// This method creates an empty managed string and pins it so that the garbage collector
    /// cannot move it around and create copies. An unmanaged copy of the the secure string is
    /// then created and copied into the managed string. The action is then called using the
    /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
    /// contents. The managed string is unpinned so that the garbage collector can resume normal
    /// behaviour and the unmanaged string is freed.
    /// 
    public static T UseDecryptedSecureString(this SecureString secureString, Func action)
    {
        int length = secureString.Length;
        IntPtr sourceStringPointer = IntPtr.Zero;

        // Create an empty string of the correct size and pin it so that the GC can't move it around.
        string insecureString = new string('\0', length);
        var insecureStringHandler = GCHandle.Alloc(insecureString, GCHandleType.Pinned);

        IntPtr insecureStringPointer = insecureStringHandler.AddrOfPinnedObject();

        try
        {
            // Create an unmanaged copy of the secure string.
            sourceStringPointer = Marshal.SecureStringToBSTR(secureString);

            // Use the pointers to copy from the unmanaged to managed string.
            for (int i = 0; i < secureString.Length; i++)
            {
                short unicodeChar = Marshal.ReadInt16(sourceStringPointer, i * 2);
                Marshal.WriteInt16(insecureStringPointer, i * 2, unicodeChar);
            }

            return action(insecureString);
        }
        finally
        {
            // Zero the managed string so that the string is erased. Then unpin it to allow the
            // GC to take over.
            Marshal.Copy(new byte[length * 2], 0, insecureStringPointer, length * 2);
            insecureStringHandler.Free();

            // Zero and free the unmanaged string.
            Marshal.ZeroFreeBSTR(sourceStringPointer);
        }
    }

    /// 
    /// Allows a decrypted secure string to be used whilst minimising the exposure of the
    /// unencrypted string.
    /// 
    /// The string to decrypt.
    /// 
    /// Func delegate which will receive the decrypted password as a string object
    /// 
    /// Result of Func delegate
    /// 
    /// This method creates an empty managed string and pins it so that the garbage collector
    /// cannot move it around and create copies. An unmanaged copy of the the secure string is
    /// then created and copied into the managed string. The action is then called using the
    /// managed string. Both the managed and unmanaged strings are then zeroed to erase their
    /// contents. The managed string is unpinned so that the garbage collector can resume normal
    /// behaviour and the unmanaged string is freed.
    /// 
    public static void UseDecryptedSecureString(this SecureString secureString, Action action)
    {
        UseDecryptedSecureString(secureString, (s) =>
        {
            action(s);
            return 0;
        });
    }
}

How can I show an image using the ImageView component in javafx and fxml?

If you want to use FXML, you should separate the controller (like you were doing with the SampleController). Then your fx:controller in your FXML should point to that.

Probably you are missing the initialize method in your controller, which is part of the Initializable interface. This method is called after the FXML is loaded, so I recommend you to set your image there.

Your SampleController class must be something like this:

public class SampleController implements Initializable {

    @FXML
    private ImageView imageView;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        File file = new File("src/Box13.jpg");
        Image image = new Image(file.toURI().toString());
        imageView.setImage(image);
    }
}

I tested here and it's working.

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

How to get HttpClient to pass credentials along with the request?

You can configure HttpClient to automatically pass credentials like this:

var myClient = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true });

When does Java's Thread.sleep throw InterruptedException?

The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException. It's well worth reading and digesting.

Run batch file as a Windows service

NSSM is totally free and hyper-easy, running command prompt / terminal as administrator:

nssm install "YourCoolServiceNameLabel"

then a dialog will appear so you can choose where is the file you want to run.

to uninstall

nssm remove "YourCoolServiceNameLabel"

Can a class member function template be virtual?

My current solution is the following (with RTTI disabled - you could use std::type_index, too):

#include <type_traits>
#include <iostream>
#include <tuple>

class Type
{
};

template<typename T>
class TypeImpl : public Type
{

};

template<typename T>
inline Type* typeOf() {
    static Type* typePtr = new TypeImpl<T>();
    return typePtr;
}

/* ------------- */

template<
    typename Calling
    , typename Result = void
    , typename From
    , typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action);

template<typename Cls>
class ChildClasses
{
public:
    using type = std::tuple<>;
};

template<typename... Childs>
class ChildClassesHelper
{
public:
    using type = std::tuple<Childs...>;
};

//--------------------------

class A;
class B;
class C;
class D;

template<>
class ChildClasses<A> : public ChildClassesHelper<B, C, D> {};

template<>
class ChildClasses<B> : public ChildClassesHelper<C, D> {};

template<>
class ChildClasses<C> : public ChildClassesHelper<D> {};

//-------------------------------------------

class A
{
public:
    virtual Type* GetType()
    {
        return typeOf<A>();
    }

    template<
        typename T,
        bool checkType = true
    >
        /*virtual*/void DoVirtualGeneric()
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<A>(this, [&](auto* other) -> decltype(auto)
                {
                    return other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "A";
    }
};

class B : public A
{
public:
    virtual Type* GetType()
    {
        return typeOf<B>();
    }
    template<
        typename T,
        bool checkType = true
    >
    /*virtual*/void DoVirtualGeneric() /*override*/
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<B>(this, [&](auto* other) -> decltype(auto)
                {
                    other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "B";
    }
};

class C : public B
{
public:
    virtual Type* GetType() {
        return typeOf<C>();
    }

    template<
        typename T,
        bool checkType = true
    >
    /*virtual*/void DoVirtualGeneric() /*override*/
    {
        if constexpr (checkType)
        {
            return DoComplexDispatch<C>(this, [&](auto* other) -> decltype(auto)
                {
                    other->template DoVirtualGeneric<T, false>();
                });
        }
        std::cout << "C";
    }
};

class D : public C
{
public:
    virtual Type* GetType() {
        return typeOf<D>();
    }
};

int main()
{
    A* a = new A();
    a->DoVirtualGeneric<int>();
}

// --------------------------

template<typename Tuple>
class RestTuple {};

template<
    template<typename...> typename Tuple,
    typename First,
    typename... Rest
>
class RestTuple<Tuple<First, Rest...>> {
public:
    using type = Tuple<Rest...>;
};

// -------------
template<
    typename CandidatesTuple
    , typename Result
    , typename From
    , typename Action
>
inline constexpr Result DoComplexDispatchInternal(From* from, Action&& action, Type* fromType)
{
    using FirstCandidate = std::tuple_element_t<0, CandidatesTuple>;

    if constexpr (std::tuple_size_v<CandidatesTuple> == 1)
    {
        return action(static_cast<FirstCandidate*>(from));
    }
    else {
        if (fromType == typeOf<FirstCandidate>())
        {
            return action(static_cast<FirstCandidate*>(from));
        }
        else {
            return DoComplexDispatchInternal<typename RestTuple<CandidatesTuple>::type, Result>(
                from, action, fromType
            );
        }
    }
}

template<
    typename Calling
    , typename Result
    , typename From
    , typename Action
>
inline Result DoComplexDispatch(From* from, Action&& action)
{
    using ChildsOfCalling = typename ChildClasses<Calling>::type;
    if constexpr (std::tuple_size_v<ChildsOfCalling> == 0)
    {
        return action(static_cast<Calling*>(from));
    }
    else {
        auto fromType = from->GetType();
        using Candidates = decltype(std::tuple_cat(std::declval<std::tuple<Calling>>(), std::declval<ChildsOfCalling>()));
        return DoComplexDispatchInternal<Candidates, Result>(
            from, std::forward<Action>(action), fromType
        );
    }
}

The only thing I don't like is that you have to define/register all child classes.

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

Convert hours:minutes:seconds into total minutes in excel

The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:

=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60

enter image description here

How do I kill a VMware virtual machine that won't die?

If you are using Windows, the virtual machine should have it's own process that is visible in task manager. Use sysinternals Process Explorer to find the right one and then kill it from there.

Can I use git diff on untracked files?

usually when i work with remote location teams it is important for me that i have prior knowledge what change done by other teams in same file, before i follow git stages untrack-->staged-->commit for that i wrote an bash script which help me to avoid unnecessary resolve merge conflict with remote team or make new local branch and compare and merge on main branch

#set -x 
branchname=`git branch | grep -F '*' |  awk '{print $2}'`
echo $branchname
git fetch origin ${branchname}
for file in `git status | grep "modified" | awk "{print $2}" `
do
echo "PLEASE CHECK OUT GIT DIFF FOR "$file 
git difftool FETCH_HEAD $file ;
done

in above script i fetch remote main branch (not necessary its master branch)to FETCH_HEAD them make a list of my modified file only and compare modified files to git difftool

here many difftool supported by git, i configure 'Meld Diff Viewer' for good GUI comparison .

Call asynchronous method in constructor?

A quick way to execute some time-consuming operation in any constructor is by creating an action and run them asynchronously.

new Action( async() => await InitializeThingsAsync())();

Running this piece of code will neither block your UI nor leave you with any loose threads. And if you need to update any UI (considering you are not using MVVM approach), you can use the Dispatcher to do so as many have suggested.

A Note: This option only provides you a way to start an execution of a method from the constructor if you don't have any init or onload or navigated overrides. Most likely this will keep on running even after the construction has been completed. Hence the result of this method call may NOT be available in the constructor itself.

How to document Python code using Doxygen

An other very good documentation tool is sphinx. It will be used for the upcoming python 2.6 documentation and is used by django and a lot of other python projects.

From the sphinx website:

  • Output formats: HTML (including Windows HTML Help) and LaTeX, for printable PDF versions
  • Extensive cross-references: semantic markup and automatic links for functions, classes, glossary terms and similar pieces of information
  • Hierarchical structure: easy definition of a document tree, with automatic links to siblings, parents and children
  • Automatic indices: general index as well as a module index
  • Code handling: automatic highlighting using the Pygments highlighter
  • Extensions: automatic testing of code snippets, inclusion of docstrings from Python modules, and more

How do I return a proper success/error message for JQuery .ajax() using PHP?

...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.

Typically, right mouse->inspect on your html page. Then look in the error console for errors like

Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Retrieve a single file from a repository

For single file, just use wget command.

First, follow the pic below to click "raw" to get the url, otherwise you will download code embedded in html. enter image description here

Then, the browser will open a new page with url start with https://raw.githubusercontent.com/...

just enter the command in the terminal:

#wget https://raw.githubusercontent.com/...

A while the file will put in your folder.

Git Cherry-pick vs Merge Workflow

Both rebase (and cherry-pick) and merge have their advantages and disadvantages. I argue for merge here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase is preferred.)

merge is preferred over cherry-pick and rebase for a couple of reasons.

  1. Robustness. The SHA1 identifier of a commit identifies it not just in and of itself but also in relation to all other commits that precede it. This offers you a guarantee that the state of the repository at a given SHA1 is identical across all clones. There is (in theory) no chance that someone has done what looks like the same change but is actually corrupting or hijacking your repository. You can cherry-pick in individual changes and they are likely the same, but you have no guarantee. (As a minor secondary issue the new cherry-picked commits will take up extra space if someone else cherry-picks in the same commit again, as they will both be present in the history even if your working copies end up being identical.)
  2. Ease of use. People tend to understand the merge workflow fairly easily. rebase tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.

Even with a merge-heavy workflow rebase and cherry-pick are still useful for particular cases:

  1. One downside to merge is cluttered history. rebase prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase code that you have shared with other repositories. Once a commit is pushed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.
  2. cherry-pick is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.

As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

I stumbled across the issue now, too. The application defined a pure virtual interface class and a user-defined class provided through a shared lib was supposed to implement the interface. When linking the application, the linker complained that the shared lib would not provide vtable and type_info for the base class, nor could they be found anywhere else. Turned out that I simply forgot to make one of the interface's methods pure virtual (i.e. omitted the " = 0" at the end of the declaration. Very rudimentary, still easy to overlook and puzzling if you can't connect the linker diagnostic to the root cause.

Visual Studio Expand/Collapse keyboard shortcuts

Collapse to definitions

CTRL + M, O

Expand all outlining

CTRL + M, X

Expand or collapse everything

CTRL + M, L

This also works with other languages like TypeScript and JavaScript

How using try catch for exception handling is best practice

I can tell you something:

Snippet #1 is not acceptable because it's ignoring exception. (it's swallowing it like nothing happened).

So do not add catch block that do nothing or just rethrows.

Catch block should add some value. For example output message to end user or log error.

Do not use exception for normal flow program logic. For example:

e.g input validation. <- This is not valid exceptional situation, rather you should write method IsValid(myInput); to check whether input item is valid or not.

Design code to avoid exception. For example:

int Parse(string input);

If we pass value that cannot be parsed to int, this method would throw and exception, instead of that we might write something like this:

bool TryParse(string input,out int result); <- this method would return boolean indicating if parse was successfull.

Maybe this is little bit out of scope of this question, but I hope this will help you to make right decisions when it's about try {} catch(){} and exceptions.

Select first 10 distinct rows in mysql

Try this SELECT DISTINCT 10 * ...

Is it possible to have empty RequestParam values use the defaultValue?

This was considered a bug in 2013: https://jira.spring.io/browse/SPR-10180

and was fixed with version 3.2.2. Problem shouldn't occur in any versions after that and your code should work just fine.

Bootstrap: wider input field

Use the bootstrap built in classes input-large, input-medium, ... : <input type="text" class="input-large search-query">

Or use your own css:

  1. Give the element a unique classname class="search-query input-mysize"
  2. Add this in your css file (not the bootstrap.less or css files):
    .input-mysize { width: 150px }

How to check if an array is empty?

you may use yourArray.length to findout number of elements in an array.

Make sure yourArray is not null before doing yourArray.length, otherwise you will end up with NullPointerException.

How to pass multiple values to single parameter in stored procedure

USE THIS

I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.

http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/

I hope this helps people because it was exactly what I was looking for

What are the differences between json and simplejson Python modules?

All of these answers aren't very helpful because they are time sensitive.

After doing some research of my own I found that simplejson is indeed faster than the builtin, if you keep it updated to the latest version.

pip/easy_install wanted to install 2.3.2 on ubuntu 12.04, but after finding out the latest simplejson version is actually 3.3.0, so I updated it and reran the time tests.

  • simplejson is about 3x faster than the builtin json at loads
  • simplejson is about 30% faster than the builtin json at dumps

Disclaimer:

The above statements are in python-2.7.3 and simplejson 3.3.0 (with c speedups) And to make sure my answer also isn't time sensitive, you should run your own tests to check since it varies so much between versions; there's no easy answer that isn't time sensitive.

How to tell if C speedups are enabled in simplejson:

import simplejson
# If this is True, then c speedups are enabled.
print bool(getattr(simplejson, '_speedups', False))

UPDATE: I recently came across a library called ujson that is performing ~3x faster than simplejson with some basic tests.

What is the difference between IQueryable<T> and IEnumerable<T>?

The primary difference is that the LINQ operators for IQueryable<T> take Expression objects instead of delegates, meaning the custom query logic it receives, e.g., a predicate or value selector, is in the form of an expression tree instead of a delegate to a method.

  • IEnumerable<T> is great for working with sequences that are iterated in-memory, but
  • IQueryable<T> allows for out-of memory things like a remote data source, such as a database or web service.

Query execution:

  • Where the execution of a query is going to be performed "in process", typically all that's required is the code (as code) to execute each part of the query.

  • Where the execution will be performed out-of-process, the logic of the query has to be represented in data such that the LINQ provider can convert it into the appropriate form for the out-of-memory execution - whether that's an LDAP query, SQL or whatever.

More in:

http://www.codeproject.com/KB/cs/646361/WhatHowWhere.jpg

What's the difference between INNER JOIN, LEFT JOIN, RIGHT JOIN and FULL JOIN?

INNER JOIN gets all records that are common between both tables based on the supplied ON clause.

LEFT JOIN gets all records from the LEFT linked and the related record from the right table ,but if you have selected some columns from the RIGHT table, if there is no related records, these columns will contain NULL.

RIGHT JOIN is like the above but gets all records in the RIGHT table.

FULL JOIN gets all records from both tables and puts NULL in the columns where related records do not exist in the opposite table.

Fix CSS hover on iPhone/iPad/iPod

Where, I solved this problem by adding the visibility attribute to the CSS code, it works on my website

Original code:

_x000D_
_x000D_
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
_x000D_
_x000D_

Fixed iOS touch code:

_x000D_
_x000D_
#zo2-body-wrap .introText .images:before_x000D_
{_x000D_
background:rgba(136,136,136,0.7);_x000D_
width:100%;_x000D_
height:100%;_x000D_
content:"";_x000D_
position:absolute;_x000D_
top:0;_x000D_
visibility:hidden;_x000D_
opacity:0;_x000D_
transition:all 0.2s ease-in-out 0s;_x000D_
}
_x000D_
_x000D_
_x000D_

Resolve promises one after another (i.e. in sequence)?

My answer based on https://stackoverflow.com/a/31070150/7542429.

Promise.series = function series(arrayOfPromises) {
    var results = [];
    return arrayOfPromises.reduce(function(seriesPromise, promise) {
      return seriesPromise.then(function() {
        return promise
        .then(function(result) {
          results.push(result);
        });
      });
    }, Promise.resolve())
    .then(function() {
      return results;
    });
  };

This solution returns the results as an array like Promise.all().

Usage:

Promise.series([array of promises])
.then(function(results) { 
  // do stuff with results here
});

error: request for member '..' in '..' which is of non-class type

I ran into a case where I got that error message and had

Foo foo(Bar());

and was basically trying to pass in a temporary Bar object to the Foo constructor. Turns out the compiler was translating this to

Foo foo(Bar(*)());

that is, a function declaration whose name is foo that returns a Foo that takes in an argument -- a function pointer returning a Bar with 0 arguments. When passing in temporaries like this, better to use Bar{} instead of Bar() to eliminate ambiguity.

Best way to combine two or more byte arrays in C#

All you need to pass list of Byte Arrays and this function will return you the Array of Bytes (Merged). This is the best solution i think :).

public static byte[] CombineMultipleByteArrays(List<byte[]> lstByteArray)
        {
            using (var ms = new MemoryStream())
            {
                using (var doc = new iTextSharp.text.Document())
                {
                    using (var copy = new PdfSmartCopy(doc, ms))
                    {
                        doc.Open();
                        foreach (var p in lstByteArray)
                        {
                            using (var reader = new PdfReader(p))
                            {
                                copy.AddDocument(reader);
                            }
                        }

                        doc.Close();
                    }
                }
                return ms.ToArray();
            }
        }

How do I pass data between Activities in Android application?

The standard approach.

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();
Bundle bundle = new Bundle();
bundle.putString(“stuff”, getrec);
i.putExtras(bundle);
startActivity(i);

Now in your second activity retrieve your data from the bundle:

Get the bundle

Bundle bundle = getIntent().getExtras();

Extract the data…

String stuff = bundle.getString(“stuff”); 

Write to rails console

As other have said, you want to use either puts or p. Why? Is that magic?

Actually not. A rails console is, under the hood, an IRB, so all you can do in IRB you will be able to do in a rails console. Since for printing in an IRB we use puts, we use the same command for printing in a rails console.

You can actually take a look at the console code in the rails source code. See the require of irb? :)

How to load html string in a webview?

I had the same requirement and I have done this in following way.You also can try out this..

Use loadData method

web.loadData("<p style='text-align:center'><img class='aligncenter size-full wp-image-1607' title='' src="+movImage+" alt='' width='240px' height='180px' /></p><p><center><U><H2>"+movName+"("+movYear+")</H2></U></center></p><p><strong>Director : </strong>"+movDirector+"</p><p><strong>Producer : </strong>"+movProducer+"</p><p><strong>Character : </strong>"+movActedAs+"</p><p><strong>Summary : </strong>"+movAnecdotes+"</p><p><strong>Synopsis : </strong>"+movSynopsis+"</p>\n","text/html", "UTF-8");

movDirector movProducer like all are my string variable.

In short i retain custom styling for my url.

String escape into XML

George, it's simple. Always use the XML APIs to handle XML. They do all the escaping and unescaping for you.

Never create XML by appending strings.

ExecutorService, how to wait for all tasks to finish

You can use ExecutorService.invokeAll method, It will execute all task and wait till all threads finished their task.

Here is complete javadoc

You can also user overloaded version of this method to specify the timeout.

Here is sample code with ExecutorService.invokeAll

public class Test {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService service = Executors.newFixedThreadPool(3);
        List<Callable<String>> taskList = new ArrayList<>();
        taskList.add(new Task1());
        taskList.add(new Task2());
        List<Future<String>> results = service.invokeAll(taskList);
        for (Future<String> f : results) {
            System.out.println(f.get());
        }
    }

}

class Task1 implements Callable<String> {
    @Override
    public String call() throws Exception {
        try {
            Thread.sleep(2000);
            return "Task 1 done";
        } catch (Exception e) {
            e.printStackTrace();
            return " error in task1";
        }
    }
}

class Task2 implements Callable<String> {
    @Override
    public String call() throws Exception {
        try {
            Thread.sleep(3000);
            return "Task 2 done";
        } catch (Exception e) {
            e.printStackTrace();
            return " error in task2";
        }
    }
}

What is the correct way to check for string equality in JavaScript?

You can use == or === but last one works in more simple way (src)

a == b (and its negation !=)

enter image description here

a === b (and its negation !==)

enter image description here

Difference between javacore, thread dump and heap dump in Websphere

Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores

How to export data with Oracle SQL Developer?

If, at some point, you only need to export a single result set, just right click "on the data" (any column of any row) there you will find an export option. The wizard exports the complete result set regardless of what you selected

How to export a CSV to Excel using Powershell

Ups, I entirely forgot this question. In the meantime I got a solution.
This Powershell script converts a CSV to XLSX in the background

Gimmicks are

  • Preserves all CSV values as plain text like =B1+B2 or 0000001.
    You don't see #Name or anything like that. No autoformating is done.
  • Automatically chooses the right delimiter (comma or semicolon) according to your regional setting
  • Autofit columns

PowerShell Code

### Set input and output path
$inputCSV = "C:\somefolder\input.csv"
$outputXLSX = "C:\somefolder\output.xlsx"

### Create a new Excel Workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

### Execute & delete the import query
$query.Refresh()
$query.Delete()

### Save & close the Workbook as XLSX. Change the output extension for Excel 2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()

Disable eslint rules for folder

YAML version :

overrides:
  - files: *-tests.js
    rules:
      no-param-reassign: 0

Example of specific rules for mocha tests :

You can also set a specific env for a folder, like this :

overrides:
  - files: test/*-tests.js
    env:
      mocha: true

This configuration will fix error message about describe and it not defined, only for your test folder:

/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef

How to increment an iterator by 2?

You could use the 'assignment by addition' operator

iter += 2;

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

I get exactly the same stacktrace when tests fail. More to the top you should see messages identfying the failing test classes. Or go to

D:\Masters\thesis related papers and tools\junitcategorizer\junitcategorizer.instrument\target\surefire-reports

and have a look at the failure reports. Fix the problems and your build is ok.

Good news : Your poms seem to be ok, Maven can compile and execute tests.

How to test an SQL Update statement before running it?

What about Transactions? They have the ROLLBACK-Feature.

@see https://dev.mysql.com/doc/refman/5.0/en/commit.html

For example:

START TRANSACTION;
SELECT * FROM nicetable WHERE somthing=1;
UPDATE nicetable SET nicefield='VALUE' WHERE somthing=1;
SELECT * FROM nicetable WHERE somthing=1; #check

COMMIT;
# or if you want to reset changes 
ROLLBACK;

SELECT * FROM nicetable WHERE somthing=1; #should be the old value

Answer on question from @rickozoe below:

In general these lines will not be executed as once. In PHP f.e. you would write something like that (perhaps a little bit cleaner, but wanted to answer quick ;-) ):

$MysqlConnection->query('START TRANSACTION;');
$erg = $MysqlConnection->query('UPDATE MyGuests SET lastname='Doe' WHERE id=2;');
if($erg)
    $MysqlConnection->query('COMMIT;');
else
    $MysqlConnection->query('ROLLBACK;');

Another way would be to use MySQL Variables (see https://dev.mysql.com/doc/refman/5.7/en/user-variables.html and https://stackoverflow.com/a/18499823/1416909 ):

# do some stuff that should be conditionally rollbacked later on

SET @v1 := UPDATE MyGuests SET lastname='Doe' WHERE id=2;
IF(v1 < 1) THEN
    ROLLBACK;
ELSE
    COMMIT;
END IF;

But I would suggest to use the language wrappers available in your favorite programming language.

type checking in javascript

These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x) to ask the question you want to ask with respect to the type of x:

js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false

Change color of Button when Mouse is over

Try this- In this example Original color is green and mouseover color will be DarkGoldenrod

<Button Content="Button" HorizontalAlignment="Left" VerticalAlignment="Bottom" Width="50" Height="50" HorizontalContentAlignment="Left" BorderBrush="{x:Null}" Foreground="{x:Null}" Margin="50,0,0,0">
    <Button.Style>
        <Style TargetType="{x:Type Button}">
            <Setter Property="Background" Value="Green"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border Background="{TemplateBinding Background}">
                            <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Background" Value="DarkGoldenrod"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
</Button>

How do I space out the child elements of a StackPanel?

I improved on Elad Katz' answer.

  • Add LastItemMargin property to MarginSetter to specially handle the last item
  • Add Spacing attached property with Vertical and Horizontal properties that adds spacing between items in vertical and horizontal lists and eliminates any trailing margin at the end of the list

Source code in gist.

Example:

<StackPanel Orientation="Horizontal" foo:Spacing.Horizontal="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<StackPanel Orientation="Vertical" foo:Spacing.Vertical="5">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

<!-- Same as vertical example above -->
<StackPanel Orientation="Vertical" foo:MarginSetter.Margin="0 0 0 5" foo:MarginSetter.LastItemMargin="0">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</StackPanel>

How do I import CSV file into a MySQL table?

The core of your problem seems to be matching the columns in the CSV file to those in the table.

Many graphical mySQL clients have very nice import dialogs for this kind of thing.

My favourite for the job is Windows based HeidiSQL. It gives you a graphical interface to build the LOAD DATA command; you can re-use it programmatically later.

Import textfile

Screenshot: "Import textfile" dialog

To open the Import textfile" dialog, go to Tools > Import CSV file:

enter image description here

How can I count the number of matches for a regex?

If you want to use Java 8 streams and are allergic to while loops, you could try this:

public static int countPattern(String references, Pattern referencePattern) {
    Matcher matcher = referencePattern.matcher(references);
    return Stream.iterate(0, i -> i + 1)
            .filter(i -> !matcher.find())
            .findFirst()
            .get();
}

Disclaimer: this only works for disjoint matches.

Example:

public static void main(String[] args) throws ParseException {
    Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
    System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
    System.out.println(countPattern("[  ]", referencePattern));
}

This prints out:

2
0
1
0

This is a solution for disjoint matches with streams:

public static int countPattern(String references, Pattern referencePattern) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            new Iterator<Integer>() {
                Matcher matcher = referencePattern.matcher(references);
                int from = 0;

                @Override
                public boolean hasNext() {
                    return matcher.find(from);
                }

                @Override
                public Integer next() {
                    from = matcher.start() + 1;
                    return 1;
                }
            },
            Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}

Converting characters to integers in Java

43 is the dec ascii number for the "+" symbol. That explains why you get a 43 back. http://en.wikipedia.org/wiki/ASCII

How to download the latest artifact from Artifactory repository?

You could also use Artifactory Query Language to get the latest artifact.

The following shell script is just an example. It uses 'items.find()' (which is available in the non-Pro version), e.g. items.find({ "repo": {"$eq":"my-repo"}, "name": {"$match" : "my-file*"}}) that searches for files that have a repository name equal to "my-repo" and match all files that start with "my-file". Then it uses the shell JSON parser ./jq to extract the latest file by sorting by the date field 'updated'. Finally it uses wget to download the artifact.

#!/bin/bash

# Artifactory settings
host="127.0.0.1"
username="downloader"
password="my-artifactory-token"

# Use Artifactory Query Language to get the latest scraper script (https://www.jfrog.com/confluence/display/RTF/Artifactory+Query+Language)
resultAsJson=$(curl -u$username:"$password" -X POST  http://$host/artifactory/api/search/aql -H "content-type: text/plain" -d 'items.find({ "repo": {"$eq":"my-repo"}, "name": {"$match" : "my-file*"}})')

# Use ./jq to pars JSON
latestFile=$(echo $resultAsJson | jq -r '.results | sort_by(.updated) [-1].name')

# Download the latest scraper script
wget -N -P ./libs/ --user $username --password $password http://$host/artifactory/my-repo/$latestFile

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

Read pdf files with php

Check out FPDF (with FPDI):

http://www.fpdf.org/

http://www.setasign.de/products/pdf-php-solutions/fpdi/

These will let you open an pdf and add content to it in PHP. I'm guessing you can also use their functionality to search through the existing content for the values you need.

Another possible library is TCPDF: https://tcpdf.org/

Update to add a more modern library: PDF Parser

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Implicit and Explicit Waits

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Explicit Wait + Expected Conditions

An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. The worst case of this is Thread.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. WebDriverWait in combination with ExpectedCondition is one way this can be accomplished.

WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
        ExpectedConditions.visibilityOfElementLocated(By.id("someid")));

How to export iTerm2 Profiles

Caveats: this answer only allows exports color settings.

iTerm => Preferences => Profiles => Colors => Load Presets => Export

Import shall be similar.

CSS: create white glow around image

You can use CSS3 to create an effect like that, but then you're only going to see it in modern browsers that support box shadow, unless you use a polyfill like CSS3PIE. So, for example, you could do something like this: http://jsfiddle.net/cany2/

Subversion stuck due to "previous operation has not finished"?

I had the same issue, what worked for me:

  1. Copy your folders and files to another place, say to a folder (I changed my files recently and the commitment failed and led to the addressed problem)
  2. check out a new working copy
  3. copy your changed files from folder to your working copy and override existing files. Commiting / Updating should work now

How to compare timestamp dates with date-only parameter in MySQL?

As I was researching this I thought it would be nice to modify the BETWEEN solution to show an example for a particular non-static/string date, but rather a variable date, or today's such as CURRENT_DATE(). This WILL use the index on the log_timestamp column.

SELECT *
FROM some_table
WHERE
    log_timestamp
    BETWEEN 
        timestamp(CURRENT_DATE()) 
    AND # Adds 23.9999999 HRS of seconds to the current date
        timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL '86399.999999' SECOND_MICROSECOND));

I did the seconds/microseconds to avoid the 12AM case on the next day. However, you could also do `INTERVAL '1 DAY' via comparison operators for a more reader-friendly non-BETWEEN approach:

SELECT *
FROM some_table
WHERE
    log_timestamp >= timestamp(CURRENT_DATE()) AND
    log_timestamp < timestamp(DATE_ADD(CURRENT_DATE(), INTERVAL 1 DAY));

Both of these approaches will use the index and should perform MUCH faster. Both seem to be equally as fast.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

Force uninstall of Visual Studio

Microsoft started to address the issue in late 2015 by releasing VisualStudioUninstaller.

They abandoned the solution for a while; however work has begun again as of April 2016.

There has finally been an official release for this uninstaller in April 2016 which is described as being "designed to cleanup/scorch all Preview/RC/RTM releases of Visual Studio 2013, Visual Studio 2015 and Visual Studio vNext".

Resource files not found from JUnit test cases

Make 'maven.test.skip' as false in pom file, while building project test reource will come under test-classes.

<maven.test.skip>false</maven.test.skip>

Open a new tab on button click in AngularJS

Proper HTML way: just surround your button with anchor element and add attribute target="_blank". It is as simple as that:

<a ng-href="{{yourDynamicURL}}" target="_blank">
    <h1>Open me in new Tab</h1>
</a>

where you can set in the controller:

$scope.yourDynamicURL = 'https://stackoverflow.com';

How to install sshpass on mac?

There are instructions on how to install sshpass here:

https://gist.github.com/arunoda/7790979

For Mac you will need to install xcode and command line tools then use the unofficial Homewbrew command:

brew install https://raw.githubusercontent.com/kadwanev/bigboybrew/master/Library/Formula/sshpass.rb

How do I call a specific Java method on a click/submit event of a specific button in JSP?

You can try adding action="#{yourBean.function1}" on each button (changing of course the method function2, function3, or whatever you need). If that does not work, you can try the same with the onclick event.

Anyway, it would be easier to help you if you tell us what kind of buttons are you trying to use, a4j:commandButton or whatever you are using.

Cannot run Eclipse; JVM terminated. Exit code=13

I did couple of things inorder to get rid of this annoying error as modifying .ini never worked for me.

  1. Installed latest JDK
  2. Delete old eclipse IDE folder completely.
  3. This time i Unziped to different location

Double Click "eclipse.exe" Works now like charm Use default workspace to load your old projects.

Am suspecting it to be JDK's Java VM issue more than eclipse.

Unable to open debugger port in IntelliJ IDEA

the key to the issue is in debugger port. I was having the same problem, I was killing every process listening on port 8081 (my http port), 1099 (JMX port), tomcat shutdown port, every java.exe, and still nothing.

The thing is this debugger port is different. If you run the application, it will go through the port you have Tomcat configured for, 8080, 8081 or whatever. But if you run it in Debug mode, it goes through a different port.

If you go edit your Tomcat configuration from IntelliJ, the last tab is Startup/Connection. Here go see the configuration for Debug mode, and you'll see its port. Mine was 50473. I changed it to 50472, and everything started working again.

Read only the first line of a file?

first_line = next(open(filename))

Dump all documents of Elasticsearch

ElasticSearch itself provides a way to create data backup and restoration. The simple command to do it is:

CURL -XPUT 'localhost:9200/_snapshot/<backup_folder name>/<backupname>' -d '{
    "indices": "<index_name>",
    "ignore_unavailable": true,
    "include_global_state": false
}'

Now, how to create, this folder, how to include this folder path in ElasticSearch configuration, so that it will be available for ElasticSearch, restoration method, is well explained here. To see its practical demo surf here.

Get name of current class?

Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you.

I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at the very end of the class: block), and can manipulate the class being created. I haven't tested this:

class InputAssigningMetaclass(type):
    def __new__(cls, name, bases, attrs):
        cls.input = get_input(name)
        return super(MyType, cls).__new__(cls, name, bases, newattrs)

class MyBaseFoo(object):
    __metaclass__ = InputAssigningMetaclass

class foo(MyBaseFoo):
    # etc, no need to create 'input'

class foo2(MyBaseFoo):
    # etc, no need to create 'input'

Null or empty check for a string variable

Yes, that code does exactly that.

You can also use:

if (@value is null or @value = '')

Edit:

With the added information that @value is an int value, you need instead:

if (@value is null)

An int value can never contain the value ''.

Check for null variable in Windows batch

To test for the existence of a command line paramater, use empty brackets:

IF [%1]==[] echo Value Missing

or

IF [%1] EQU [] echo Value Missing

The SS64 page on IF will help you here. Under "Does %1 exist?".

You can't set a positional parameter, so what you should do is do something like

SET MYVAR=%1

You can then re-set MYVAR based on its contents.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

Copy Pasting @Lichtamberg's comments to gotoalberto's answer

Works also for Java 1.8:

# in ~/.zshrc and ~/.bashrc

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_92.jdk/Contents/Home 
export PATH=$JAVA_HOME/bin:$PATH 

This fixed my issue on java 8.

Maximum length for MySQL type text

How many characters can a type text field store?

According to Documentation You can use maximum of 21,844 characters if the charset is UTF8

If a lot, would I be able to specify length in the db text type field as I would with varchar?

You dont need to specify the length. If you need more character use data types MEDIUMTEXT or LONGTEXT. With VARCHAR, specifieng length is not for Storage requirement, it is only for how the data is retrieved from data base.

Google Maps API v3: How to remove all markers?

This is the method Google themselves use in at least one sample:

var markers = [];

// Clear out the old markers.
markers.forEach(function(marker) {
  marker.setMap(null);
});
markers = [];

Check Google sample for complete code example:

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox

How can I check if a Perl array contains a particular value?

You certainly want a hash here. Place the bad parameters as keys in the hash, then decide whether a particular parameter exists in the hash.

our %bad_params = map { $_ => 1 } qw(badparam1 badparam2 badparam3)

if ($bad_params{$new_param}) {
  print "That is a bad parameter\n";
}

If you are really interested in doing it with an array, look at List::Util or List::MoreUtils

Count number of rows matching a criteria

mydata$sCode == "CA" will return a boolean array, with a TRUE value everywhere that the condition is met. To illustrate:

> mydata = data.frame(sCode = c("CA", "CA", "AC"))
> mydata$sCode == "CA"
[1]  TRUE  TRUE FALSE

There are a couple of ways to deal with this:

  1. sum(mydata$sCode == "CA"), as suggested in the comments; because TRUE is interpreted as 1 and FALSE as 0, this should return the numer of TRUE values in your vector.

  2. length(which(mydata$sCode == "CA")); the which() function returns a vector of the indices where the condition is met, the length of which is the count of "CA".

Edit to expand upon what's happening in #2:

> which(mydata$sCode == "CA")
[1] 1 2

which() returns a vector identify each column where the condition is met (in this case, columns 1 and 2 of the dataframe). The length() of this vector is the number of occurences.

How can Perl's print add a newline by default?

If Perl 5.10+ is not an option, here is a quick and dirty approximation. It's not exactly the same, since say has some magic when its first arg is a handle, but for printing to STDOUT:

sub say {print @_, "\n"}

say 'hello';

Call a Javascript function every 5 seconds continuously

You can use setInterval(), the arguments are the same.

const interval = setInterval(function() {
   // method to be executed;
 }, 5000);

clearInterval(interval); // thanks @Luca D'Amico

How to calculate probability in a normal distribution given mean & standard deviation?

Here is more info. First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:

import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)

#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability

#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function 
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%

#To find the variate for which the probability is given, let's say the 
#value which needed to provide a 98% probability, you'd use the 
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187

fatal error: Python.h: No such file or directory

If you use a virtualenv with a 3.6 python (edge right now), be sure to install the matching python 3.6 dev sudo apt-get install python3.6-dev, otherwise executing sudo python3-dev will install the python dev 3.3.3-1, which won't solve the issue.

How to use onSavedInstanceState example please

One major note that all new Android developers should know is that any information in Widgets (TextView, Buttons, etc.) will be persisted automatically by Android as long as you assign an ID to them. So that means most of the UI state is taken care of without issue. Only when you need to store other data does this become an issue.

From Android Docs:

The only work required by you is to provide a unique ID (with the android:id attribute) for each widget you want to save its state. If a widget does not have an ID, then it cannot save its state

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

Recursively looping through an object to build a property list

A simple path global variable across each recursive call does the trick for me !

_x000D_
_x000D_
var object = {
  aProperty: {
    aSetting1: 1,
    aSetting2: 2,
    aSetting3: 3,
    aSetting4: 4,
    aSetting5: 5
  },
  bProperty: {
    bSetting1: {
      bPropertySubSetting: true
    },
    bSetting2: "bString"
  },
  cProperty: {
    cSetting: "cString"
  }
}

function iterate(obj, path = []) {
  for (var property in obj) {
    if (obj.hasOwnProperty(property)) {
      if (typeof obj[property] == "object") {
        let curpath = [...path, property];
        iterate(obj[property], curpath);
      } else {
        console.log(path.join('.') + '.' + property + "   " + obj[property]);
        $('#output').append($("<div/>").text(path.join('.') + '.' + property))
      }
    }
  }
}

iterate(object);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.1/jquery.min.js"></script>
<div id='output'></div>
_x000D_
_x000D_
_x000D_