Programs & Examples On #Character replacement

How do I replace a character at a particular index in JavaScript?

In JavaScript, strings are immutable, which means the best you can do is to create a new string with the changed content and assign the variable to point to it.

You'll need to define the replaceAt() function yourself:

String.prototype.replaceAt = function(index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

And use it like this:

var hello = "Hello World";
alert(hello.replaceAt(2, "!!")); // Should display He!!o World

How do I find the last column with data?

Try using the code after you active the sheet:

Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

If you use Cells.SpecialCells(xlCellTypeLastCell).Row only, the problem will be that the xlCellTypeLastCell information will not be updated unless one do a "Save file" action. But use UsedRange will always update the information in realtime.

Refreshing Web Page By WebDriver When Waiting For Specific Condition

5 different ways to refresh a webpage using Selenium Webdriver

There is no special extra coding. I have just used the existing functions in different ways to get it work. Here they are :

  1. Using sendKeys.Keys method

    driver.get("https://accounts.google.com/SignUp");
    driver.findElement(By.id("firstname-placeholder")).sendKeys(Keys.F5);
    
  2. Using navigate.refresh() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.navigate().refresh();
    
  3. Using navigate.to() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.navigate().to(driver.getCurrentUrl());
    
  4. Using get() method

    driver.get("https://accounts.google.com/SignUp");  
    driver.get(driver.getCurrentUrl());
    
  5. Using sendKeys() method

    driver.get("https://accounts.google.com/SignUp"); 
    driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
    

initialize a numpy array

Maybe something like this will fit your needs..

import numpy as np

N = 5
res = []

for i in range(N):
    res.append(np.cumsum(np.ones(shape=(2,4))))

res = np.array(res).reshape((10, 4))
print(res)

Which produces the following output

[[ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]
 [ 1.  2.  3.  4.]
 [ 5.  6.  7.  8.]]

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Creating instance list of different objects

List anyObject = new ArrayList();

or

List<Object> anyObject = new ArrayList<Object>();

now anyObject can hold objects of any type.

use instanceof to know what kind of object it is.

Trying to use fetch and pass in mode: no-cors

The simple solution: Add the following to the very top of the php file you are requesting the data from.

header("Access-Control-Allow-Origin: *");

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

I had a similar problem while moving from Visual Studio 2013 to Visual Studio 2015 on a MVC project.

Deleting the whole .vs solution worked as a charm as Johan J v Rensburg pointed out.

In Python, how do I convert all of the items in a list to floats?

you can use numpy to avoid looping:

import numpy as np
list(np.array(my_list).astype(float)

How to detect scroll direction

Following example will listen to MOUSE scroll only, no touch nor trackpad scrolls.

It uses jQuery.on() (As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document).

$('#elem').on( 'DOMMouseScroll mousewheel', function ( event ) {
  if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
    //scroll down
    console.log('Down');
  } else {
    //scroll up
    console.log('Up');
  }
  //prevent page fom scrolling
  return false;
});

Works on all browsers.

fiddle: http://jsfiddle.net/honk1/gWnNv/7/

In Java, what does NaN mean?

NaN = Not a Number.

AngularJS event on window innerWidth size change

I found a jfiddle that might help here: http://jsfiddle.net/jaredwilli/SfJ8c/

Ive refactored the code to make it simpler for this.

// In your controller
var w = angular.element($window);
$scope.$watch(
  function () {
    return $window.innerWidth;
  },
  function (value) {
    $scope.windowWidth = value;
  },
  true
);

w.bind('resize', function(){
  $scope.$apply();
});

You can then reference to windowWidth from the html

<span ng-bind="windowWidth"></span>

string to string array conversion in java

An additional method:

As was already mentioned, you could convert the original String "name" to a char array quite easily:

String originalString = "name";
char[] charArray = originalString.toCharArray();

To continue this train of thought, you could then convert the char array to a String array:

String[] stringArray = new String[charArray.length];
for (int i = 0; i < charArray.length; i++){
    stringArray[i] = String.valueOf(charArray[i]);
}

At this point, your stringArray will be filled with the original values from your original string "name". For example, now calling

System.out.println(stringArray[0]);

Will return the value "n" (as a String) in this case.

C# DataRow Empty-check

A simple method along the lines of:

bool AreAllColumnsEmpty(DataRow dr)
{
 if (dr == null)
 {
  return true;
 }
 else
 {
  foreach(var value in dr.ItemArray)
  {
    if (value != null)
    {
      return false;
    }
  }
  return true;
 }
}

Should give you what you're after, and to make it "nice" (as there's nothing as far as I'm aware, in the Framework), you could wrap it up as an extension method, and then your resultant code would be:

if (datarow.AreAllColumnsEmpty())
{
}
else
{
}

Converting Secret Key into a String and Vice Versa

You can convert the SecretKey to a byte array (byte[]), then Base64 encode that to a String. To convert back to a SecretKey, Base64 decode the String and use it in a SecretKeySpec to rebuild your original SecretKey.

For Java 8

SecretKey to String:

// create new key
SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
// get base64 encoded version of the key
String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());

String to SecretKey:

// decode the base64 encoded string
byte[] decodedKey = Base64.getDecoder().decode(encodedKey);
// rebuild key using SecretKeySpec
SecretKey originalKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES"); 

For Java 7 and before (including Android):

NOTE I: you can skip the Base64 encoding/decoding part and just store the byte[] in SQLite. That said, performing Base64 encoding/decoding is not an expensive operation and you can store strings in almost any DB without issues.

NOTE II: Earlier Java versions do not include a Base64 in one of the java.lang or java.util packages. It is however possible to use codecs from Apache Commons Codec, Bouncy Castle or Guava.

SecretKey to String:

// CREATE NEW KEY
// GET ENCODED VERSION OF KEY (THIS CAN BE STORED IN A DB)

    SecretKey secretKey;
    String stringKey;

    try {secretKey = KeyGenerator.getInstance("AES").generateKey();}
    catch (NoSuchAlgorithmException e) {/* LOG YOUR EXCEPTION */}

    if (secretKey != null) {stringKey = Base64.encodeToString(secretKey.getEncoded(), Base64.DEFAULT)}

String to SecretKey:

// DECODE YOUR BASE64 STRING
// REBUILD KEY USING SecretKeySpec

    byte[] encodedKey     = Base64.decode(stringKey, Base64.DEFAULT);
    SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");

Image change every 30 seconds - loop

I agree with using frameworks for things like this, just because its easier. I hacked this up real quick, just fades an image out and then switches, also will not work in older versions of IE. But as you can see the code for the actual fade is much longer than the JQuery implementation posted by KARASZI István.

function changeImage() {
    var img = document.getElementById("img");
    img.src = images[x];
    x++;        
    if(x >= images.length) {
        x = 0;
    } 
    fadeImg(img, 100, true);
    setTimeout("changeImage()", 30000);
}

function fadeImg(el, val, fade) {
    if(fade === true) {
        val--;
    } else {
        val ++;
    }       
    if(val > 0 && val < 100) {
        el.style.opacity = val / 100;
        setTimeout(function(){ fadeImg(el, val, fade); }, 10);
    }
}

var images = [], x = 0;
images[0] = "image1.jpg";
images[1] = "image2.jpg";
images[2] = "image3.jpg";
setTimeout("changeImage()", 30000);

Bootstrap: adding gaps between divs

I required only one instance of the vertical padding, so I inserted this line in the appropriate place to avoid adding more to the css. <div style="margin-top:5px"></div>

How to get element by classname or id

getElementsByClassName is a function on the DOM Document. It is neither a jQuery nor a jqLite function.

Don't add the period before the class name when using it:

var result = document.getElementsByClassName("multi-files");

Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):

var wrappedResult = angular.element(result);

If you want to select from the element in a directive's link function you need to access the DOM reference instead of the the jqLite reference - element[0] instead of element:

link: function (scope, element, attrs) {

  var elementResult = element[0].getElementsByClassName('multi-files');
}

Alternatively you can use the document.querySelector function (need the period here if selecting by class):

var queryResult = element[0].querySelector('.multi-files');
var wrappedQueryResult = angular.element(queryResult);

Demo: http://plnkr.co/edit/AOvO47ebEvrtpXeIzYOH?p=preview

Filling a List with all enum values in Java

Try this:

... = new ArrayList<Something>(EnumSet.allOf(Something.class));

as ArrayList has a constructor with Collection<? extends E>. But use this method only if you really want to use EnumSet.

All enums have access to the method values(). It returns an array of all enum values:

... = Arrays.asList(Something.values());

How to get your Netbeans project into Eclipse

One other easy way of doing it would be as follows (if you have a simple NetBeans project and not using maven for example).

  1. In Eclipse, Go to File -> New -> Java Project
  2. Give a name for your project and click finish to create your project
  3. When the project is created find the source folder in NetBeans project, drag and drop all the source files from the NetBeans project to 'src' folder of your new created project in eclipse.
  4. Move the java source files to respective package (if required)
  5. Now you should be able to run your NetBeans project in Eclipse.

How to bind event listener for rendered elements in Angular 2?

HostListener should be the proper way to bind event into your component:

@Component({
  selector: 'your-element'
})

export class YourElement {
  @HostListener('click', ['$event']) onClick(event) {
     console.log('component is clicked');
     console.log(event);
  }
}

JavaScript string encryption and decryption?

The existing answers which leverage SJCL, CryptoJS, and/or WebCrypto aren't necessarily wrong but they're not as safe as you might initially suspect. Generally you want to use libsodium. First I'll explain why, then how.

Why Not SJCL, CryptoJS, WebCrypto, etc.?

Short answer: In order for your encryption to actually be secure, these libraries expect you to make too many choices e.g. the block cipher mode (CBC, CTR, GCM; if you can't tell which of the three I just listed is secure to use and under what constraints, you shouldn't be burdened with this sort of choice at all).

Unless your job title is cryptography engineer, the odds are stacked against you implementing it securely.

Why to Avoid CryptoJS?

CryptoJS offers a handful of building blocks and expects you to know how to use them securely. It even defaults to CBC mode (archived).

Why is CBC mode bad?

Read this write-up on AES-CBC vulnerabilities.

Why to Avoid WebCrypto?

WebCrypto is a potluck standard, designed by committee, for purposes that are orthogonal to cryptography engineering. Specifically, WebCrypto was meant to replace Flash, not provide security.

Why to Avoid SJCL?

SJCL's public API and documentation begs users to encrypt data with a human-remembered password. This is rarely, if ever, what you want to do in the real world.

Additionally: Its default PBKDF2 round count is roughly 86 times as small as you want it to be. AES-128-CCM is probably fine.

Out of the three options above, SJCL is the least likely to end in tears. But there are better options available.

Why is Libsodium Better?

You don't need to choose between a menu of cipher modes, hash functions, and other needless options. You'll never risk screwing up your parameters and removing all security from your protocol.

Instead, libsodium just gives you simple options tuned for maximum security and minimalistic APIs.

  • crypto_box() / crypto_box_open() offer authenticated public-key encryption.
    • The algorithm in question combines X25519 (ECDH over Curve25519) and XSalsa20-Poly1305, but you don't need to know (or even care) about that to use it securely
  • crypto_secretbox() / crypto_secretbox_open() offer shared-key authenticated encryption.
    • The algorithm in question is XSalsa20-Poly1305, but you don't need to know/care

Additionally, libsodium has bindings in dozens of popular programming languages, so it's very likely that libsodium will just work when trying to interoperate with another programming stack. Also, libsodium tends to be very fast without sacrificing security.

How to Use Libsodium in JavaScript?

First, you need to decide one thing:

  1. Do you just want to encrypt/decrypt data (and maybe still somehow use the plaintext in database queries securely) and not worry about the details? Or...
  2. Do you need to implement a specific protocol?

If you selected the first option, get CipherSweet.js.

The documentation is available online. EncryptedField is sufficient for most use cases, but the EncryptedRow and EncryptedMultiRows APIs may be easier if you have a lot of distinct fields you want to encrypt.

With CipherSweet, you don't need to even know what a nonce/IV is to use it securely.

Additionally, this handles int/float encryption without leaking facts about the contents through ciphertext size.

Otherwise, you'll want sodium-plus, which is a user-friendly frontend to various libsodium wrappers. Sodium-Plus allows you to write performant, asynchronous, cross-platform code that's easy to audit and reason about.

To install sodium-plus, simply run...

npm install sodium-plus

There is currently no public CDN for browser support. This will change soon. However, you can grab sodium-plus.min.js from the latest Github release if you need it.

_x000D_
_x000D_
const { SodiumPlus } = require('sodium-plus');_x000D_
let sodium;_x000D_
_x000D_
(async function () {_x000D_
    if (!sodium) sodium = await SodiumPlus.auto();_x000D_
    let plaintext = 'Your message goes here';_x000D_
    let key = await sodium.crypto_secretbox_keygen();_x000D_
    let nonce = await sodium.randombytes_buf(24);_x000D_
    let ciphertext = await sodium.crypto_secretbox(_x000D_
        plaintext,_x000D_
        nonce,_x000D_
        key    _x000D_
    );_x000D_
    console.log(ciphertext.toString('hex'));_x000D_
_x000D_
    let decrypted = await sodium.crypto_secretbox_open(_x000D_
        ciphertext,_x000D_
        nonce,_x000D_
        key_x000D_
    );_x000D_
_x000D_
    console.log(decrypted.toString());_x000D_
})();
_x000D_
_x000D_
_x000D_

The documentation for sodium-plus is available on Github.

If you'd like a step-by-step tutorial, this dev.to article has what you're looking for.

Java Package Does Not Exist Error

I had the exact same problem when manually compiling through the command line, my solution was I didn't include the -sourcepath directory so that way all the subdirectory java files would be compiled too!

How to install and run Typescript locally in npm?

To install TypeScript local in project as a development dependency you can use --save-dev key

npm install --save-dev typescript

It's also writes the typescript into your package.json

You also need to have a tsconfig.json file. For example

{
  "compilerOptions": {
    "target": "ES5",
    "module": "system",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "exclude": [
    "node_modules",
    ".npm"
  ]
}

For more information about the tsconfig you can see here http://www.typescriptlang.org/docs/handbook/tsconfig-json.html

Nested classes' scope?

In Python mutable objects are passed as reference, so you can pass a reference of the outer class to the inner class.

class OuterClass:
    def __init__(self):
        self.outer_var = 1
        self.inner_class = OuterClass.InnerClass(self)
        print('Inner variable in OuterClass = %d' % self.inner_class.inner_var)

    class InnerClass:
        def __init__(self, outer_class):
            self.outer_class = outer_class
            self.inner_var = 2
            print('Outer variable in InnerClass = %d' % self.outer_class.outer_var)

Inline style to act as :hover in CSS

If that <p> tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'. https://cssinjs.org/

SQL injection that gets around mysql_real_escape_string()

TL;DR

mysql_real_escape_string() will provide no protection whatsoever (and could furthermore munge your data) if:

  • MySQL's NO_BACKSLASH_ESCAPES SQL mode is enabled (which it might be, unless you explicitly select another SQL mode every time you connect); and

  • your SQL string literals are quoted using double-quote " characters.

This was filed as bug #72458 and has been fixed in MySQL v5.7.6 (see the section headed "The Saving Grace", below).

This is another, (perhaps less?) obscure EDGE CASE!!!

In homage to @ircmaxell's excellent answer (really, this is supposed to be flattery and not plagiarism!), I will adopt his format:

The Attack

Starting off with a demonstration...

mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"'); // could already be set
$var = mysql_real_escape_string('" OR 1=1 -- ');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

This will return all records from the test table. A dissection:

  1. Selecting an SQL Mode

    mysql_query('SET SQL_MODE="NO_BACKSLASH_ESCAPES"');
    

    As documented under String Literals:

    There are several ways to include quote characters within a string:

    • A “'” inside a string quoted with “'” may be written as “''”.

    • A “"” inside a string quoted with “"” may be written as “""”.

    • Precede the quote character by an escape character (“\”).

    • A “'” inside a string quoted with “"” needs no special treatment and need not be doubled or escaped. In the same way, “"” inside a string quoted with “'” needs no special treatment.

    If the server's SQL mode includes NO_BACKSLASH_ESCAPES, then the third of these options—which is the usual approach adopted by mysql_real_escape_string()—is not available: one of the first two options must be used instead. Note that the effect of the fourth bullet is that one must necessarily know the character that will be used to quote the literal in order to avoid munging one's data.

  2. The Payload

    " OR 1=1 -- 
    

    The payload initiates this injection quite literally with the " character. No particular encoding. No special characters. No weird bytes.

  3. mysql_real_escape_string()

    $var = mysql_real_escape_string('" OR 1=1 -- ');
    

    Fortunately, mysql_real_escape_string() does check the SQL mode and adjust its behaviour accordingly. See libmysql.c:

    ulong STDCALL
    mysql_real_escape_string(MYSQL *mysql, char *to,const char *from,
                 ulong length)
    {
      if (mysql->server_status & SERVER_STATUS_NO_BACKSLASH_ESCAPES)
        return escape_quotes_for_mysql(mysql->charset, to, 0, from, length);
      return escape_string_for_mysql(mysql->charset, to, 0, from, length);
    }
    

    Thus a different underlying function, escape_quotes_for_mysql(), is invoked if the NO_BACKSLASH_ESCAPES SQL mode is in use. As mentioned above, such a function needs to know which character will be used to quote the literal in order to repeat it without causing the other quotation character from being repeated literally.

    However, this function arbitrarily assumes that the string will be quoted using the single-quote ' character. See charset.c:

    /*
      Escape apostrophes by doubling them up
    
    // [ deletia 839-845 ]
    
      DESCRIPTION
        This escapes the contents of a string by doubling up any apostrophes that
        it contains. This is used when the NO_BACKSLASH_ESCAPES SQL_MODE is in
        effect on the server.
    
    // [ deletia 852-858 ]
    */
    
    size_t escape_quotes_for_mysql(CHARSET_INFO *charset_info,
                                   char *to, size_t to_length,
                                   const char *from, size_t length)
    {
    // [ deletia 865-892 ]
    
        if (*from == '\'')
        {
          if (to + 2 > to_end)
          {
            overflow= TRUE;
            break;
          }
          *to++= '\'';
          *to++= '\'';
        }
    

    So, it leaves double-quote " characters untouched (and doubles all single-quote ' characters) irrespective of the actual character that is used to quote the literal! In our case $var remains exactly the same as the argument that was provided to mysql_real_escape_string()—it's as though no escaping has taken place at all.

  4. The Query

    mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');
    

    Something of a formality, the rendered query is:

    SELECT * FROM test WHERE name = "" OR 1=1 -- " LIMIT 1
    

As my learned friend put it: congratulations, you just successfully attacked a program using mysql_real_escape_string()...

The Bad

mysql_set_charset() cannot help, as this has nothing to do with character sets; nor can mysqli::real_escape_string(), since that's just a different wrapper around this same function.

The problem, if not already obvious, is that the call to mysql_real_escape_string() cannot know with which character the literal will be quoted, as that's left to the developer to decide at a later time. So, in NO_BACKSLASH_ESCAPES mode, there is literally no way that this function can safely escape every input for use with arbitrary quoting (at least, not without doubling characters that do not require doubling and thus munging your data).

The Ugly

It gets worse. NO_BACKSLASH_ESCAPES may not be all that uncommon in the wild owing to the necessity of its use for compatibility with standard SQL (e.g. see section 5.3 of the SQL-92 specification, namely the <quote symbol> ::= <quote><quote> grammar production and lack of any special meaning given to backslash). Furthermore, its use was explicitly recommended as a workaround to the (long since fixed) bug that ircmaxell's post describes. Who knows, some DBAs might even configure it to be on by default as means of discouraging use of incorrect escaping methods like addslashes().

Also, the SQL mode of a new connection is set by the server according to its configuration (which a SUPER user can change at any time); thus, to be certain of the server's behaviour, you must always explicitly specify your desired mode after connecting.

The Saving Grace

So long as you always explicitly set the SQL mode not to include NO_BACKSLASH_ESCAPES, or quote MySQL string literals using the single-quote character, this bug cannot rear its ugly head: respectively escape_quotes_for_mysql() will not be used, or its assumption about which quote characters require repeating will be correct.

For this reason, I recommend that anyone using NO_BACKSLASH_ESCAPES also enables ANSI_QUOTES mode, as it will force habitual use of single-quoted string literals. Note that this does not prevent SQL injection in the event that double-quoted literals happen to be used—it merely reduces the likelihood of that happening (because normal, non-malicious queries would fail).

In PDO, both its equivalent function PDO::quote() and its prepared statement emulator call upon mysql_handle_quoter()—which does exactly this: it ensures that the escaped literal is quoted in single-quotes, so you can be certain that PDO is always immune from this bug.

As of MySQL v5.7.6, this bug has been fixed. See change log:

Functionality Added or Changed

Safe Examples

Taken together with the bug explained by ircmaxell, the following examples are entirely safe (assuming that one is either using MySQL later than 4.1.20, 5.0.22, 5.1.11; or that one is not using a GBK/Big5 connection encoding):

mysql_set_charset($charset);
mysql_query("SET SQL_MODE=''");
$var = mysql_real_escape_string('" OR 1=1 /*');
mysql_query('SELECT * FROM test WHERE name = "'.$var.'" LIMIT 1');

...because we've explicitly selected an SQL mode that doesn't include NO_BACKSLASH_ESCAPES.

mysql_set_charset($charset);
$var = mysql_real_escape_string("' OR 1=1 /*");
mysql_query("SELECT * FROM test WHERE name = '$var' LIMIT 1");

...because we're quoting our string literal with single-quotes.

$stmt = $pdo->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$stmt->execute(["' OR 1=1 /*"]);

...because PDO prepared statements are immune from this vulnerability (and ircmaxell's too, provided either that you're using PHP=5.3.6 and the character set has been correctly set in the DSN; or that prepared statement emulation has been disabled).

$var  = $pdo->quote("' OR 1=1 /*");
$stmt = $pdo->query("SELECT * FROM test WHERE name = $var LIMIT 1");

...because PDO's quote() function not only escapes the literal, but also quotes it (in single-quote ' characters); note that to avoid ircmaxell's bug in this case, you must be using PHP=5.3.6 and have correctly set the character set in the DSN.

$stmt = $mysqli->prepare('SELECT * FROM test WHERE name = ? LIMIT 1');
$param = "' OR 1=1 /*";
$stmt->bind_param('s', $param);
$stmt->execute();

...because MySQLi prepared statements are safe.

Wrapping Up

Thus, if you:

  • use native prepared statements

OR

  • use MySQL v5.7.6 or later

OR

  • in addition to employing one of the solutions in ircmaxell's summary, use at least one of:

    • PDO;
    • single-quoted string literals; or
    • an explicitly set SQL mode that does not include NO_BACKSLASH_ESCAPES

...then you should be completely safe (vulnerabilities outside the scope of string escaping aside).

Convert INT to FLOAT in SQL

In oracle db there is a trick for casting int to float (I suppose, it should also work in mysql):

select myintfield + 0.0 as myfloatfield from mytable

While @Heximal's answer works, I don't personally recommend it.

This is because it uses implicit casting. Although you didn't type CAST, either the SUM() or the 0.0 need to be cast to be the same data-types, before the + can happen. In this case the order of precedence is in your favour, and you get a float on both sides, and a float as a result of the +. But SUM(aFloatField) + 0 does not yield an INT, because the 0 is being implicitly cast to a FLOAT.

I find that in most programming cases, it is much preferable to be explicit. Don't leave things to chance, confusion, or interpretation.

If you want to be explicit, I would use the following.

CAST(SUM(sl.parts) AS FLOAT) * cp.price
-- using MySQL CAST FLOAT  requires 8.0

I won't discuss whether NUMERIC or FLOAT *(fixed point, instead of floating point)* is more appropriate, when it comes to rounding errors, etc. I'll just let you google that if you need to, but FLOAT is so massively misused that there is a lot to read about the subject already out there.

You can try the following to see what happens...

CAST(SUM(sl.parts) AS NUMERIC(10,4)) * CAST(cp.price AS NUMERIC(10,4))

What is the purpose of .PHONY in a Makefile?

By default, Makefile targets are "file targets" - they are used to build files from other files. Make assumes its target is a file, and this makes writing Makefiles relatively easy:

foo: bar
  create_one_from_the_other foo bar

However, sometimes you want your Makefile to run commands that do not represent physical files in the file system. Good examples for this are the common targets "clean" and "all". Chances are this isn't the case, but you may potentially have a file named clean in your main directory. In such a case Make will be confused because by default the clean target would be associated with this file and Make will only run it when the file doesn't appear to be up-to-date with regards to its dependencies.

These special targets are called phony and you can explicitly tell Make they're not associated with files, e.g.:

.PHONY: clean
clean:
  rm -rf *.o

Now make clean will run as expected even if you do have a file named clean.

In terms of Make, a phony target is simply a target that is always out-of-date, so whenever you ask make <phony_target>, it will run, independent from the state of the file system. Some common make targets that are often phony are: all, install, clean, distclean, TAGS, info, check.

Why do I have to "git push --set-upstream origin <branch>"?

A basically full command is like git push <remote> <local_ref>:<remote_ref>. If you run just git push, git does not know what to do exactly unless you have made some config that helps git to make a decision. In a git repo, we can setup multiple remotes. Also we can push a local ref to any remote ref. The full command is the most straightforward way to make a push. If you want to type fewer words, you have to config first, like --set-upstream.

Why does 2 mod 4 = 2?

When you divide 2 by 4, you get 0 with 2 left over or remaining. Modulo is just the remainder after dividing the number.

2D character array initialization in C

How to create an array size 5 containing pointers to characters:

char *array_of_pointers[ 5 ];        //array size 5 containing pointers to char
char m = 'm';                        //character value holding the value 'm'
array_of_pointers[0] = &m;           //assign m ptr into the array position 0.
printf("%c", *array_of_pointers[0]); //get the value of the pointer to m

How to create a pointer to an array of characters:

char (*pointer_to_array)[ 5 ];        //A pointer to an array containing 5 chars
char m = 'm';                         //character value holding the value 'm'
*pointer_to_array[0] = m;             //dereference array and put m in position 0
printf("%c", (*pointer_to_array)[0]); //dereference array and get position 0

How to create an 2D array containing pointers to characters:

char *array_of_pointers[5][2];          
//An array size 5 containing arrays size 2 containing pointers to char

char m = 'm';                           
//character value holding the value 'm'

array_of_pointers[4][1] = &m;           
//Get position 4 of array, then get position 1, then put m ptr in there.

printf("%c", *array_of_pointers[4][1]); 
//Get position 4 of array, then get position 1 and dereference it.

How to create a pointer to an 2D array of characters:

char (*pointer_to_array)[5][2];
//A pointer to an array size 5 each containing arrays size 2 which hold chars

char m = 'm';                            
//character value holding the value 'm'

(*pointer_to_array)[4][1] = m;           
//dereference array, Get position 4, get position 1, put m there.

printf("%c", (*pointer_to_array)[4][1]); 
//dereference array, Get position 4, get position 1

To help you out with understanding how humans should read complex C/C++ declarations read this: http://www.programmerinterview.com/index.php/c-cplusplus/c-declarations/

What is the yield keyword used for in C#?

Here is a simple way to understand the concept: The basic idea is, if you want a collection that you can use "foreach" on, but gathering the items into the collection is expensive for some reason (like querying them out of a database), AND you will often not need the entire collection, then you create a function that builds the collection one item at a time and yields it back to the consumer (who can then terminate the collection effort early).

Think of it this way: You go to the meat counter and want to buy a pound of sliced ham. The butcher takes a 10-pound ham to the back, puts it on the slicer machine, slices the whole thing, then brings the pile of slices back to you and measures out a pound of it. (OLD way). With yield, the butcher brings the slicer machine to the counter, and starts slicing and "yielding" each slice onto the scale until it measures 1-pound, then wraps it for you and you're done. The Old Way may be better for the butcher (lets him organize his machinery the way he likes), but the New Way is clearly more efficient in most cases for the consumer.

Arithmetic overflow error converting numeric to data type numeric

check your value which you want to store in integer column. I think this is greater then range of integer. if you want to store value greater then integer range. you should use bigint datatype

How to concatenate string variables in Bash

Bash also supports a += operator as shown in this code:

A="X Y"
A+=" Z"
echo "$A"

output

X Y Z

What is the default maximum heap size for Sun's JVM from Java SE 6?

one way is if you have a jdk installed , in bin folder there is a utility called jconsole(even visualvm can be used). Launch it and connect to the relevant java process and you can see what are the heap size settings set and many other details

When running headless or cli only, jConsole can be used over lan, if you specify a port to connect on when starting the service in question.

Default optional parameter in Swift function

The default argument allows you to call the function without passing an argument. If you don't pass the argument, then the default argument is supplied. So using your code, this...

test()

...is exactly the same as this:

test(nil)

If you leave out the default argument like this...

func test(firstThing: Int?) {
    if firstThing != nil {
        print(firstThing!)
    }
    print("done")
}

...then you can no longer do this...

test()

If you do, you will get the "missing argument" error that you described. You must pass an argument every time, even if that argument is just nil:

test(nil)   // this works

How to view files in binary from bash?

sudo apt-get install bless

Bless is GUI tool which can view, edit, seach and a lot more. Its very light weight.

what is difference between success and .done() method of $.ajax

In short, decoupling success callback function from the ajax function so later you can add your own handlers without modifying the original code (observer pattern).

Please find more detailed information from here: https://stackoverflow.com/a/14754681/1049184

Initialize empty vector in structure - c++

How about

user r = {"",{}};

or

user r = {"",{'\0'}};

or

user r = {"",std::vector<unsigned char>()};

or

user r;

How to start Apache and MySQL automatically when Windows 8 comes up

Open:

C/users/YourUserName/AppData/Roaming/Microsoft/Windows/Start Menu/Programs/Start-up

If there is a problem finding the above directory:***

Press Windows + R and write shell:startup. Press Enter. It will move you to the directory.

Drag and drop the XAMPP control panel to the above directory

It will open XAMPP automatically.

If you want to auto start Apache and MySQL, click on config in XAMPP and check the Apache and XAMPP items (if unchecked) and save it. It will start it automatically.

What is this date format? 2011-08-12T20:17:46.384Z

@John-Skeet gave me the clue to fix my own issue around this. As a younger programmer this small issue is easy to miss and hard to diagnose. So Im sharing it in the hopes it will help someone.

My issue was that I wanted to parse the following string contraining a time stamp from a JSON I have no influence over and put it in more useful variables. But I kept getting errors.

So given the following (pay attention to the string parameter inside ofPattern();

String str = "20190927T182730.000Z"

LocalDateTime fin;
fin = LocalDateTime.parse( str, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss.SSSZ") );

Error:

Exception in thread "main" java.time.format.DateTimeParseException: Text 
'20190927T182730.000Z' could not be parsed at index 19

The problem? The Z at the end of the Pattern needs to be wrapped in 'Z' just like the 'T' is. Change "yyyyMMdd'T'HHmmss.SSSZ" to "yyyyMMdd'T'HHmmss.SSS'Z'" and it works.

Removing the Z from the pattern alltogether also led to errors.

Frankly, I'd expect a Java class to have anticipated this.

how to convert a string date to date format in oracle10g

You can convert a string to a DATE using the TO_DATE function, then reformat the date as another string using TO_CHAR, i.e.:

SELECT TO_CHAR(
         TO_DATE('15/August/2009,4:30 PM'
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM DUAL;

15-08-2009

For example, if your table name is MYTABLE and the varchar2 column is MYDATESTRING:

SELECT TO_CHAR(
         TO_DATE(MYDATESTRING
                ,'DD/Month/YYYY,HH:MI AM')
       ,'DD-MM-YYYY')
FROM MYTABLE;

compare two list and return not matching items using linq

The naive approach:

MsgList.Where(x => !SentList.Any(y => y.MsgID == x.MsgID))

Be aware this will take up to m*n operations as it compares every MsgID in SentList to each in MsgList ("up to" because it will short-circuit when it does happen to match).

How to Use UTF-8 Collation in SQL Server database?

Note that as of Microsoft SQL Server 2016, UTF-8 is supported by bcp, BULK_INSERT, and OPENROWSET.

Addendum 2016-12-21: SQL Server 2016 SP1 now enables Unicode Compression (and most other previously Enterprise-only features) for all versions of MS SQL including Standard and Express. This is not the same as UTF-8 support, but it yields a similar benefit if the goal is disk space reduction for Western alphabets.

Another git process seems to be running in this repository

I faced same problem. I had to do little more to resolve this. First I deleted index.lock then I cloned fresh code from existing git repository location. I had my code changes in seperated location. I copiped .git folder and .gitignore file and pasted in the code folder where I had made code changes. Then I tried to commit and push, it worked smoothly. May be this impormation will be helpful if your problem doesn't by above given solutions.

How to send string from one activity to another?

Intents are intense.

Intents are useful for passing data around the android framework. You can communicate with your own Activities and even other processes. Check the developer guide and if you have specific questions (it's a lot to digest up front) come back.

How to run regasm.exe from command line other than Visual Studio command prompt?

You don't need the directory on your path. You could put it on your path, but you don't NEED to do that.
If you are calling regasm rarely, or calling it from a batch file, you may find it is simpler to just invoke regasm via the fully-qualified pathname on the exe, eg:

c:\Windows\Microsoft.NET\Framework\v2.0.50727\regasm.exe   MyAssembly.dll

Reading a UTF8 CSV file with Python

Python 2.X

There is a unicode-csv library which should solve your problems, with added benefit of not naving to write any new csv-related code.

Here is a example from their readme:

>>> import unicodecsv
>>> from cStringIO import StringIO
>>> f = StringIO()
>>> w = unicodecsv.writer(f, encoding='utf-8')
>>> w.writerow((u'é', u'ñ'))
>>> f.seek(0)
>>> r = unicodecsv.reader(f, encoding='utf-8')
>>> row = r.next()
>>> print row[0], row[1]
é ñ

Python 3.X

In python 3 this is supported out of the box by the build-in csv module. See this example:

import csv
with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

Turn a number into star rating display using jQuery and CSS

Why not just have five separate images of a star (empty, quarter-full, half-full, three-quarter-full and full) then just inject the images into your DOM depending on the truncated or rouded value of rating multiplied by 4 (to get a whole numner for the quarters)?

For example, 4.8618164 multiplied by 4 and rounded is 19 which would be four and three quarter stars.

Alternatively (if you're lazy like me), just have one image selected from 21 (0 stars through 5 stars in one-quarter increments) and select the single image based on the aforementioned value. Then it's just one calculation followed by an image change in the DOM (rather than trying to change five different images).

Get the full URL in PHP

Clear code, working in all webservers (Apache, nginx, IIS, ...):

$url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

Difference of keywords 'typename' and 'class' in templates?

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

and

template<typename T>
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above -- it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).

You also must use class when explicitly instantiating a template:

template class Foo<int>;

I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

How do I get the total Json record count using JQuery?

Why would you want length in this case?

If you do want to check for length, have the server return a JSON array with key-value pairs like this:

[
  {key:value},
  {key:value}
]

In JSON, [ and ] represents an array (with a length property), { and } represents a object (without a length property). You can iterate through the members of a object, but you will get functions as well, making a length check of the numbers of members useless except for iterating over them.

How to write a caption under an image?

Put the image — let's say it's width is 140px — inside of a link:

<a><img src='image link' style='width: 140px'></a>

Next, put the caption in a and give it a width less than your image, while centering it:

<a>
  <img src='image link' style='width: 140px'>
  <div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>

Next, in the link tag, style the link so that it no longer looks like a link. You can give it any color you want, but just remove any text decoration your links may carry.

<a style='text-decoration: none; color: orange;'>
  <img src='image link' style='width: 140px'>
  <div style='width: 130px; text-align: center;'>I just love to visit this most beautiful place in all the world.</div>
</a>

I wrapped the image with it's caption in a link so that no text could push the caption out of the way: The caption is tied to the picture by the link. Here's an example: http://www.alphaeducational.com/p/okay.html

How do I add space between items in an ASP.NET RadioButtonList

Even easier...

ASP.NET

<asp:RadioButtonList runat="server" ID="MyRadioButtonList" RepeatDirection="Horizontal" CssClass="FormatRadioButtonList"> ...

CSS

.FormatRadioButtonList label
{
  margin-right: 15px;
}

How to extend / inherit components?

You can inherit @Input, @Output, @ViewChild, etc. Look at the sample:

@Component({
    template: ''
})
export class BaseComponent {
    @Input() someInput: any = 'something';

    @Output() someOutput: EventEmitter<void> = new EventEmitter<void>();

}

@Component({
    selector: 'app-derived',
    template: '<div (click)="someOutput.emit()">{{someInput}}</div>',
    providers: [
        { provide: BaseComponent, useExisting: DerivedComponent }
    ]
})
export class DerivedComponent {

}

What is the difference between XAMPP or WAMP Server & IIS?

WAMP stands for Windows,Apache,Mysql,Php

XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)

Advantages of XAMPP:

  • It is cross-platform software

  • It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.

  • it is easy to configure and use.

Advantages of WAMP:

  • It is easy to Use. (Changing Configuration)

  • WAMP is Available for both 64 bit and 32-bit system.

if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.

i suggest using laragon :

Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.

Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.

Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.

Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.

Advantages of Laragon:

  • Pretty URLs
    Use app.test instead of localhost/app.

  • Portable
    You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.

  • Isolated
    Laragon has an isolated environment with your OS - it will keep your system clean.

  • Easy Operation

    Unlike others which pre-config for you, Laragon auto-configsall the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.

  • Modern & Powerful
    Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed. Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.

How To Convert A Number To an ASCII Character?

you can simply cast it.

char c = (char)100;

jQuery Refresh/Reload Page if Ajax Success after time

I prefer this way Using ajaxStop + setInterval,, this will refresh the page after any XHR[ajax] request in the same page

    $(document).ajaxStop(function() {
        setInterval(function() {
            location.reload();
        }, 3000);
    });

Equivalent to 'app.config' for a library (DLL)

Why not to use:

  • [ProjectNamespace].Properties.Settings.Default.[KeyProperty] for C#
  • My.Settings.[KeyProperty] for VB.NET

You just have to update visually those properties at design-time through:

[Solution Project]->Properties->Settings

Simple way to change the position of UIView?

Other way:

CGPoint position = CGPointMake(100,30);
[self setFrame:(CGRect){
      .origin = position,
      .size = self.frame.size
}];

This i save size parameters and change origin only.

Chart won't update in Excel (2007)

I had this problem and found that it was caused by having two excel applications running at the same time. If I closed everything and opened just the file I was having problems with the charts where dynamic like they should be. Maybe this helps

Parse query string in JavaScript

Me too! http://jsfiddle.net/drzaus/8EE8k/

(Note: without fancy nested or duplicate checking)

deparam = (function(d,x,params,p,i,j) {
return function (qs) {
    // start bucket; can't cheat by setting it in scope declaration or it overwrites
    params = {};
    // remove preceding non-querystring, correct spaces, and split
    qs = qs.substring(qs.indexOf('?')+1).replace(x,' ').split('&');
    // march and parse
    for (i = qs.length; i > 0;) {
        p = qs[--i];
        // allow equals in value
        j = p.indexOf('=');
        // what if no val?
        if(j === -1) params[d(p)] = undefined;
        else params[d(p.substring(0,j))] = d(p.substring(j+1));
    }

    return params;
};//--  fn  deparam
})(decodeURIComponent, /\+/g);

And tests:

var tests = {};
tests["simple params"] = "ID=2&first=1&second=b";
tests["full url"] = "http://blah.com/?third=c&fourth=d&fifth=e";
tests['just ?'] = '?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses';
tests['with equals'] = 'foo=bar&baz=quux&equals=with=extra=equals&grault=garply';
tests['no value'] = 'foo=bar&baz=&qux=quux';
tests['value omit'] = 'foo=bar&baz&qux=quux';

var $output = document.getElementById('output');
function output(msg) {
    msg = Array.prototype.slice.call(arguments, 0).join("\n");
    if($output) $output.innerHTML += "\n" + msg + "\n";
    else console.log(msg);
}
var results = {}; // save results, so we can confirm we're not incorrectly referencing
$.each(tests, function(msg, test) {
    var q = deparam(test);
    results[msg] = q;
    output(msg, test, JSON.stringify(q), $.param(q));
    output('-------------------');
});

output('=== confirming results non-overwrite ===');
$.each(results, function(msg, result) {
    output(msg, JSON.stringify(result));
    output('-------------------');
});

Results in:

simple params
ID=2&first=1&second=b
{"second":"b","first":"1","ID":"2"}
second=b&first=1&ID=2
-------------------
full url
http://blah.com/?third=c&fourth=d&fifth=e
{"fifth":"e","fourth":"d","third":"c"}
fifth=e&fourth=d&third=c
-------------------
just ?
?animal=bear&fruit=apple&building=Empire State Building&spaces=these+are+pluses
{"spaces":"these are pluses","building":"Empire State Building","fruit":"apple","animal":"bear"}
spaces=these%20are%20pluses&building=Empire%20State%20Building&fruit=apple&animal=bear
-------------------
with equals
foo=bar&baz=quux&equals=with=extra=equals&grault=garply
{"grault":"garply","equals":"with=extra=equals","baz":"quux","foo":"bar"}
grault=garply&equals=with%3Dextra%3Dequals&baz=quux&foo=bar
-------------------
no value
foo=bar&baz=&qux=quux
{"qux":"quux","baz":"","foo":"bar"}
qux=quux&baz=&foo=bar
-------------------
value omit
foo=bar&baz&qux=quux
{"qux":"quux","foo":"bar"}   <-- it's there, i swear!
qux=quux&baz=&foo=bar        <-- ...see, jQuery found it
-------------------

Best practices for catching and re-throwing .NET exceptions

Nobody has explained the difference between ExceptionDispatchInfo.Capture( ex ).Throw() and a plain throw, so here it is. However, some people have noticed the problem with throw.

The complete way to rethrow a caught exception is to use ExceptionDispatchInfo.Capture( ex ).Throw() (only available from .Net 4.5).

Below there are the cases necessary to test this:

1.

void CallingMethod()
{
    //try
    {
        throw new Exception( "TEST" );
    }
    //catch
    {
    //    throw;
    }
}

2.

void CallingMethod()
{
    try
    {
        throw new Exception( "TEST" );
    }
    catch( Exception ex )
    {
        ExceptionDispatchInfo.Capture( ex ).Throw();
        throw; // So the compiler doesn't complain about methods which don't either return or throw.
    }
}

3.

void CallingMethod()
{
    try
    {
        throw new Exception( "TEST" );
    }
    catch
    {
        throw;
    }
}

4.

void CallingMethod()
{
    try
    {
        throw new Exception( "TEST" );
    }
    catch( Exception ex )
    {
        throw new Exception( "RETHROW", ex );
    }
}

Case 1 and case 2 will give you a stack trace where the source code line number for the CallingMethod method is the line number of the throw new Exception( "TEST" ) line.

However, case 3 will give you a stack trace where the source code line number for the CallingMethod method is the line number of the throw call. This means that if the throw new Exception( "TEST" ) line is surrounded by other operations, you have no idea at which line number the exception was actually thrown.

Case 4 is similar with case 2 because the line number of the original exception is preserved, but is not a real rethrow because it changes the type of the original exception.

Tooltip on image

I am set Tooltips On My Working Project That Is 100% Working

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
.tooltip {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border-bottom: 1px dotted black;_x000D_
}_x000D_
_x000D_
.tooltip .tooltiptext {_x000D_
  visibility: hidden;_x000D_
  width: 120px;_x000D_
  background-color: black;_x000D_
  color: #fff;_x000D_
  text-align: center;_x000D_
  border-radius: 6px;_x000D_
  padding: 5px 0;_x000D_
_x000D_
  /* Position the tooltip */_x000D_
  position: absolute;_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
  visibility: visible;_x000D_
}_x000D_
.size_of_img{_x000D_
width:90px}_x000D_
</style>_x000D_
_x000D_
<body style="text-align:center;">_x000D_
_x000D_
<p>Move the mouse over the text below:</p>_x000D_
_x000D_
<div class="tooltip"><img class="size_of_img" src="https://babeltechreviews.com/wp-content/uploads/2018/07/rendition1.img_.jpg" alt="Image 1" /><span class="tooltiptext">grewon.pdf</span></div>_x000D_
_x000D_
<p>Note that the position of the tooltip text isn't very good. Check More Position <a href="https://www.w3schools.com/css/css_tooltip.asp">GO</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Convert list of ASCII codes to string (byte array) in Python

I much prefer the array module to the struct module for this kind of tasks (ones involving sequences of homogeneous values):

>>> import array
>>> array.array('B', [17, 24, 121, 1, 12, 222, 34, 76]).tostring()
'\x11\x18y\x01\x0c\xde"L'

no len call, no string manipulation needed, etc -- fast, simple, direct, why prefer any other approach?!

Get top most UIViewController

The best solution for me is an extension with a function. Create a swift file with this extension

First is the UIWindow extension:

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

inside that file add function

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

And if you want to use it, you can call it anywhere. Example:

  override func viewDidLoad() {
    super.viewDidLoad()
      if let topVC = visibleViewController() {
             //show some label or text field 
    }
}

File code is like this:

import UIKit

public extension UIWindow {
    var visibleViewController: UIViewController? {
        return UIWindow.visibleVC(vc: self.rootViewController)
    }

    static func visibleVC(vc: UIViewController?) -> UIViewController? {
        if let navigationViewController = vc as? UINavigationController {
            return UIWindow.visibleVC(vc: navigationViewController.visibleViewController)
        } else if let tabBarVC = vc as? UITabBarController {
            return UIWindow.visibleVC(vc: tabBarVC.selectedViewController)
        } else {
            if let presentedVC = vc?.presentedViewController {
                return UIWindow.visibleVC(vc: presentedVC)
            } else {
                return vc
            }
        }
    }
}

func visibleViewController() -> UIViewController? {
    let appDelegate = UIApplication.shared.delegate
    if let window = appDelegate!.window {
        return window?.visibleViewController
    }
    return nil
}

Getting error: ISO C++ forbids declaration of with no type

Your declaration is int ttTreeInsert(int value);

However, your definition/implementation is

ttTree::ttTreeInsert(int value)
{
}

Notice that the return type int is missing in the implementation. Instead it should be

int ttTree::ttTreeInsert(int value)
{
    return 1; // or some valid int
}

Get the latest record from mongodb collection

Yet another way of getting the last item from a MongoDB Collection (don't mind about the examples):

> db.collection.find().sort({'_id':-1}).limit(1)

Normal Projection

> db.Sports.find()
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2017", "Body" : "Again, the Pats won the Super Bowl." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Sorted Projection ( _id: reverse order )

> db.Sports.find().sort({'_id':-1})
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }
{ "_id" : ObjectId("5bfb6011dea65504b456ab13"), "Type" : "World Cup 2018", "Head" : "Brazil Qualified for Round of 16", "Body" : "The Brazilians are happy today, due to the qualification of the Brazilian Team for the Round of 16 for the World Cup 2018." }
{ "_id" : ObjectId("5bfb5f82dea65504b456ab12"), "Type" : "NFL", "Head" : "Patriots Won SuperBowl 2018", "Body" : "Again, the Pats won the Super Bowl" }

sort({'_id':-1}), defines a projection in descending order of all documents, based on their _ids.

Sorted Projection ( _id: reverse order ): getting the latest (last) document from a collection.

> db.Sports.find().sort({'_id':-1}).limit(1)
{ "_id" : ObjectId("5bfb60b1dea65504b456ab14"), "Type" : "F1", "Head" : "Ferrari Lost Championship", "Body" : "By two positions, Ferrari loses the F1 Championship, leaving the Italians in tears." }

Two values from one input in python?

Two inputs separated by space:

x,y=input().split()

How to set delay in android?

You can use this:

import java.util.Timer;

and for the delay itself, add:

 new Timer().schedule(
                    new TimerTask(){
                
                        @Override
                        public void run(){
                            
                        //if you need some code to run when the delay expires
                        }
                        
                    }, delay);

where the delay variable is in milliseconds; for example set delay to 5000 for a 5-second delay.

Oracle Date datatype, transformed to 'YYYY-MM-DD HH24:MI:SS TMZ' through SQL

There's a bit of confusion in your question:

  • a Date datatype doesn't save the time zone component. This piece of information is truncated and lost forever when you insert a TIMESTAMP WITH TIME ZONE into a Date.
  • When you want to display a date, either on screen or to send it to another system via a character API (XML, file...), you use the TO_CHAR function. In Oracle, a Date has no format: it is a point in time.
  • Reciprocally, you would use TO_TIMESTAMP_TZ to convert a VARCHAR2 to a TIMESTAMP, but this won't convert a Date to a TIMESTAMP.
  • You use FROM_TZ to add the time zone information to a TIMESTAMP (or a Date).
  • In Oracle, CST is a time zone but CDT is not. CDT is a daylight saving information.
  • To complicate things further, CST/CDT (-05:00) and CST/CST (-06:00) will have different values obviously, but the time zone CST will inherit the daylight saving information depending upon the date by default.

So your conversion may not be as simple as it looks.

Assuming that you want to convert a Date d that you know is valid at time zone CST/CST to the equivalent at time zone CST/CDT, you would use:

SQL> SELECT from_tz(d, '-06:00') initial_ts,
  2         from_tz(d, '-06:00') at time zone ('-05:00') converted_ts
  3    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  4                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  5            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
09/10/12 01:10:21,000000 -06:00 09/10/12 02:10:21,000000 -05:00

My default timestamp format has been used here. I can specify a format explicitely:

SQL> SELECT to_char(from_tz(d, '-06:00'),'yyyy-mm-dd hh24:mi:ss TZR') initial_ts,
  2         to_char(from_tz(d, '-06:00') at time zone ('-05:00'),
  3                 'yyyy-mm-dd hh24:mi:ss TZR') converted_ts
  4    FROM (SELECT cast(to_date('2012-10-09 01:10:21',
  5                              'yyyy-mm-dd hh24:mi:ss') as timestamp) d
  6            FROM dual);

INITIAL_TS                      CONVERTED_TS
------------------------------- -------------------------------
2012-10-09 01:10:21 -06:00      2012-10-09 02:10:21 -05:00

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

The Code part :

Image imProfile = new Image(getClass().getResourceAsStream("/img/profile128.png"));

ImageView profileImage=new ImageView(imProfile);

in a javafx maven:

enter image description here

How do I print to the debug output window in a Win32 app?

To print to the real console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE. The extra console window is annoying, but for debugging purposes it's very valuable.

OutputDebugString prints to the debugger output when running inside the debugger.

Python - IOError: [Errno 13] Permission denied:

For me nothing from above worked. So I solved my problem with this workaround. Just check that you have added SYSTEM in directory folder. I hope it will help somoene.

import os
# create file
@staticmethod
def create_file(path):
    if not os.path.exists(path):
        os.system('echo # > {}'.format(path))

# append lines to the file
split_text = text_file.split('\n')
    for st in split_text:
        os.system('echo {} >> {}'.format(st,path))

How to implement band-pass Butterworth filter with Scipy.signal.butter

You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high] (expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band".

Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.

from scipy.signal import butter, lfilter


def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y


if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

Here are the plots that are generated by this script:

Frequency response for several filter orders

enter image description here

default web page width - 1024px or 980px?

980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.

Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.

Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/

How to convert byte[] to InputStream?

Check out java.io.ByteArrayInputStream

Make git automatically remove trailing whitespace before committing

This doesn't remove whitespace automatically before a commit, but it is pretty easy to effect. I put the following perl script in a file named git-wsf (git whitespace fix) in a dir in $PATH so I can:

git wsf | sh

and it removes all whitespace only from lines of files that git reports as a diff.

#! /bin/sh
git diff --check | perl -x $0
exit

#! /usr/bin/perl

use strict;

my %stuff;
while (<>) {
    if (/trailing whitespace./) {
        my ($file,$line) = split(/:/);
        push @{$stuff{$file}},$line;
    }
}

while (my ($file, $line) = each %stuff) {
    printf "ex %s <<EOT\n", $file;
    for (@$line) {
        printf '%ds/ *$//'."\n", $_;
    }
    print "wq\nEOT\n";
}

Generate a unique id

Why don't use GUID?

Guid guid = Guid.NewGuid();
string str = guid.ToString();

How to check if a file exists in Documents folder?

If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking

for (int i = 0; i < numberHere; ++i){
    NSFileManager* fileMgr = [NSFileManager defaultManager];
    NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
    NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
    BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
    if (fileExists == NO){
        cout << "DOESNT Exist!" << endl;
    } else {
        cout << "DOES Exist!" << endl;
    }
}

NameError: name 'self' is not defined

For cases where you also wish to have the option of setting 'b' to None:

def p(self, **kwargs):
    b = kwargs.get('b', self.a)
    print b

How do you detect/avoid Memory leaks in your (Unmanaged) code?

If you are using Visual Studio, Microsoft provides some useful functions for detecting and debugging memory leaks.

I would start with this article: https://msdn.microsoft.com/en-us/library/x98tx3cf(v=vs.140).aspx

Here is the quick summary of those articles. First, include these headers:

#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>

Then you need to call this when your program exits:

_CrtDumpMemoryLeaks();

Alternatively, if your program does not exit in the same place every time, you can call this at the start of your program:

_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

Now when the program exits all the allocations that were not free'd will be printed in the Output Window along with the file they were allocated in and the allocation occurrence.

This strategy works for most programs. However, it becomes difficult or impossible in certain cases. Using third party libraries that do some initialization on startup may cause other objects to appear in the memory dump and can make tracking down your leaks difficult. Also, if any of your classes have members with the same name as any of the memory allocation routines( such as malloc ), the CRT debug macros will cause problems.

There are other techniques explained in the MSDN link referenced above that could be used as well.

How to stop console from closing on exit?

You could open a command prompt, CD to the Debug or Release folder, and type the name of your exe. When I suggest this to people they think it is a lot of work, but here are the bare minimum clicks and keystrokes for this:

  • in Visual Studio, right click your project in Solution Explorer or the tab with the file name if you have a file in the solution open, and choose Open Containing Folder or Open in Windows Explorer
  • in the resulting Windows Explorer window, double-click your way to the folder with the exe
  • Shift-right-click in the background of the explorer window and choose Open Commmand Window here
  • type the first letter of your executable and press tab until the full name appears
  • press enter

I think that's 14 keystrokes and clicks (counting shift-right-click as two for example) which really isn't much. Once you have the command prompt, of course, running it again is just up-arrow, enter.

Remove trailing zeros from decimal in SQL Server

I understand this is an old post but would like to provide SQL that i came up with

DECLARE @value DECIMAL(23,3)
set @value = 1.2000
select @value original_val, 
    SUBSTRING(  CAST( @value as VARCHAR(100)), 
                0,
                PATINDEX('%.%',CAST(@value as VARCHAR(100)))
            )
      + CASE WHEN ROUND( 
                        REVERSE( SUBSTRING( CAST(@value as VARCHAR(100)),
                                        PATINDEX('%.%',CAST(@value as VARCHAR(100)))+1,
                                        LEN(CAST(@value as VARCHAR(100)))
                                        )
                                )
                    ,1) > 0 THEN 
            '.' 
            +  REVERSE(ROUND(REVERSE(SUBSTRING( CAST(@value as VARCHAR(100)),
                                                PATINDEX('%.%',CAST(@value as VARCHAR(100)))+1,
                                                LEN(CAST(@value as VARCHAR(100)))
                                                )
                ),1))
        ELSE '' END  AS modified_val

How to extend available properties of User.Identity

Check out this great blog post by John Atten: ASP.NET Identity 2.0: Customizing Users and Roles

It has great step-by-step info on the whole process. Go read it : )

Here are some of the basics.

Extend the default ApplicationUser class by adding new properties (i.e.- Address, City, State, etc.):

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> 
    GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this,  DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    // Use a sensible display name for views:
    [Display(Name = "Postal Code")]
    public string PostalCode { get; set; }

    // Concatenate the address info for display in tables and such:
    public string DisplayAddress
    {
        get
        {
            string dspAddress = string.IsNullOrWhiteSpace(this.Address) ? "" : this.Address;
            string dspCity = string.IsNullOrWhiteSpace(this.City) ? "" : this.City;
            string dspState = string.IsNullOrWhiteSpace(this.State) ? "" : this.State;
            string dspPostalCode = string.IsNullOrWhiteSpace(this.PostalCode) ? "" : this.PostalCode;

            return string.Format("{0} {1} {2} {3}", dspAddress, dspCity, dspState, dspPostalCode);
        }
    }

Then you add your new properties to your RegisterViewModel.

    // Add the new address properties:
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

Then update the Register View to include the new properties.

    <div class="form-group">
        @Html.LabelFor(m => m.Address, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.Address, new { @class = "form-control" })
        </div>
    </div>

Then update the Register() method on AccountController with the new properties.

    // Add the Address properties:
    user.Address = model.Address;
    user.City = model.City;
    user.State = model.State;
    user.PostalCode = model.PostalCode;

How to find time complexity of an algorithm

Time complexity with examples

1 - Basic Operations (arithmetic, comparisons, accessing array’s elements, assignment) : The running time is always constant O(1)

Example :

read(x)                               // O(1)
a = 10;                               // O(1)
a = 1.000.000.000.000.000.000         // O(1)

2 - If then else statement: Only taking the maximum running time from two or more possible statements.

Example:

age = read(x)                               // (1+1) = 2
if age < 17 then begin                      // 1
      status = "Not allowed!";              // 1
end else begin
      status = "Welcome! Please come in";   // 1
      visitors = visitors + 1;              // 1+1 = 2
end;

So, the complexity of the above pseudo code is T(n) = 2 + 1 + max(1, 1+2) = 6. Thus, its big oh is still constant T(n) = O(1).

3 - Looping (for, while, repeat): Running time for this statement is the number of looping multiplied by the number of operations inside that looping.

Example:

total = 0;                                  // 1
for i = 1 to n do begin                     // (1+1)*n = 2n
      total = total + i;                    // (1+1)*n = 2n
end;
writeln(total);                             // 1

So, its complexity is T(n) = 1+4n+1 = 4n + 2. Thus, T(n) = O(n).

4 - Nested Loop (looping inside looping): Since there is at least one looping inside the main looping, running time of this statement used O(n^2) or O(n^3).

Example:

for i = 1 to n do begin                     // (1+1)*n  = 2n
   for j = 1 to n do begin                  // (1+1)n*n = 2n^2
       x = x + 1;                           // (1+1)n*n = 2n^2
       print(x);                            // (n*n)    = n^2
   end;
end;

Common Running Time

There are some common running times when analyzing an algorithm:

  1. O(1) – Constant Time Constant time means the running time is constant, it’s not affected by the input size.

  2. O(n) – Linear Time When an algorithm accepts n input size, it would perform n operations as well.

  3. O(log n) – Logarithmic Time Algorithm that has running time O(log n) is slight faster than O(n). Commonly, algorithm divides the problem into sub problems with the same size. Example: binary search algorithm, binary conversion algorithm.

  4. O(n log n) – Linearithmic Time This running time is often found in "divide & conquer algorithms" which divide the problem into sub problems recursively and then merge them in n time. Example: Merge Sort algorithm.

  5. O(n2) – Quadratic Time Look Bubble Sort algorithm!

  6. O(n3) – Cubic Time It has the same principle with O(n2).

  7. O(2n) – Exponential Time It is very slow as input get larger, if n = 1000.000, T(n) would be 21000.000. Brute Force algorithm has this running time.

  8. O(n!) – Factorial Time THE SLOWEST !!! Example : Travel Salesman Problem (TSP)

Taken from this article. Very well explained should give a read.

Python Pandas iterate over rows and access column names

This was not as straightforward as I would have hoped. You need to use enumerate to keep track of how many columns you have. Then use that counter to look up the name of the column. The accepted answer does not show you how to access the column names dynamically.

for row in df.itertuples(index=False, name=None):
    for k,v in enumerate(row):
        print("column: {0}".format(df.columns.values[k]))
        print("value: {0}".format(v)

Java - remove last known item from ArrayList

clients.get will return a ClientThread and not a String, and it will bomb with an IndexOutOfBoundsException if it would compile as Java is zero based for indexing.

Similarly I think you should call remove on the clients list.

ClientThread hey = clients.get(clients.size()-1);
clients.remove(hey);
System.out.println(hey + " has logged out.");
System.out.println("CONNECTED PLAYERS: " + clients.size());

I would use the stack functions of a LinkedList in this case though.

ClientThread hey = clients.removeLast()

Iterate over the lines of a string

I suppose you could roll your own:

def parse(string):
    retval = ''
    for char in string:
        retval += char if not char == '\n' else ''
        if char == '\n':
            yield retval
            retval = ''
    if retval:
        yield retval

I'm not sure how efficient this implementation is, but that will only iterate over your string once.

Mmm, generators.

Edit:

Of course you'll also want to add in whatever type of parsing actions you want to take, but that's pretty simple.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

How to find path of active app.config file?

If you mean you are only getting a null return when you use NUnit, then you probably need to copy the ConnectionString value the your app.config of your application to the app.config of your test library.

When it is run by the test loader, the test assembly is loaded at runtime and will look in its own app.config (renamed to testAssembly.dll.config at compile time) rather then your applications config file.

To get the location of the assembly you're running, try

System.Reflection.Assembly.GetExecutingAssembly().Location

Rails: How can I rename a database column in a Ruby on Rails migration?

Let's KISS. All it takes is three simple steps. The following works for Rails 5.2.

1 . Create a Migration

  • rails g migration RenameNameToFullNameInStudents

  • rails g RenameOldFieldToNewFieldInTableName - that way it is perfectly clear to maintainers of the code base later on. (use a plural for the table name).

2. Edit the migration

# I prefer to explicitly write theupanddownmethods.

# ./db/migrate/20190114045137_rename_name_to_full_name_in_students.rb

class RenameNameToFullNameInStudents < ActiveRecord::Migration[5.2]
  def up
    # rename_column :table_name, :old_column, :new_column
    rename_column :students, :name, :full_name
  end

  def down
            # Note that the columns are reversed
    rename_column :students, :full_name, :name
  end
end

3. Run your migrations

rake db:migrate

And you are off to the races!

What is the difference between Cloud Computing and Grid Computing?

You should really read Wikipedia for in-depth understanding. In short, Cloud computing means you develop/run your software remotely on remote platform. This can be either using remote virtual infrastructure (amazon EC2), remote platform (google app engine), or remote application (force.com or gmail.com).

Grid computing means using many physical hardwares to do computations (in the broad sense) as if it was a single hardware. This means that you can run your application on several distinct machines at the same time.

not very accurate but enough to get you started.

Merge unequal dataframes and replace missing rows with 0

"all" option does not work anymore, The new parameter is;

x = pd.merge(df1, df2, how="outer")

The project cannot be built until the build path errors are resolved.

On my Mac this is what worked for me

  1. Project > Clean (errors and warnings will remain or increase after this)
  2. Close Eclipse
  3. Reopen Eclipse (errors show momentarily and then disappear, warnings remain)

You are good to go and can now run your project

Working copy XXX locked and cleanup failed in SVN

In-place unversioning of the files, and a fresh checkout into the same location, has solved this problem for me.

In TortoiseSVN, to do an in-place unversioning, right-drag the root folder of the working copy from the file list onto itself in the directory tree, and choose "SVN Export versioned items here" from the pop-up menu. TortoiseSVN notices that the destination is the same as the source, and suggests unversioning the working copy.

After unversioning, do a fresh checkout into the same folder (which now contains an unversioned copy of all the files you had). TortoiseSVN will warn you that you are checking out into an existing folder, but you can go ahead.

After this, cleanups, updates and other operations worked without a hitch. Since both of the above steps preserve local modifications, there should not be any loss of information (but backing the working copy up before this may nevertheless be a good idea).

One warning: If the working copy contains mixed versions or uncommitted property changes, that information WILL be lost. For me, this is not a common occurrence, and given the choice of a corrupt working copy or losing uncommitted property changes, I tend to opt for the latter.

Embed a PowerPoint presentation into HTML

I got so sick of trying all of the different options to web host a power point that were flaky or required flash so I rolled my own.

My solution uses a very simple javascript function to simply scroll / replace a image tag with GIFs that I saved from the Power Point presentation itself.

  1. In the power point presentation click Save As and select GIF. Pick the quality you want to display the presentation at. Power Point will save one GIF image for each slide and name them Slide1.GIF, Slide2.GIF, etc.....

  2. Create a HTML page and add a image tag to display the Power point GIF images.

    <img src="Slide1.GIF" id="mainImage" name="mainImage" width="100%" height="100%" alt="">
    
  3. Add some first, previous, next and last clickable objects with the onClick action as below:

    <a href="#" onclick="swapImage(0);"><img src="/images/first.png" border=0 alt="First"></a>
    <a href="#" onclick="swapImage(currentIndex-1);"><img src="/images/left.png" border=0 alt="Back"></a>
    <a href="#" onclick="swapImage(currentIndex+1);"><img src="/images/right.png" border=0 alt="Next"></a>
    <a href="#" onclick="swapImage(maxIndex);"><img src="/images/last.png" border=0 alt="Last"></a>
    
  4. Finally, add the below javascript function that when called grabs the next Slide.GIF image and displays it to the img tag.

    <script type="text/javascript">
        //Initilize start value to 1 'For Slide1.GIF'
        var currentIndex = 1;
    
        //NOTE: Set this value to the number of slides you have in the presentation.
        var maxIndex=12;
    
        function swapImage(imageIndex){
            //Check if we are at the last image already, return if we are.
            if(imageIndex>maxIndex){
                currentIndex=maxIndex;
                return;
            }
    
            //Check if we are at the first image already, return if we are.
            if(imageIndex<1){
                currentIndex=1;
                return;
            }
    
            currentIndex=imageIndex;
            //Otherwise update mainImage
            document.getElementById("mainImage").src='Slide' +  currentIndex  + '.GIF';
            return;
        }
    </script>
    

Make sure the GIFs are reachable from the HTMl page. They are by default expected to be in the same directory but you should be able to see the logic and how to set to a image directory if required

I have training material up for my company that uses this technique at http://www.vanguarddata.com.au so before you spend any time trying it out you are welcome to look at in action.

I hope this helps someone else out there who is having as much headaches with this as I did.....

how to clear JTable

This is the fastest and easiest way that I have found;

while (tableModel.getRowCount()>0)
          {
             tableModel.removeRow(0);
          }

This clears the table lickety split and leaves it ready for new data.

How to call code behind server method from a client side JavaScript function?

Try creating a new service and calling it. The processing can be done there, and returned back.

http://code.msdn.microsoft.com/windowsazure/WCF-Azure-AJAX-Calculator-4cf3099e

function makeCall(operation){
    var n1 = document.getElementById("num1").value;
    var n2 = document.getElementById("num2").value;
if(n1 && n2){

        // Instantiate a service proxy
        var proxy = new Service();

        // Call correct operation on vf cproxy       
        switch(operation){

            case "gridOne":
                proxy.Calculate(AjaxService.Operation.getWeather, n1, n2,
 onSuccess, onFail, null);

****HTML CODE****
<p>Major City: <input type="text" id="num1" onclick="return num1_onclick()"
/></p>
<p>Country: <input type="text" id="num2" onclick="return num2_onclick()"
/></p> 
<input id="btnDivide" type="button" onclick="return makeCall('gridOne');" 

Visual Studio Code includePath

For everybody that falls off google, in here, this is the fix for VSCode 1.40 (2019):

Open the global settings.json: File > Preferences > Settings

Open the global settings.json: File > Preferences > Settings

Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.

Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.

Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME to your correct system (my case windows) username)
(edit info: There is a problem with the recursion of my approach. VSCode doesn't like multiple definitions for the same thing. I solved it with "C_Cpp.intelliSenseEngine": "Tag Parser" )

Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME to your correct system (my case windows) username)

the code before line 7, on the settings.json has nothing to do with arduino or includePath. You may not copy that...

JSON section to add to settings.json:

"C_Cpp.default.includePath": [
        "C:/Program Files (x86)/Arduino/libraries/**",
        "C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino/**",
        "C:/Program Files (x86)/Arduino/hardware/tools/avr/avr/include/**",
        "C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/5.4.0/include/**",
        "C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard/**",
        "C:/Users/<YOUR USERNAME>/.platformio/packages/framework-arduinoavr/**",
        "C:/Users/<YOUR USERNAME>/Documents/Arduino/libraries/**",
        "{$workspaceFolder}/libraries/**",
        "{$workspaceFolder}/**"
    ],
"C_Cpp.intelliSenseEngine": "Tag Parser"

How to remove leading zeros from alphanumeric text?

I think that it is so easy to do that. You can just loop over the string from the start and removing zeros until you found a not zero char.

int lastLeadZeroIndex = 0;
for (int i = 0; i < str.length(); i++) {
  char c = str.charAt(i);
  if (c == '0') {
    lastLeadZeroIndex = i;
  } else {
    break;
  }
}

str = str.subString(lastLeadZeroIndex+1, str.length());

How can I add comments in MySQL?

You can use single line comments:

-- this is a comment
# this is also a comment

Or a multiline comment:

/*
   multiline
   comment
*/

Easiest way to convert month name to month number in JS ? (Jan = 01)

Just for fun I did this:

function getMonthFromString(mon){
   return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}

Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):

function getMonthFromString(mon){

   var d = Date.parse(mon + "1, 2012");
   if(!isNaN(d)){
      return new Date(d).getMonth() + 1;
   }
   return -1;
 }

Sry for all the edits - getting ahead of myself

json_encode sparse PHP array as JSON array, not JSON object

json_decode($jsondata, true);

true turns all properties to array (sequential or not)

What is the default font of Sublime Text?

Yes. You can use Console of Sublime with (Linux):

Ctrl + `

And type:

view.settings().get('font_face')

Get any setting the same way.

List names of all tables in a SQL Server 2012 schema

SELECT t1.name AS [Schema], t2.name AS [Table]
FROM sys.schemas t1
INNER JOIN sys.tables t2
ON t2.schema_id = t1.schema_id
ORDER BY t1.name,t2.name

How do I drop a function if it already exists?

IF EXISTS (
    SELECT * FROM sysobjects WHERE id = object_id(N'function_name') 
    AND xtype IN (N'FN', N'IF', N'TF')
)
    DROP FUNCTION function_name
GO

If you want to avoid the sys* tables, you could instead do (from here in example A):

IF object_id(N'function_name', N'FN') IS NOT NULL
    DROP FUNCTION function_name
GO

The main thing to catch is what type of function you are trying to delete (denoted in the top sql by FN, IF and TF):

  • FN = Scalar Function
  • IF = Inlined Table Function
  • TF = Table Function

What does request.getParameter return?

Per the Javadoc:

Returns the value of a request parameter as a String, or null if the parameter does not exist.

Do note that it is possible to submit an empty parameter - such that the parameter exists, but has no value. For example, I could include &log=&somethingElse into the URL to enable logging, without needing to specify &log=true. In this case, the value will be an empty String ("").

Codeigniter - multiple database connections

If you need to connect to more than one database simultaneously you can do so as follows:

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to (or you can pass the connection values as indicated above).

By setting the second parameter to TRUE (boolean) the function will return the database object.

Visit https://www.codeigniter.com/userguide3/database/connecting.html for further information.

Resolving javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed Error?

  • Make sure of your JVM location. There can be half a dozen JREs on your system. Which one is your Tomcat really using? Anywhere inside code running in your Tomcat, write println(System.getProperty("java.home")). Note this location. In <java.home>/lib/security/cacerts file are the certificates used by your Tomcat.
  • Find the root certificate that is failing. This can be found by turning on SSL debug using -Djavax.net.debug=all. Run your app and note from console ssl logs the CA that is failing. Its url will be available. In my case I was surprised to find that a proxy zscaler was the one which was failing, as it was actually proxying my calls, and returning its own CA certificate.
  • Paste url in browser. Certificate will get downloaded.
  • Import this certificate into cacerts using keytool import.

Set environment variables from file of key/value pairs

try something like this

for line in `cat your_env_file`; do if [[ $line != \#* ]];then export $line; fi;done

jQuery or Javascript - how to disable window scroll without overflow:hidden;

tfe answered this question in another post on StackOverflow: Answered

Another method would be to use:

$(document).bind("touchmove",function(event){
  event.preventDefault();
});

But it may prevent some of the jquery mobile functionality from working properly.

Unable to show a Git tree in terminal

I would suggest anyone to write down the full command

git log --all --decorate --oneline --graph

rather than create an alias.

It's good to get the commands into your head, so you know it by heart i.e. do not depend on aliases when you change machines.

SQL query for extracting year from a date

This worked for me:

SELECT EXTRACT(YEAR FROM ASOFDATE) FROM PSASOFDATE;

Find index of a value in an array

int keyIndex = Array.FindIndex(words, w => w.IsKey);

That actually gets you the integer index and not the object, regardless of what custom class you have created

Drop multiple columns in pandas

You don't need to wrap it in a list with [..], just provide the subselection of the columns index:

df.drop(df.columns[[1, 69]], axis=1, inplace=True)

as the index object is already regarded as list-like.

Is there a combination of "LIKE" and "IN" in SQL?

I know this is very late, but I had a similar situation. I needed a "Like In" operator for a set of stored procedures I have, which accept many parameters and then uses those parameters to aggregate data from multiple RDBMS systems, thus no RDBMS-specific tricks would work, however the stored procedure and any functions will run on MS SQL Server, so we can use T-SQL for the functionality of generating the full SQL statements for each RDBMS, but the output needs to be fairly RDBMS-independent.

This is what I've come up with for the moment to turn a delimited string (such as a parameter coming into a stored procedure) into a block of SQL. I call it "Lichen" for "LIKE IN". Get it?

Lichen.sql

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =======================================================================
-- Lichen - Scalar Valued Function
-- Returns nvarchar(512) of "LIKE IN" results.  See further documentation.
-- CREATOR: Norman David Cooke
-- CREATED: 2020-02-05
-- UPDATED:
-- =======================================================================
CREATE OR ALTER FUNCTION Lichen 
(
    -- Add the parameters for the function here
    @leadingAnd bit = 1,
    @delimiter nchar(1) = ';',
    @colIdentifier nvarchar(64),
    @argString nvarchar(256)
)
RETURNS nvarchar(512)
AS
BEGIN
    -- Declare the return variable here
    DECLARE @result nvarchar(512)

    -- set delimiter to detect (add more here to detect a delimiter if one isn't provided)
    DECLARE @delimit nchar(1) = ';'
    IF NOT @delimiter = @delimit 
        SET @delimit = @delimiter


    -- check to see if we have any delimiters in the input pattern
    IF CHARINDEX(@delimit, @argString) > 1  -- check for the like in delimiter
    BEGIN  -- begin 'like in' branch having found a delimiter
        -- set up a table variable and string_split the provided pattern into it.
        DECLARE @lichenTable TABLE ([id] [int] IDENTITY(1,1) NOT NULL, line NVARCHAR(32))
        INSERT INTO @lichenTable SELECT * FROM STRING_SPLIT(@argString, ';')

        -- setup loop iterators and determine how many rows were inserted into lichen table
        DECLARE @loopCount int = 1
        DECLARE @lineCount int 
        SELECT @lineCount = COUNT(*) from @lichenTable

        -- select the temp table (to see whats inside for debug)
        --select * from @lichenTable

        -- BEGIN AND wrapper block for 'LIKE IN' if bit is set
        IF @leadingAnd = 1
            SET @result = ' AND ('
        ELSE
            SET @result = ' ('

        -- loop through temp table to build multiple "LIKE 'x' OR" blocks inside the outer AND wrapper block
        WHILE ((@loopCount IS NOT NULL) AND (@loopCount <= @lineCount))
        BEGIN -- begin loop through @lichenTable
            IF (@loopcount = 1) -- the first loop does not get the OR in front
                SELECT @result = CONCAT(@result, ' ', @colIdentifier, ' LIKE ''', line, '''') FROM @lichenTable WHERE id = @loopCount
            ELSE  -- but all subsequent loops do
                SELECT @result = CONCAT(@result, ' OR ', @colIdentifier, ' LIKE ''', line, '''') FROM @lichenTable WHERE id = @loopCount
            SET @loopcount = @loopCount + 1     -- increment loop
        END -- end loop through @lichenTable

        -- set final parens after lichenTable loop
        SET @result = CONCAT(@result, ' )')
    END  -- end 'like in' branch having found a delimiter
    ELSE -- no delimiter was provided
    BEGIN   -- begin "no delimiter found" branch
        IF @leadingAnd = 1 
            SET @result = CONCAT(' AND ', @colIdentifier, ' LIKE ''' + @argString + '''')
        ELSE
            SET @result = CONCAT(' ', @colIdentifier, ' LIKE ''' + @argString + '''')
    END     -- end "no delimiter found" branch

    -- Return the result of the function
    RETURN @result
END  -- end lichen function

GO

The delimiter detection is possibly planned, but for now it defaults to a semicolon so you can just put default in there. There are probably bugs in this. The @leadingAnd parameter is just a bit value to determine if you want a leading "AND" put in front of the block so it fits in nicely with other WHERE clause additions.

Example Usage (with delimiter in argString)

SELECT [dbo].[Lichen] (
   default        -- @leadingAND, bit, default: 1
  ,default        -- @delimiter, nchar(1), default: ';'
  ,'foo.bar'      -- @colIdentifier, nvarchar(64), this is the column identifier
  ,'01%;02%;%03%' -- @argString, nvarchar(256), this is the input string to parse "LIKE IN" from
)
GO

Will return a nvarchar(512) containing:

 AND ( foo.bar LIKE '01%' OR foo.bar LIKE '02%' OR foo.bar LIKE '%03%' ) 

It will also skip the block if the input does not contain a delimiter:

Example Usage (without delimiter in argString)

SELECT [dbo].[Lichen] (
   default        -- @leadingAND, bit, default: 1
  ,default        -- @delimiter, nchar(1), default: ';'
  ,'foo.bar'      -- @colIdentifier, nvarchar(64), this is the column identifier
  ,'01%'          -- @argString, nvarchar(256), this is the input string to parse "LIKE IN" from
)
GO

Will return a nvarchar(512) containing:

 AND foo.bar LIKE '01%'

I'm going to continue work on this, so if I've overlooked something (glaringly obvious or otherwise) please feel free to comment or reach out.

How to return history of validation loss in Keras

The following simple code works great for me:

    seqModel =model.fit(x_train, y_train,
          batch_size      = batch_size,
          epochs          = num_epochs,
          validation_data = (x_test, y_test),
          shuffle         = True,
          verbose=0, callbacks=[TQDMNotebookCallback()]) #for visualization

Make sure you assign the fit function to an output variable. Then you can access that variable very easily

# visualizing losses and accuracy
train_loss = seqModel.history['loss']
val_loss   = seqModel.history['val_loss']
train_acc  = seqModel.history['acc']
val_acc    = seqModel.history['val_acc']
xc         = range(num_epochs)

plt.figure()
plt.plot(xc, train_loss)
plt.plot(xc, val_loss)

Hope this helps. source: https://keras.io/getting-started/faq/#how-can-i-record-the-training-validation-loss-accuracy-at-each-epoch

Pandas sum by groupby, but exclude certain columns

You can select the columns of a groupby:

In [11]: df.groupby(['Country', 'Item_Code'])[["Y1961", "Y1962", "Y1963"]].sum()
Out[11]:
                       Y1961  Y1962  Y1963
Country     Item_Code
Afghanistan 15            10     20     30
            25            10     20     30
Angola      15            30     40     50
            25            30     40     50

Note that the list passed must be a subset of the columns otherwise you'll see a KeyError.

Why "no projects found to import"?

After a long time finally i found that! Here my Way: File -> New Project -> Android Project From Existing Code -> Browse to your project root directory finish!

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

If you have multiple versions of a package / module, you need to be using virtualenv (emphasis mine):

virtualenv is a tool to create isolated Python environments.

The basic problem being addressed is one of dependencies and versions, and indirectly permissions. Imagine you have an application that needs version 1 of LibFoo, but another application requires version 2. How can you use both these applications? If you install everything into /usr/lib/python2.7/site-packages (or whatever your platform’s standard location is), it’s easy to end up in a situation where you unintentionally upgrade an application that shouldn’t be upgraded.

Or more generally, what if you want to install an application and leave it be? If an application works, any change in its libraries or the versions of those libraries can break the application.

Also, what if you can’t install packages into the global site-packages directory? For instance, on a shared host.

In all these cases, virtualenv can help you. It creates an environment that has its own installation directories, that doesn’t share libraries with other virtualenv environments (and optionally doesn’t access the globally installed libraries either).

That's why people consider insert(0, to be wrong -- it's an incomplete, stopgap solution to the problem of managing multiple environments.

Asp Net Web API 2.1 get client IP address

Replying to this 4 year old post, because this seems overcomplicated to me, at least if you're hosting on IIS.

Here's how I solved it:

using System;
using System.Net;
using System.Web;
using System.Web.Http;
...
[HttpPost]
[Route("ContactForm")]
public IHttpActionResult PostContactForm([FromBody] ContactForm contactForm)
    {
        var hostname = HttpContext.Current.Request.UserHostAddress;
        IPAddress ipAddress = IPAddress.Parse(hostname);
        IPHostEntry ipHostEntry = Dns.GetHostEntry(ipAddress);
        ...

Unlike OP, this gives me the client IP and client hostname, not the server. Perhaps they've fixed the bug since then?

Android Studio doesn't see device

Thing which worked for me is is to uncheck the usb debug mode under your mobile setting developer option and allow again it will show the my device option

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

Simple solution for this problem to have quick chat with person who has owner role in gitlab. He can push one file READ.md or similar to just start with. Later, everything will be working as earlier.

Setting the target version of Java in ant javac

You may also set {{ant.build.javac.target=1.5}} ant property to update default target version of task. See http://ant.apache.org/manual/javacprops.html#target

Get the client IP address using PHP

    $ipaddress = '';
    if ($_SERVER['HTTP_CLIENT_IP'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if ($_SERVER['HTTP_X_FORWARDED_FOR'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_X_FORWARDED'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if ($_SERVER['HTTP_FORWARDED_FOR'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if ($_SERVER['HTTP_FORWARDED'] != '127.0.0.1')
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if ($_SERVER['REMOTE_ADDR'] != '127.0.0.1')
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

How to map and remove nil values in Ruby

You could use compact:

[1, nil, 3, nil, nil].compact
=> [1, 3] 

I'd like to remind people that if you're getting an array containing nils as the output of a map block, and that block tries to conditionally return values, then you've got code smell and need to rethink your logic.

For instance, if you're doing something that does this:

[1,2,3].map{ |i|
  if i % 2 == 0
    i
  end
}
# => [nil, 2, nil]

Then don't. Instead, prior to the map, reject the stuff you don't want or select what you do want:

[1,2,3].select{ |i| i % 2 == 0 }.map{ |i|
  i
}
# => [2]

I consider using compact to clean up a mess as a last-ditch effort to get rid of things we didn't handle correctly, usually because we didn't know what was coming at us. We should always know what sort of data is being thrown around in our program; Unexpected/unknown data is bad. Anytime I see nils in an array I'm working on, I dig into why they exist, and see if I can improve the code generating the array, rather than allow Ruby to waste time and memory generating nils then sifting through the array to remove them later.

'Just my $%0.2f.' % [2.to_f/100]

How to find GCD, LCM on a set of numbers

int lcmcal(int i,int y)
{
    int n,x,s=1,t=1;
    for(n=1;;n++)
    {
        s=i*n;
        for(x=1;t<s;x++)
        {
            t=y*x;
        }
        if(s==t)
            break;
    }
    return(s);
}

How to compare DateTime without time via LINQ?

Try

var q = db.Games.Where(t => t.StartDate.Date >= DateTime.Now.Date).OrderBy(d => d.StartDate);

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Table Height 100% inside Div element

Had a similar problem. My solution was to give the inner table a fixed height of 1px and set the height of the td in the inner table to 100%. Against all odds, it works fine, tested in IE, Chrome and FF!

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

DateTime group by date and hour

SELECT [activity_dt], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [activity_dt]), '20010101') as [activity_dt]
    FROM table) abc
 GROUP BY [activity_dt]

There is already an object named in the database

Same case (no DB and MigrationHistory table on Server). My steps:

  1. I deleted Migration data from Up and Down section of my first migration.
  2. Update Database with empty migration (MigrationHistory table was created)
  3. Add your REAL migration and update database with it.

How to set or change the default Java (JDK) version on OS X?

JDK Switch Script

I have adapted the answer from @Alex above and wrote the following to fix the code for Java 9.

$ cat ~/.jdk
#!/bin/bash

#list available jdks
alias jdks="/usr/libexec/java_home -V"
# jdk version switching - e.g. `jdk 6` will switch to version 1.6
function jdk() {
  echo "Switching java version $1";

  requestedVersion=$1
  oldStyleVersion=8
  # Set the version
  if [ $requestedVersion -gt $oldStyleVersion ]; then
    export JAVA_HOME=$(/usr/libexec/java_home -v $1);
  else
    export JAVA_HOME=`/usr/libexec/java_home -v 1.$1`;
  fi

  echo "Setting JAVA_HOME=$JAVA_HOME"

  which java
  java -version;
}

Switch to Java 8

$ jdk 8
Switching java version 8
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
/usr/bin/java
java version "1.8.0_131"
Java(TM) SE Runtime Environment (build 1.8.0_131-b11)
Java HotSpot(TM) 64-Bit Server VM (build 25.131-b11, mixed mode)

Switch to Java 9

$ jdk 9
Switching java version 9
Setting JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-9.0.1.jdk/Contents/Home
/usr/bin/java
java version "9.0.1"
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

How to drop columns using Rails migration

Clear & Simple Instructions for Rails 5 & 6

  • WARNING: You will lose data if you remove a column from your database. To proceed, see below:
  • Warning: the below instructions are for trivial migrations. For complex migrations with e.g. millions and millions of rows, you will have to account for the possibility of failures, you will also have to think about how to optimise your migrations so that they run swiftly, and the possibility that users will use your app while the migration process is occurring. If you have multiple databases, or if anything is remotely complicated, then don't blame me if anything goes wrong!

1. Create a migration

Run the following command in your terminal:

rails generate migration remove_fieldname_from_tablename fieldname:fieldtype

Note: the table name should be in plural form as per rails convention.

Example:

In my case I want to remove the accepted column (a boolean value) from the quotes table:

rails g migration RemoveAcceptedFromQuotes accepted:boolean

See the documentation re: a convention when adding/removing fields to a table:

There is a special syntactic shortcut to generate migrations that add fields to a table.

rails generate migration add_fieldname_to_tablename fieldname:fieldtype

2. Check the migration

# db/migrate/20190122035000_remove_accepted_from_quotes.rb
class RemoveAcceptedFromQuotes < ActiveRecord::Migration[5.2]
  # with rails 5.2 you don't need to add a separate "up" and "down" method.
  def change
    remove_column :quotes, :accepted, :boolean
  end
end

3. Run the migration

rake db:migrate or rails db:migrate (they're both the same)

....And then you're off to the races!

What's the most efficient way to erase duplicates and sort a vector?

More understandable code from: https://en.cppreference.com/w/cpp/algorithm/unique

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <cctype>

int main() 
{
    // remove duplicate elements
    std::vector<int> v{1,2,3,1,2,3,3,4,5,4,5,6,7};
    std::sort(v.begin(), v.end()); // 1 1 2 2 3 3 3 4 4 5 5 6 7 
    auto last = std::unique(v.begin(), v.end());
    // v now holds {1 2 3 4 5 6 7 x x x x x x}, where 'x' is indeterminate
    v.erase(last, v.end()); 
    for (int i : v)
      std::cout << i << " ";
    std::cout << "\n";
}

ouput:

1 2 3 4 5 6 7

jQuery make global variable

set the variable on window:

window.a_href = a_href;

App.Config change value

That worked for me in WPF application:

string configPath = Path.Combine(System.Environment.CurrentDirectory, "YourApplication.exe");
Configuration config = ConfigurationManager.OpenExeConfiguration(configPath);
config.AppSettings.Settings["currentLanguage"].Value = "En";
config.Save();

excel VBA run macro automatically whenever a cell is changed

I was creating a form in which the user enters an email address used by another macro to email a specific cell group to the address entered. I patched together this simple code from several sites and my limited knowledge of VBA. This simply watches for one cell (In my case K22) to be updated and then kills any hyperlink in that cell.

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim KeyCells As Range

    ' The variable KeyCells contains the cells that will
    ' cause an alert when they are changed.
    Set KeyCells = Range("K22")

    If Not Application.Intersect(KeyCells, Range(Target.Address)) _
           Is Nothing Then

        Range("K22").Select
        Selection.Hyperlinks.Delete

    End If 
End Sub

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

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.

Android add placeholder text to EditText

This how to make input password that has hint which not converted to * !!.

On XML :

android:inputType="textPassword"
android:gravity="center"
android:ellipsize="start"
android:hint="Input Password !."

thanks to : mango and rjrjr for the insight :D.

How to exclude a directory in find . command

-prune definitely works and is the best answer because it prevents descending into the dir that you want to exclude. -not -path which still searches the excluded dir, it just doesn't print the result, which could be an issue if the excluded dir is mounted network volume or you don't permissions.

The tricky part is that find is very particular about the order of the arguments, so if you don't get them just right, your command may not work. The order of arguments is generally as such:

find {path} {options} {action}

{path}: Put all the path related arguments first, like . -path './dir1' -prune -o

{options}: I have the most success when putting -name, -iname, etc as the last option in this group. E.g. -type f -iname '*.js'

{action}: You'll want to add -print when using -prune

Here's a working example:

# setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js

# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print

# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print

HTML table: keep the same width for columns

give this style to td: width: 1%;

How to pass a callback as a parameter into another function

You can use JavaScript CallBak like this:

var a;

function function1(callback) {
 console.log("First comeplete");
 a = "Some value";
 callback();
}
function function2(){
 console.log("Second comeplete:", a);
}


function1(function2);

Or Java Script Promise:

let promise = new Promise(function(resolve, reject) { 
  // do function1 job
  let a = "Your assign value"
  resolve(a);
});

promise.then(             

function(a) {
 // do function2 job with function1 return value;
 console.log("Second comeplete:", a);
},
function(error) { 
 console.log("Error found");
});

How to choose the id generation strategy when using JPA and Hibernate

I find this lecture very valuable https://vimeo.com/190275665, in point 3 it summarizes these generators and also gives some performance analysis and guideline one when you use each one.

How do I check (at runtime) if one class is a subclass of another?

#issubclass(child,parent)

class a:
    pass
class b(a):
    pass
class c(b):
    pass

print(issubclass(c,b))#it returns true

How to get package name from anywhere?

Create a java module to be initially run when starting your app. This module would be extending the android Application class and would initialize any global app variables and also contain app-wide utility routines -

public class MyApplicationName extends Application {

    private final String PACKAGE_NAME = "com.mysite.myAppPackageName";

    public String getPackageName() { return PACKAGE_NAME; }
}

Of course, this could include logic to obtain the package name from the android system; however, the above is smaller, faster and cleaner code than obtaining it from android.

Be sure to place an entry in your AndroidManifest.xml file to tell android to run your application module before running any activities -

<application 
    android:name=".MyApplicationName" 
    ...
>

Then, to obtain the package name from any other module, enter

MyApp myApp = (MyApp) getApplicationContext();
String myPackage = myApp.getPackageName();

Using an application module also gives you a context for modules that need but don't have a context.

Print a string as hex bytes?

Your can transform your string to a int generator, apply hex formatting for each element and intercalate with separator:

>>> s = "Hello world !!"
>>> ":".join("{:02x}".format(ord(c)) for c in s)
'48:65:6c:6c:6f:20:77:6f:72:6c:64:20:21:21

Find and replace string values in list

Beside list comprehension, you can try map

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

JPA COUNT with composite primary key query not working

Use count(d.ertek) or count(d.id) instead of count(d). This can be happen when you have composite primary key at your entity.

sh: 0: getcwd() failed: No such file or directory on cited drive

Please check the directory path whether exists or not. This error comes up if the folder doesn't exists from where you are running the command. Probably you have executed a remove command from same path in command line.

Pandas/Python: Set value of one column based on value in another column

I had a big dataset and .loc[] was taking too long so I found a vectorized way to do it. Recall that you can set a column to a logical operator, so this works:

file['Flag'] = (file['Claim_Amount'] > 0)

This gives a Boolean, which I wanted, but you can multiply it by, say, 1 to make an Integer.

How to write log to file

Declare up top in your global var so all your processes can access if needed.

package main

import (
    "log"
    "os"
)
var (
    outfile, _ = os.Create("path/to/my.log") // update path for your needs
    l      = log.New(outfile, "", 0)
)

func main() {
    l.Println("hello, log!!!")
}

PHP absolute path to root

Create a constant with absolute path to the root by using define in ShowInfo.php:

define('ROOTPATH', __DIR__);

Or PHP <= 5.3

define('ROOTPATH', dirname(__FILE__));

Now use it:

if (file_exists(ROOTPATH.'/Texts/MyInfo.txt')) {
  // ...
}

Or use the DOCUMENT_ROOT defined in $_SERVER:

if (file_exists($_SERVER['DOCUMENT_ROOT'].'/Texts/MyInfo.txt')) {
  // ...
}

Convert string to Time

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

JavaScript push to array

That is an object, not an array. So you would do:

var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);

How to remove all whitespace from a string?

In general, we want a solution that is vectorised, so here's a better test example:

whitespace <- " \t\n\r\v\f" # space, tab, newline, 
                            # carriage return, vertical tab, form feed
x <- c(
  " x y ",           # spaces before, after and in between
  " \u2190 \u2192 ", # contains unicode chars
  paste0(            # varied whitespace     
    whitespace, 
    "x", 
    whitespace, 
    "y", 
    whitespace, 
    collapse = ""
  ),   
  NA                 # missing
)
## [1] " x y "                           
## [2] " ? ? "                           
## [3] " \t\n\r\v\fx \t\n\r\v\fy \t\n\r\v\f"
## [4] NA

The base R approach: gsub

gsub replaces all instances of a string (fixed = TRUE) or regular expression (fixed = FALSE, the default) with another string. To remove all spaces, use:

gsub(" ", "", x, fixed = TRUE)
## [1] "xy"                            "??"             
## [3] "\t\n\r\v\fx\t\n\r\v\fy\t\n\r\v\f" NA 

As DWin noted, in this case fixed = TRUE isn't necessary but provides slightly better performance since matching a fixed string is faster than matching a regular expression.

If you want to remove all types of whitespace, use:

gsub("[[:space:]]", "", x) # note the double square brackets
## [1] "xy" "??" "xy" NA 

gsub("\\s", "", x)         # same; note the double backslash

library(regex)
gsub(space(), "", x)       # same

"[:space:]" is an R-specific regular expression group matching all space characters. \s is a language-independent regular-expression that does the same thing.


The stringr approach: str_replace_all and str_trim

stringr provides more human-readable wrappers around the base R functions (though as of Dec 2014, the development version has a branch built on top of stringi, mentioned below). The equivalents of the above commands, using [str_replace_all][3], are:

library(stringr)
str_replace_all(x, fixed(" "), "")
str_replace_all(x, space(), "")

stringr also has a str_trim function which removes only leading and trailing whitespace.

str_trim(x) 
## [1] "x y"          "? ?"          "x \t\n\r\v\fy" NA    
str_trim(x, "left")    
## [1] "x y "                   "? ? "    
## [3] "x \t\n\r\v\fy \t\n\r\v\f" NA     
str_trim(x, "right")    
## [1] " x y"                   " ? ?"    
## [3] " \t\n\r\v\fx \t\n\r\v\fy" NA      

The stringi approach: stri_replace_all_charclass and stri_trim

stringi is built upon the platform-independent ICU library, and has an extensive set of string manipulation functions. The equivalents of the above are:

library(stringi)
stri_replace_all_fixed(x, " ", "")
stri_replace_all_charclass(x, "\\p{WHITE_SPACE}", "")

Here "\\p{WHITE_SPACE}" is an alternate syntax for the set of Unicode code points considered to be whitespace, equivalent to "[[:space:]]", "\\s" and space(). For more complex regular expression replacements, there is also stri_replace_all_regex.

stringi also has trim functions.

stri_trim(x)
stri_trim_both(x)    # same
stri_trim(x, "left")
stri_trim_left(x)    # same
stri_trim(x, "right")  
stri_trim_right(x)   # same

"Uncaught TypeError: Illegal invocation" in Chrome

When you execute a method (i.e. function assigned to an object), inside it you can use this variable to refer to this object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
_x000D_
_x000D_

If you assign a method from one object to another, its this variable refers to the new object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
  someProperty: false,_x000D_
  someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
_x000D_
_x000D_

The same thing happens when you assign requestAnimationFrame method of window to another object. Native functions, such as this, has build-in protection from executing it in other context.

There is a Function.prototype.call() function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({}) gives TypeError: Illegal invocation. However, alert.call(window) works fine, because now alert is executed in its original scope.

If you use .call() with your object like that:

support.animationFrame.call(window, function() {});

it works fine, because requestAnimationFrame is executed in scope of window instead of your object.

However, using .call() every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind(). It has similar effect to .call(), but instead of calling the function, it creates a new function which will always be called in specified context. For example:

_x000D_
_x000D_
window.someProperty = true;_x000D_
var obj = {_x000D_
  someProperty: false,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
_x000D_
_x000D_

The only downside of Function.prototype.bind() is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.

As you probably already figured out, you can use .bind() to always execute requestAnimationFrame in context of window. Your code could look like this:

var support = {
    animationFrame: (window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame).bind(window)
};

Then you can simply use support.animationFrame(function() {});.

How do I represent a time only value in .NET?

I think Rubens' class is a good idea so thought to make an immutable sample of his Time class with basic validation.

class Time
{
    public int Hours   { get; private set; }
    public int Minutes { get; private set; }
    public int Seconds { get; private set; }

    public Time(uint h, uint m, uint s)
    {
        if(h > 23 || m > 59 || s > 59)
        {
            throw new ArgumentException("Invalid time specified");
        }
        Hours = (int)h; Minutes = (int)m; Seconds = (int)s;
    }

    public Time(DateTime dt)
    {
        Hours = dt.Hour;
        Minutes = dt.Minute;
        Seconds = dt.Second;
    }

    public override string ToString()
    {  
        return String.Format(
            "{0:00}:{1:00}:{2:00}",
            this.Hours, this.Minutes, this.Seconds);
    }
}

Set JavaScript variable = null, or leave undefined?

I declare them as undefined when I don't assign a value because they are undefined after all.

AngularJS - Binding radio buttons to models with boolean values

The correct approach in Angularjs is to use ng-value for non-string values of models.

Modify your code like this:

<label data-ng-repeat="choice in question.choices">
  <input type="radio" name="response" data-ng-model="choice.isUserAnswer" data-ng-value="true" />
  {{choice.text}}
</label>

Ref: Straight from the horse's mouth

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

How do I initialize a TypeScript Object with a JSON-Object?

This is my approach (very simple):

const jsonObj: { [key: string]: any } = JSON.parse(jsonStr);

for (const key in jsonObj) {
  if (!jsonObj.hasOwnProperty(key)) {
    continue;
  }

  console.log(key); // Key
  console.log(jsonObj[key]); // Value
  // Your logic...
}

How to get every first element in 2 dimensional list

You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

How to create batch file in Windows using "start" with a path and command with spaces

Interestingly, it seems that in Windows Embedded Compact 7, you cannot specify a title string. The first parameter has to be the command or program.

Rails select helper - Default selected value, how?

Rails 3.0.9

select options_for_select([value1, value2, value3], default)

How to create EditText accepts Alphabets only in android?

Try This

<EditText
  android:id="@+id/EditText1"
  android:text=""
  android:inputType="text|textNoSuggestions"
  android:textSize="18sp"
  android:layout_width="80dp"
  android:layout_height="43dp">
</EditText>

Other inputType can be found Here ..

Check if user is using IE

It's several years later, and the Edge browser now uses Chromium as its rendering engine.
Checking for IE 11 is still a thing, sadly.

Here is a more straightforward approach, as ancient versions of IE should be gone.

if (window.document.documentMode) {
  // Do IE stuff
}

Here is my old answer (2014):

In Edge the User Agent String has changed.

/**
 * detect IEEdge
 * returns version of IE/Edge or false, if browser is not a Microsoft browser
 */
function detectIEEdge() {
    var ua = window.navigator.userAgent;

    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }

    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }

    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
       // Edge => return version number
       return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }

    // other browser
    return false;
}

Sample usage:

alert('IEEdge ' + detectIEEdge());

Default string of IE 10:

Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)

Default string of IE 11:

Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko 

Default string of Edge 12:

Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0 

Default string of Edge 13 (thx @DrCord):

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586 

Default string of Edge 14:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/14.14300 

Default string of Edge 15:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 Edge/15.15063 

Default string of Edge 16:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 Edge/16.16299 

Default string of Edge 17:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134 

Default string of Edge 18 (Insider preview):

Mozilla/5.0 (Windows NT 10.0; Win64; x64; ServiceUI 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17730 

Test at CodePen:

http://codepen.io/gapcode/pen/vEJNZN

Max value of Xmx and Xms in Eclipse?

I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.

Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)

Print "\n" or newline characters as part of the output on terminal

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'

Iterate through a C array

It depends. If it's a dynamically allocated array, that is, you created it calling malloc, then as others suggest you must either save the size of the array/number of elements somewhere or have a sentinel (a struct with a special value, that will be the last one).

If it's a static array, you can sizeof it's size/the size of one element. For example:

int array[10], array_size;
...
array_size = sizeof(array)/sizeof(int);

Note that, unless it's global, this only works in the scope where you initialized the array, because if you past it to another function it gets decayed to a pointer.

Hope it helps.

if, elif, else statement issues in Bash

Missing space between elif and [ rest your program is correct. you need to correct it an check it out. here is fixed program:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

useful link related to this bash if else statement

LINQ query on a DataTable

var results = from DataRow myRow in myDataTable.Rows
    where (int)myRow["RowNo"] == 1
    select myRow

Android: keeping a background service alive (preventing process death)

When you bind your Service to Activity with BIND_AUTO_CREATE your service is being killed just after your Activity is Destroyed and unbound. It does not depend on how you've implemented your Services unBind method it will be still killed.

The other way is to start your Service with startService method from your Activity. This way even if your Activity is destroyed your service won't be destroyed or even paused but you have to pause/destroy it by yourself with stopSelf/stopService when appropriate.

SQL Logic Operator Precedence: And and Or

  1. Arithmetic operators
  2. Concatenation operator
  3. Comparison conditions
  4. IS [NOT] NULL, LIKE, [NOT] IN
  5. [NOT] BETWEEN
  6. Not equal to
  7. NOT logical condition
  8. AND logical condition
  9. OR logical condition

You can use parentheses to override rules of precedence.

How to convert FormData (HTML5 object) to JSON

In my case form Data was data , fire base was expecting an object but data contains object as well as all other stuffs so i tried data.value it worked!!!

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

How to install a specific JDK on Mac OS X?

The easiest way is to use Homebrew. Install Homebrew and then:

brew tap caskroom/versions
brew cask install java7

You can list all available versions using the following command: brew cask search java

m2e error in MavenArchiver.getManifest()

I had also faced the same issue and it got resolved by changing the version from 3.2.0 to 2.6 as shown in below pom.xml snippet

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.6</version>
    <configuration>
        <warSourceDirectory>src/main/webapp</warSourceDirectory>
        <warName>Spring4MVC</warName>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
</plugin>

Visual Studio SignTool.exe Not Found

No Worries! I have found the solution! I just installed https://msdn.microsoft.com/en-us/windows/desktop/bg162891.aspx and it all worked fine :)

Variable length (Dynamic) Arrays in Java

I disagree with the previous answers suggesting ArrayList, because ArrayList is not a Dynamic Array but a List backed by an array. The difference is that you cannot do the following:

ArrayList list = new ArrayList(4);
list.put(3,"Test");

It will give you an IndexOutOfBoundsException because there is no element at this position yet even though the backing array would permit such an addition. So you need to use a custom extendable Array implementation like suggested by @randy-lance

Limit results in jQuery UI Autocomplete

Adding to Andrew's answer, you can even introduce a maxResults property and use it this way:

$("#auto").autocomplete({ 
    maxResults: 10,
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(src, request.term);
        response(results.slice(0, this.options.maxResults));
    }
});

jsFiddle: http://jsfiddle.net/vqwBP/877/

This should help code readability and maintainability!

ImportError: No module named 'selenium'

Even though the egg file may be present, that does not necessarily mean that it is installed. Check out this previous answer for some hint:

How to install Selenium WebDriver on Mac OS

How to close a thread from within?

How about sys.exit() from the module sys.

If sys.exit() is executed from within a thread it will close that thread only.

This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

Can you change what a symlink points to after it is created?

Yes, you can!

$ ln -sfn source_file_or_directory_name softlink_name

Java system properties and environment variables

Fatal error: Cannot use object of type stdClass as array in

if you really want an array instead you can use:

$getvidids->result_array()

which would return the same information as an associative array.

Adjusting the Xcode iPhone simulator scale and size

You can't have 1:1 ratio.

However you can scale it from the iOS Simulator > Window > Scale menu.

Concatenate text files with Windows command line, dropping leading lines

I don't have enough reputation points to comment on the recommendation to use *.csv >> ConcatenatedFile.csv, but I can add a warning:

If you create ConcatenatedFile.csv file in the same directory that you are using for concatenation it will be added to itself.

HTML <sup /> tag affecting line height, how to make it consistent?

I prefer to use length on the vertical-align. This aligns the baseline of the element at the given length above the baseline of its parent.

sup {
   font-size: .83em;
   vertical-align: 0.25em;
   line-height: 0;
}

Can Linux apps be run in Android?

You can install chrooted linux distribution alongside android bacause android is based on linux kernel. If your phone is not rooted, you may use fakeroot (easiest way is to use Debinan nonroot app) even with GUI (with android X-server app or via VNC). If you have a rooted phone, you can install almost fully functional distribution.

I think the best performance and the least limitations you can achieve with Gentoo because all software compiles to your native arm architecture and it is the most flexible, but not the easiest. You may be interested in this post about installing Gentoo on android.

Getting MAC Address

You can do this with psutil which is cross-platform:

import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]