Programs & Examples On #Multi model forms

How to Execute SQL Script File in Java?

Try this code:

String strProc =
         "DECLARE \n" +
         "   sys_date DATE;"+
         "" +
         "BEGIN\n" +
         "" +
         "   SELECT SYSDATE INTO sys_date FROM dual;\n" +
         "" +
         "END;\n";

try{
    DriverManager.registerDriver ( new oracle.jdbc.driver.OracleDriver () );
    Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@your_db_IP:1521:your_db_SID","user","password");  
    PreparedStatement psProcToexecute = connection.prepareStatement(strProc);
    psProcToexecute.execute();
}catch (Exception e) {
    System.out.println(e.toString());  
}

substring of an entire column in pandas dataframe

case the column isn't string, use astype to convert:

df['col'] = df['col'].astype(str).str[:9]

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

I don't think you need the trailing slash in the URL entry. Ie, put this instead:

(r'^led-tv$', filter_by_led ),

This is assuming you have trailing slashes enabled, which is the default.

Install Node.js on Ubuntu

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.19.0/install.sh | bash

nvm install v0.10.33

Just use nvm for Node.js version control - nvm.

How to invoke function from external .c file in C?

use #include "ClasseAusiliaria.c" [Dont use angle brackets (< >) ]

and I prefer save file with .h extension in the same Directory/folder.

#include "ClasseAusiliaria.h"

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

How can I do a case insensitive string comparison?

How about using StringComparison.CurrentCultureIgnoreCase instead?

Detecting arrow key presses in JavaScript

Here's an example implementation:

var targetElement = $0 || document.body;

function getArrowKeyDirection (keyCode) {
  return {
    37: 'left',
    39: 'right',
    38: 'up',
    40: 'down'
  }[keyCode];
}

function isArrowKey (keyCode) {
  return !!getArrowKeyDirection(keyCode);
}

targetElement.addEventListener('keydown', function (event) {
  var direction,
      keyCode = event.keyCode;

  if (isArrowKey(keyCode)) {
    direction = getArrowKeyDirection(keyCode);

    console.log(direction);
  }
});

MySQL select all rows from last month until (now() - 1 month), for comparative purposes

You can get the first of the month, by calculating the last_day of the month before and add one day. It is awkward, but I think it is better than formatting a date as string and use that for calculation.

select 
  *
from
  yourtable t
where
  /* Greater or equal to the start of last month */
  t.date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) and
  /* Smaller or equal than one month ago */
  t.date <= DATE_SUB(NOW(), INTERVAL 1 MONTH)

How is Java platform-independent when it needs a JVM to run?

JVM will be platform dependent.
But whatever it will generate that will be platform independent. [which we called as bytecode or simply you can say...the class file]. for that why Java is called Platform independent.
you can run the same class file on Mac as well on Windows but it will require JRE.

Delete specified file from document directory

I checked your code. It's working for me. Check any error you are getting using the modified code below

- (void)removeImage:(NSString *)filename
{
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

  NSString *filePath = [documentsPath stringByAppendingPathComponent:filename];
  NSError *error;
  BOOL success = [fileManager removeItemAtPath:filePath error:&error];
  if (success) {
      UIAlertView *removedSuccessFullyAlert = [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"Successfully removed" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil];
      [removedSuccessFullyAlert show];
  }
  else
  {
      NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
  }
}

SQL Error: ORA-01861: literal does not match format string 01861

The format you use for the date doesn't match to Oracle's default date format.

A default installation of Oracle Database sets the DEFAULT DATE FORMAT to dd-MMM-yyyy.

Either use the function TO_DATE(dateStr, formatStr) or simply use dd-MMM-yyyy date format model.

What is the maximum recursion depth in Python, and how to increase it?

I'm not sure I'm repeating someone but some time ago some good soul wrote Y-operator for recursively called function like:

def tail_recursive(func):
  y_operator = (lambda f: (lambda y: y(y))(lambda x: f(lambda *args: lambda: x(x)(*args))))(func)
  def wrap_func_tail(*args):
    out = y_operator(*args)
    while callable(out): out = out()
    return out
  return wrap_func_tail

and then recursive function needs form:

def my_recursive_func(g):
  def wrapped(some_arg, acc):
    if <condition>: return acc
    return g(some_arg, acc)
  return wrapped

# and finally you call it in code

(tail_recursive(my_recursive_func))(some_arg, acc)

for Fibonacci numbers your function looks like this:

def fib(g):
  def wrapped(n_1, n_2, n):
    if n == 0: return n_1
    return g(n_2, n_1 + n_2, n-1)
  return wrapped

print((tail_recursive(fib))(0, 1, 1000000))

output:

..684684301719893411568996526838242546875

(actually tones of digits)

How can I convert an Integer to localized month name in Java?

Using SimpleDateFormat.

import java.text.SimpleDateFormat;

public String formatMonth(String month) {
    SimpleDateFormat monthParse = new SimpleDateFormat("MM");
    SimpleDateFormat monthDisplay = new SimpleDateFormat("MMMM");
    return monthDisplay.format(monthParse.parse(month));
}


formatMonth("2"); 

Result: February

Syntax of for-loop in SQL Server

Try it, learn it:

DECLARE @r INT = 5
DECLARE @i INT = 0
DECLARE @F varchar(max) = ''
WHILE @i < @r
BEGIN

    DECLARE @j INT = 0
    DECLARE @o varchar(max) = ''
    WHILE @j < @r - @i - 1
    BEGIN
        SET @o = @o + ' '
        SET @j += 1
    END

    DECLARE @k INT = 0
    WHILE @k < @i + 1
    BEGIN
        SET @o = @o + ' *'  -- '*'
        SET @k += 1
    END
    SET @i += 1
    SET @F = @F + @o + CHAR(13)
END
PRINT @F

With date:

DECLARE @d DATE = '2019-11-01'
WHILE @d < GETDATE()
BEGIN
    PRINT @d
    SET @d = DATEADD(DAY,1,@d)
END
PRINT 'n'
PRINT @d

How do I get monitor resolution in Python?

For later versions of PyGtk:

import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk

display = Gdk.Display.get_default()
n_monitors = display.get_n_monitors()
print("there are %d monitors" % n_monitors)
for m in range(n_monitors):
  monitor = display.get_monitor(m)
  geometry = monitor.get_geometry()
  print("monitor %d: %d x %d" % (m, geometry.width, geometry.height))

How to print formatted BigDecimal values?

To set thousand separator, say 123,456.78 you have to use DecimalFormat:

     DecimalFormat df = new DecimalFormat("#,###.00");
     System.out.println(df.format(new BigDecimal(123456.75)));
     System.out.println(df.format(new BigDecimal(123456.00)));
     System.out.println(df.format(new BigDecimal(123456123456.78)));

Here is the result:

123,456.75
123,456.00
123,456,123,456.78

Although I set #,###.00 mask, it successfully formats the longer values too. Note that the comma(,) separator in result depends on your locale. It may be just space( ) for Russian locale.

Can I call a base class's virtual function if I'm overriding it?

Just in case you do this for a lot of functions in your class:

class Foo {
public:
  virtual void f1() {
    // ...
  }
  virtual void f2() {
    // ...
  }
  //...
};

class Bar : public Foo {
private:
  typedef Foo super;
public:
  void f1() {
    super::f1();
  }
};

This might save a bit of writing if you want to rename Foo.

Excel formula to get ranking position

You could also use the RANK function

=RANK(C2,$C$2:$C$7,0)

It would return data like your example:

  | A       | B        | C
1 | name    | position | points
2 | person1 | 1        | 10
3 | person2 | 2        | 9
4 | person3 | 2        | 9
5 | person4 | 2        | 9
6 | person5 | 5        | 8
7 | person6 | 6        | 7

The 'Points' column needs to be sorted into descending order.

Generic type conversion FROM string

I used lobos answer and it works. But I had a problem with the conversion of doubles because of the culture settings. So I added

return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);

Reading CSV files using C#

private static DataTable ConvertCSVtoDataTable(string strFilePath)
        {
            DataTable dt = new DataTable();
            using (StreamReader sr = new StreamReader(strFilePath))
            {
                string[] headers = sr.ReadLine().Split(',');
                foreach (string header in headers)
                {
                    dt.Columns.Add(header);
                }
                while (!sr.EndOfStream)
                {
                    string[] rows = sr.ReadLine().Split(',');
                    DataRow dr = dt.NewRow();
                    for (int i = 0; i < headers.Length; i++)
                    {
                        dr[i] = rows[i];
                    }
                    dt.Rows.Add(dr);
                }

            }

            return dt;
        }

        private static void WriteToDb(DataTable dt)
        {
            string connectionString =
                "Data Source=localhost;" +
                "Initial Catalog=Northwind;" +
                "Integrated Security=SSPI;";

            using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("spInsertTest", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        cmd.Parameters.Add("@policyID", SqlDbType.Int).Value = 12;
                        cmd.Parameters.Add("@statecode", SqlDbType.VarChar).Value = "blagh2";
                        cmd.Parameters.Add("@county", SqlDbType.VarChar).Value = "blagh3";

                        con.Open();
                        cmd.ExecuteNonQuery();
                    }
                }

         }

Is it better to use "is" or "==" for number comparison in Python?

Use ==.

Sometimes, on some python implementations, by coincidence, integers from -5 to 256 will work with is (in CPython implementations for instance). But don't rely on this or use it in real programs.

How to find controls in a repeater header or footer

As noted in the comments, this only works AFTER you've DataBound your repeater.

To find a control in the header:

lblControl = repeater1.Controls[0].Controls[0].FindControl("lblControl");

To find a control in the footer:

lblControl = repeater1.Controls[repeater1.Controls.Count - 1].Controls[0].FindControl("lblControl");

With extension methods

public static class RepeaterExtensionMethods
{
    public static Control FindControlInHeader(this Repeater repeater, string controlName)
    {
        return repeater.Controls[0].Controls[0].FindControl(controlName);
    }

    public static Control FindControlInFooter(this Repeater repeater, string controlName)
    {
        return repeater.Controls[repeater.Controls.Count - 1].Controls[0].FindControl(controlName);
    }
}

Getting a slice of keys from a map

You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect":

package main

import (
    "fmt"
    "reflect"
)

func main() {
    abc := map[string]int{
        "a": 1,
        "b": 2,
        "c": 3,
    }

    keys := reflect.ValueOf(abc).MapKeys()

    fmt.Println(keys) // [a b c]
}

Efficient iteration with index in Scala

Indeed, calling zipWithIndex on a collection will traverse it and also create a new collection for the pairs. To avoid this, you can just call zipWithIndex on the iterator for the collection. This will just return a new iterator that keeps track of the index while iterating, so without creating an extra collection or additional traversing.

This is how scala.collection.Iterator.zipWithIndex is currently implemented in 2.10.3:

  def zipWithIndex: Iterator[(A, Int)] = new AbstractIterator[(A, Int)] {
    var idx = 0
    def hasNext = self.hasNext
    def next = {
      val ret = (self.next, idx)
      idx += 1
      ret
    }
  }

This should even be a bit more efficient than creating a view on the collection.

How can I get just the first row in a result set AFTER ordering?

You can nest your queries:

select * from (
    select bla
    from bla
    where bla
    order by finaldate desc
)
where rownum < 2

Can I change a column from NOT NULL to NULL without dropping it?

Sure you can.

ALTER TABLE myTable ALTER COLUMN myColumn int NULL

Just substitute int for whatever datatype your column is.

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

The first part of your question is a duplicate of Why do I get a JsonReaderException with this code?, but the most relevant part from that (my) answer is this:

[A] JObject isn't the elementary base type of everything in JSON.net, but JToken is. So even though you could say,

object i = new int[0];

in C#, you can't say,

JObject i = JObject.Parse("[0, 0, 0]");

in JSON.net.

What you want is JArray.Parse, which will accept the array you're passing it (denoted by the opening [ in your API response). This is what the "StartArray" in the error message is telling you.

As for what happened when you used JArray, you're using arr instead of obj:

var rcvdData = JsonConvert.DeserializeObject<LocationData>(arr /* <-- Here */.ToString(), settings);

Swap that, and I believe it should work.

Although I'd be tempted to deserialize arr directly as an IEnumerable<LocationData>, which would save some code and effort of looping through the array. If you aren't going to use the parsed version separately, it's best to avoid it.

Cannot overwrite model once compiled Mongoose

I have been experiencing this issue & it was not because of the schema definitions but rather of serverless offline mode - I just managed to resolve it with this:

serverless offline --skipCacheInvalidation

Which is mentioned here https://github.com/dherault/serverless-offline/issues/258

Hopefully that helps someone else who is building their project on serverless and running offline mode.

MySql server startup error 'The server quit without updating PID file '

If your system has multiple version of Mysql then you are likely going to hit this PID error

we can begin with killing all MySQL process
sudo killall mysqld

Go to /usr/local choose which MySQL version you want to have, then provide the MySQL permission to that. In my case I needed version 8.
sudo chown -R mysql mysql-8.0.21-macos10.15-x86_64

Go to the folder /usr/local/mysql-8.0.21-macos10.15-x86_64 & start SQL server
sudo ./mysql.server start(Enter your laptop password) If it gives below output... the PID issue is solved

@xxxx-M-R0SU support-files $ sudo ./mysql.server start Starting MySQL .. SUCCESS!

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

Prerequirements

Make sure that you've downloaded the latest extras as well as the Android 5.0 SDK via the SDK-Manager.enter image description here

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

running php script (php function) in linux bash

just run in linux terminal to get phpinfo .

   php -r 'phpinfo();'

and to run file like index.php

    php -f index.php

Display an array in a readable/hierarchical format

One-liner for a quick-and-easy JSON representation:

    echo json_encode($data, JSON_PRETTY_PRINT);

If using composer for the project already, require symfony/yaml and:

    echo Yaml::dump($data);

CSS rotate property in IE

To rotate by 45 degrees in IE, you need the following code in your stylesheet:

filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476); /* IE6,IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; /* IE8 */

You’ll note from the above that IE8 has different syntax to IE6/7. You need to supply both lines of code if you want to support all versions of IE.

The horrible numbers there are in Radians; you’ll need to work out the figures for yourself if you want to use an angle other than 45 degrees (there are tutorials on the internet if you look for them).

Also note that the IE6/7 syntax causes problems for other browsers due to the unescaped colon symbol in the filter string, meaning that it is invalid CSS. In my tests, this causes Firefox to ignore all CSS code after the filter. This is something you need to be aware of as it can cause hours of confusion if you get caught out by it. I solved this by having the IE-specific stuff in a separate stylesheet which other browsers didn’t load.

All other current browsers (including IE9 and IE10 — yay!) support the CSS3 transform style (albeit often with vendor prefixes), so you can use the following code to achieve the same effect in all other browsers:

-moz-transform: rotate(45deg);  /* FF3.5/3.6 */
-o-transform: rotate(45deg);  /* Opera 10.5 */
-webkit-transform: rotate(45deg);  /* Saf3.1+ */
transform: rotate(45deg);  /* Newer browsers (incl IE9) */

Hope that helps.

Edit

Since this answer is still getting up-votes, I feel I should update it with information about a JavaScript library called CSS Sandpaper that allows you to use (near) standard CSS code for rotations even in older IE versions.

Once you’ve added CSS Sandpaper to your site, you should then be able to write the following CSS code for IE6–8:

-sand-transform: rotate(40deg);

Much easier than the traditional filter style you'd normally need to use in IE.

Edit

Also note an additional quirk specifically with IE9 (and only IE9), which supports both the standard transform and the old style IE -ms-filter. If you have both of them specified, this can result in IE9 getting completely confused and rendering just a solid black box where the element would have been. The best solution to this is to avoid the filter style by using the Sandpaper polyfill mentioned above.

What do &lt; and &gt; stand for?

&lt; ==  lesser-than == <
&gt; == greater-than == >

In Python, how do I use urllib to see if a website is 404 or 200?

For Python 3:

import urllib.request, urllib.error

url = 'http://www.google.com/asdfsf'
try:
    conn = urllib.request.urlopen(url)
except urllib.error.HTTPError as e:
    # Return code error (e.g. 404, 501, ...)
    # ...
    print('HTTPError: {}'.format(e.code))
except urllib.error.URLError as e:
    # Not an HTTP-specific error (e.g. connection refused)
    # ...
    print('URLError: {}'.format(e.reason))
else:
    # 200
    # ...
    print('good')

How do you detect Credit card type based on number?

Updated: 15th June 2016 (as an ultimate solution currently)

Please note that I even give vote up for the one is top voted, but to make it clear these are the regexps actually works i tested it with thousands of real BIN codes. The most important is to use start strings (^) otherwise it will give false results in real world!

JCB ^(?:2131|1800|35)[0-9]{0,}$ Start with: 2131, 1800, 35 (3528-3589)

American Express ^3[47][0-9]{0,}$ Start with: 34, 37

Diners Club ^3(?:0[0-59]{1}|[689])[0-9]{0,}$ Start with: 300-305, 309, 36, 38-39

Visa ^4[0-9]{0,}$ Start with: 4

MasterCard ^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$ Start with: 2221-2720, 51-55

Maestro ^(5[06789]|6)[0-9]{0,}$ Maestro always growing in the range: 60-69, started with / not something else, but starting 5 must be encoded as mastercard anyway. Maestro cards must be detected in the end of the code because some others has in the range of 60-69. Please look at the code.

Discover ^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$ Discover quite difficult to code, start with: 6011, 622126-622925, 644-649, 65

In javascript I use this function. This is good when u assign it to an onkeyup event and it give result as soon as possible.

function cc_brand_id(cur_val) {
    // the regular expressions check for possible matches as you type, hence the OR operators based on the number of chars
    // regexp string length {0} provided for soonest detection of beginning of the card numbers this way it could be used for BIN CODE detection also

    //JCB
    jcb_regex = new RegExp('^(?:2131|1800|35)[0-9]{0,}$'); //2131, 1800, 35 (3528-3589)
    // American Express
    amex_regex = new RegExp('^3[47][0-9]{0,}$'); //34, 37
    // Diners Club
    diners_regex = new RegExp('^3(?:0[0-59]{1}|[689])[0-9]{0,}$'); //300-305, 309, 36, 38-39
    // Visa
    visa_regex = new RegExp('^4[0-9]{0,}$'); //4
    // MasterCard
    mastercard_regex = new RegExp('^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$'); //2221-2720, 51-55
    maestro_regex = new RegExp('^(5[06789]|6)[0-9]{0,}$'); //always growing in the range: 60-69, started with / not something else, but starting 5 must be encoded as mastercard anyway
    //Discover
    discover_regex = new RegExp('^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$');
    ////6011, 622126-622925, 644-649, 65


    // get rid of anything but numbers
    cur_val = cur_val.replace(/\D/g, '');

    // checks per each, as their could be multiple hits
    //fix: ordering matter in detection, otherwise can give false results in rare cases
    var sel_brand = "unknown";
    if (cur_val.match(jcb_regex)) {
        sel_brand = "jcb";
    } else if (cur_val.match(amex_regex)) {
        sel_brand = "amex";
    } else if (cur_val.match(diners_regex)) {
        sel_brand = "diners_club";
    } else if (cur_val.match(visa_regex)) {
        sel_brand = "visa";
    } else if (cur_val.match(mastercard_regex)) {
        sel_brand = "mastercard";
    } else if (cur_val.match(discover_regex)) {
        sel_brand = "discover";
    } else if (cur_val.match(maestro_regex)) {
        if (cur_val[0] == '5') { //started 5 must be mastercard
            sel_brand = "mastercard";
        } else {
            sel_brand = "maestro"; //maestro is all 60-69 which is not something else, thats why this condition in the end
        }
    }

    return sel_brand;
}

Here you can play with it:

http://jsfiddle.net/upN3L/69/

For PHP use this function, this detects some sub VISA/MC cards too:

/**
  * Obtain a brand constant from a PAN
  *
  * @param string $pan               Credit card number
  * @param bool   $include_sub_types Include detection of sub visa brands
  * @return string
  */
public static function getCardBrand($pan, $include_sub_types = false)
{
    //maximum length is not fixed now, there are growing number of CCs has more numbers in length, limiting can give false negatives atm

    //these regexps accept not whole cc numbers too
    //visa
    $visa_regex = "/^4[0-9]{0,}$/";
    $vpreca_regex = "/^428485[0-9]{0,}$/";
    $postepay_regex = "/^(402360|402361|403035|417631|529948){0,}$/";
    $cartasi_regex = "/^(432917|432930|453998)[0-9]{0,}$/";
    $entropay_regex = "/^(406742|410162|431380|459061|533844|522093)[0-9]{0,}$/";
    $o2money_regex = "/^(422793|475743)[0-9]{0,}$/";

    // MasterCard
    $mastercard_regex = "/^(5[1-5]|222[1-9]|22[3-9]|2[3-6]|27[01]|2720)[0-9]{0,}$/";
    $maestro_regex = "/^(5[06789]|6)[0-9]{0,}$/";
    $kukuruza_regex = "/^525477[0-9]{0,}$/";
    $yunacard_regex = "/^541275[0-9]{0,}$/";

    // American Express
    $amex_regex = "/^3[47][0-9]{0,}$/";

    // Diners Club
    $diners_regex = "/^3(?:0[0-59]{1}|[689])[0-9]{0,}$/";

    //Discover
    $discover_regex = "/^(6011|65|64[4-9]|62212[6-9]|6221[3-9]|622[2-8]|6229[01]|62292[0-5])[0-9]{0,}$/";

    //JCB
    $jcb_regex = "/^(?:2131|1800|35)[0-9]{0,}$/";

    //ordering matter in detection, otherwise can give false results in rare cases
    if (preg_match($jcb_regex, $pan)) {
        return "jcb";
    }

    if (preg_match($amex_regex, $pan)) {
        return "amex";
    }

    if (preg_match($diners_regex, $pan)) {
        return "diners_club";
    }

    //sub visa/mastercard cards
    if ($include_sub_types) {
        if (preg_match($vpreca_regex, $pan)) {
            return "v-preca";
        }
        if (preg_match($postepay_regex, $pan)) {
            return "postepay";
        }
        if (preg_match($cartasi_regex, $pan)) {
            return "cartasi";
        }
        if (preg_match($entropay_regex, $pan)) {
            return "entropay";
        }
        if (preg_match($o2money_regex, $pan)) {
            return "o2money";
        }
        if (preg_match($kukuruza_regex, $pan)) {
            return "kukuruza";
        }
        if (preg_match($yunacard_regex, $pan)) {
            return "yunacard";
        }
    }

    if (preg_match($visa_regex, $pan)) {
        return "visa";
    }

    if (preg_match($mastercard_regex, $pan)) {
        return "mastercard";
    }

    if (preg_match($discover_regex, $pan)) {
        return "discover";
    }

    if (preg_match($maestro_regex, $pan)) {
        if ($pan[0] == '5') { //started 5 must be mastercard
            return "mastercard";
        }
        return "maestro"; //maestro is all 60-69 which is not something else, thats why this condition in the end

    }

    return "unknown"; //unknown for this system
}

How to maintain a Unique List in Java?

Use new HashSet<String> An example:

import java.util.HashSet;
import java.util.Set;

public class MainClass {
  public static void main(String args[]) {
    String[] name1 = { "Amy", "Jose", "Jeremy", "Alice", "Patrick" };

    String[] name2 = { "Alan", "Amy", "Jeremy", "Helen", "Alexi" };

    String[] name3 = { "Adel", "Aaron", "Amy", "James", "Alice" };

    Set<String> letter = new HashSet<String>();

    for (int i = 0; i < name1.length; i++)
      letter.add(name1[i]);

    for (int j = 0; j < name2.length; j++)
      letter.add(name2[j]);

    for (int k = 0; k < name3.length; k++)
      letter.add(name3[k]);

    System.out.println(letter.size() + " letters must be sent to: " + letter);

  }
}

Combine :after with :hover

 #alertlist li:hover:after,#alertlist li.selected:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}?

jsFiddle Link

Renaming files using node.js

  1. fs.readdir(path, callback)
  2. fs.rename(old,new,callback)

Go through http://nodejs.org/api/fs.html

One important thing - you can use sync functions also. (It will work like C program)

Connect Bluestacks to Android Studio

For those people with (cannot connect to localhost:5555: No connection could be made because the target machine actively refused it. (10061) :

Blustacks is listening at IPv4-Localhost-TCP-5555 (not IPv6). Most of the time Windows has IPv6 enabled by default and Localhost is solving ::1:

If the client (ADB) tries to connect a server using localhost and IPv6 is enabled on the main network adapter, ADB will not connect to the server.

So, you have two options :

1- Change your ADB client TCP connection string to localhost IPV4 : adb connect 127.0.0.1

OR :

2-Disable IPV6 protocol from the main network adapter.

How do I use regex in a SQLite query?

With python, assuming con is the connection to SQLite, you can define the required UDF by writing:

con.create_function('regexp', 2, lambda x, y: 1 if re.search(x,y) else 0)

Here is a more complete example:

import re
import sqlite3

with sqlite3.connect(":memory:") as con:
    con.create_function('regexp', 2, lambda x, y: 1 if re.search(x,y) else 0)
    cursor = con.cursor()
    # ...
    cursor.execute("SELECT * from person WHERE surname REGEXP '^A' ")


Deserialize JSON string to c# object

I think the JavaScriptSerializer does not create a dynamic object.

So you should define the class first:

class MyObj {
    public int arg1 {get;set;}
    public int arg2 {get;set;}
}

And deserialize that instead of object:

serializer.Deserialize<MyObj>(str);

Not testet, please try.

How to change a dataframe column from String type to Double type in PySpark?

There is no need for an UDF here. Column already provides cast method with DataType instance :

from pyspark.sql.types import DoubleType

changedTypedf = joindf.withColumn("label", joindf["show"].cast(DoubleType()))

or short string:

changedTypedf = joindf.withColumn("label", joindf["show"].cast("double"))

where canonical string names (other variations can be supported as well) correspond to simpleString value. So for atomic types:

from pyspark.sql import types 

for t in ['BinaryType', 'BooleanType', 'ByteType', 'DateType', 
          'DecimalType', 'DoubleType', 'FloatType', 'IntegerType', 
           'LongType', 'ShortType', 'StringType', 'TimestampType']:
    print(f"{t}: {getattr(types, t)().simpleString()}")
BinaryType: binary
BooleanType: boolean
ByteType: tinyint
DateType: date
DecimalType: decimal(10,0)
DoubleType: double
FloatType: float
IntegerType: int
LongType: bigint
ShortType: smallint
StringType: string
TimestampType: timestamp

and for example complex types

types.ArrayType(types.IntegerType()).simpleString()   
'array<int>'
types.MapType(types.StringType(), types.IntegerType()).simpleString()
'map<string,int>'

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

Thanks for the post Dave Aaron Smith

I edited your answer to accept decimal point and number's from number section. This work perfect for me.

$(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right,decimal(.)in number part, decimal(.) in alphabet
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39,110,190];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (96 <= event.which && event.which <= 106) || // Always 1 through 9 from number section 
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      (96 == event.which && $(this).attr("value")) || // No 0 first digit from number section
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});

Remove part of a string

You can use a built-in for this, strsplit:

> s = "TGAS_1121"
> s1 = unlist(strsplit(s, split='_', fixed=TRUE))[2]
> s1    
 [1] "1121"

strsplit returns both pieces of the string parsed on the split parameter as a list. That's probably not what you want, so wrap the call in unlist, then index that array so that only the second of the two elements in the vector are returned.

Finally, the fixed parameter should be set to TRUE to indicate that the split parameter is not a regular expression, but a literal matching character.

How do I get the color from a hexadecimal color code using .NET?

Use

System.Drawing.Color.FromArgb(myHashCode);

Can .NET load and parse a properties file equivalent to Java Properties class?

C# generally uses xml-based config files rather than the *.ini-style file like you said, so there's nothing built-in to handle this. However, google returns a number of promising results.

iPad browser WIDTH & HEIGHT standard

The pixel width and height of your page will depend on orientation as well as the meta viewport tag, if specified. Here are the results of running jquery's $(window).width() and $(window).height() on iPad 1 browser.

When page has no meta viewport tag:

  • Portrait: 980x1208
  • Landscape: 980x661

When page has either of these two meta tags:

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width">

<meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1">

  • Portrait: 768x946
  • Landscape: 1024x690

With <meta name="viewport" content="width=device-width">:

  • Portrait: 768x946
  • Landscape: 768x518

With <meta name="viewport" content="height=device-height">:

  • Portrait: 980x1024
  • Landscape: 980x1024

With <meta name="viewport" content="height=device-height,width=device-width">:

  • Portrait: 768x1024
  • Landscape: 768x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,width=device-width,height=device-height">

  • Portrait: 768x1024
  • Landscape: 1024x1024

With <meta name="viewport" content="initial-scale=1,user-scalable=no,maximum-scale=1,height=device-height">

  • Portrait: 831x1024
  • Landscape: 1520x1024

View tabular file such as CSV from command line

Tabview: lightweight python curses command line CSV file viewer (and also other tabular Python data, like a list of lists) is here on Github

Features:

  • Python 2.7+, 3.x
  • Unicode support
  • Spreadsheet-like view for easily visualizing tabular data
  • Vim-like navigation (h,j,k,l, g(top), G(bottom), 12G goto line 12, m - mark, ' - goto mark, etc.)
  • Toggle persistent header row
  • Dynamically resize column widths and gap
  • Sort ascending or descending by any column. 'Natural' order sort for numeric values.
  • Full-text search, n and p to cycle between search results
  • 'Enter' to view the full cell contents
  • Yank cell contents to clipboard
  • F1 or ? for keybindings
  • Can also use from python command line to visualize any tabular data (e.g. list-of-lists)

What is the difference between primary, unique and foreign key constraints, and indexes?

1)A primary key is a set of one or more attributes that uniquely identifies tuple within relation.

2)A foreign key is a set of attributes from a relation scheme which can be uniquely identify tuples fron another relation scheme.

How to make bootstrap 3 fluid layout without horizontal scrollbar

I also have it and while waiting on them to fix it, I added this shame css :

body { overflow-x: hidden;}

it's an horrible alternative, but it work. I'll be happy to remove it when they'll have fixed the issue.

An other alternative, as pointed out in the issue, is to override .row :

.row {
  margin-left: 0px;
  margin-right: 0px;
}

How to use BufferedReader in Java

As far as i understand fr is the object of your FileReadExample class. So it is obvious it will not have any method like fr.readLine() if you dont create one yourself.

secondly, i think a correct constructor of the BufferedReader class will help you do your task.

String str;
BufferedReader buffread = new BufferedReader(new FileReader(new File("file.dat")));
str = buffread.readLine();
.
.
buffread.close();

this should help you.

Php multiple delimiters in explode

Try about using:

$output = preg_split('/ (@|vs) /', $input);

How can I set a css border on one side only?

#testDiv{
    /* set green border independently on each side */
    border-left: solid green 2px;
    border-right: solid green 2px;
    border-bottom: solid green 2px;
    border-top: solid green 2px;
}

How to get file path in iPhone app

You need to use the URL for the link, such as this:

NSURL *path = [[NSBundle mainBundle] URLForResource:@"imagename" withExtension:@"jpg"];

It will give you a proper URL ref.

Add an object to an Array of a custom class

If you want to create a garage and fill it up with new cars that can be accessed later, use this code:

for (int i = 0; i < garage.length; i++)
     garage[i] = new Car("argument");

Also, the cars are later accessed using:

garage[0];
garage[1];
garage[2];
etc.

Retrieve all values from HashMap keys in an ArrayList Java

Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.

Map <String, Object> map;
List<Object> list = new ArrayList<Object>(map.values());

What are the dark corners of Vim your mom never told you about?

Mappings to make movements operate on the current screen line in wrap mode. I discovered this in a comment for a Vim tip some time ago, and it has proven quite handy.

function! ScreenMovement(movement)
  if &wrap
    return "g" . a:movement
  else
    return a:movement
  endif
endfunction
onoremap <silent> <expr> j ScreenMovement("j")
onoremap <silent> <expr> k ScreenMovement("k")
onoremap <silent> <expr> 0 ScreenMovement("0")
onoremap <silent> <expr> ^ ScreenMovement("^")
onoremap <silent> <expr> $ ScreenMovement("$")
nnoremap <silent> <expr> j ScreenMovement("j")
nnoremap <silent> <expr> k ScreenMovement("k")
nnoremap <silent> <expr> 0 ScreenMovement("0")
nnoremap <silent> <expr> ^ ScreenMovement("^")
nnoremap <silent> <expr> $ ScreenMovement("$")

What's the difference between IFrame and Frame?

While the security is the same, it may be easier for fraudulent applications to dupe users using an iframe since they have more flexibility regarding where the frame is placed.

android View not attached to window manager

Above solution didn't work for me. So what I did is take ProgressDialog as globally and then add this to my activity

@Override
    protected void onDestroy() {
        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
        super.onDestroy();
    }

so that in case if activity is destroyed then the ProgressDialog will also be destroy.

Search for a particular string in Oracle clob column

select *  
from TABLE_NAME
where dbms_lob.instr(COLUMNNAME,'searchtext') > 0;

Git mergetool generates unwanted .orig files

Or just add

*.orig

to your global gitignore

How to close a Java Swing application from the code

I guess a EXIT_ON_CLOSE

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

before System.exit(0) is better since you can write a Window Listener to make some cleaning operations before actually leaving the app.

That window listener allows you to defined:

public void windowClosing(WindowEvent e) {
    displayMessage("WindowListener method called: windowClosing.");
    //A pause so user can see the message before
    //the window actually closes.
    ActionListener task = new ActionListener() {
        boolean alreadyDisposed = false;
        public void actionPerformed(ActionEvent e) {
            if (frame.isDisplayable()) {
                alreadyDisposed = true;
                frame.dispose();
            }
        }
    };
    Timer timer = new Timer(500, task); //fire every half second
    timer.setInitialDelay(2000);        //first delay 2 seconds
    timer.setRepeats(false);
    timer.start();
}

public void windowClosed(WindowEvent e) {
    //This will only be seen on standard output.
    displayMessage("WindowListener method called: windowClosed.");
}

Using Bootstrap Modal window as PartialView

I have achieved this by using one nice example i have found here. I have replaced the jquery dialog used in that example with the Twitter Bootstrap Modal windows.

Read XML Attribute using XmlDocument

Assuming your example document is in the string variable doc

> XDocument.Parse(doc).Root.Attribute("SuperNumber")
1

How to add "Maven Managed Dependencies" library in build path eclipse?

If you have removed Maven dependency from Library accidentally. Add below in pom.xml

<build>     
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.3</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
</build>

Getting time elapsed in Objective-C

The other answers are correct (with a caveat*). I add this answer simply to show an example usage:

- (void)getYourAffairsInOrder
{
    NSDate* methodStart = [NSDate date];  // Capture start time.

    // … Do some work …

    NSLog(@"DEBUG Method %s ran. Elapsed: %f seconds.", __func__, -([methodStart timeIntervalSinceNow]));  // Calculate and report elapsed time.
}

On the debugger console, you see something like this:

DEBUG Method '-[XMAppDelegate getYourAffairsInOrder]' ran. Elapsed: 0.033827 seconds.

*Caveat: As others mentioned, use NSDate to calculate elapsed time only for casual purposes. One such purpose might be common testing, crude profiling, where you just want a rough idea of how long a method is taking.

The risk is that the device's clock's current time setting could change at any moment because of network clock syncing. So NSDate time could jump forward or backward at any moment.

#pragma mark in Swift?

Xcode 8 now handles it as followed and shows up like this in the method dropdown:

enter image description here

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

(Basically what @user3464070 already said)

For Mac:

cd ~/Library/Android/sdk
# download latest tools
curl -O https://dl.google.com/android/repository/tools_r25.2.3-macosx.zip
# overwrite existing tools folder without prompting
unzip -o tools_r25.2.3-macosx.zip
# clean up
rm tools_r25.2.3-macosx.zip

What's "tools:context" in Android layout files?

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    //more views

</androidx.constraintlayout.widget.ConstraintLayout>

In the above code, the basic need of tools:context is to tell which activity or fragment the layout file is associated with by default. So, you can specify the activity class name using the same dot prefix as used in Manifest file.

By doing so, the Android Studio will choose the necessary theme for the preview automatically and you don’t have to do the preview settings manually. As we all know that a layout file can be associated with several activities but the themes are defined in the Manifest file and these themes are associated with your activity. So, by adding tools:context in your layout file, the Android Studio preview will automatically choose the necessary theme for you.

What is parsing in terms that a new programmer would understand?

Simple explanation: Parsing is breaking a block of data into smaller pieces (tokens) by following a set of rules (using delimiters for example), so that this data could be processes piece by piece (managed, analysed, interpreted, transmitted, ets).

Examples: Many applications (like Spreadsheet programs) use CSV (Comma Separated Values) file format to import and export data. CSV format makes it possible for the applications to process this data with a help of a special parser. Web browsers have special parsers for HTML and CSS files. JSON parsers exist. All special file formats must have some parsers designed specifically for them.

Convert the first element of an array to a string in PHP

If your goal is output your array to a string for debbuging: you can use the print_r() function, which receives an expression parameter (your array), and an optional boolean return parameter. Normally the function is used to echo the array, but if you set the return parameter as true, it will return the array impression.

Example:

    //We create a 2-dimension Array as an example
    $ProductsArray = array();

    $row_array['Qty'] = 20;
    $row_array['Product'] = "Cars";

    array_push($ProductsArray,$row_array);

    $row_array2['Qty'] = 30;
    $row_array2['Product'] = "Wheels";

    array_push($ProductsArray,$row_array2);

    //We save the Array impression into a variable using the print_r function
    $ArrayString = print_r($ProductsArray, 1);

    //You can echo the string
    echo $ArrayString;

    //or Log the string into a Log file
    $date = date("Y-m-d H:i:s", time());
    $LogFile = "Log.txt";
    $fh = fopen($LogFile, 'a') or die("can't open file");
    $stringData = "--".$date."\n".$ArrayString."\n";
    fwrite($fh, $stringData);
    fclose($fh);

This will be the output:

Array
(
    [0] => Array
        (
            [Qty] => 20
            [Product] => Cars
        )

    [1] => Array
        (
            [Qty] => 30
            [Product] => Wheels
        )

)

MySQL DELETE FROM with subquery as condition

You need to refer to the alias again in the delete statement, like:

DELETE th FROM term_hierarchy AS th
....

As outlined here in MySQL docs.

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Time::Piece::datetime() can eliminate T.

use Time::Piece;
print localtime->datetime(T => q{ });

How do I measure separate CPU core usage for a process?

dstat -C 0,1,2,3 

Will also give you the CPU usage of first 4 cores. Of course, if you have 32 cores then this command gets a little bit longer but useful if you only interested in few cores.

For example, if you only interested in core 3 and 7 then you could do

dstat -C 3,7

Moving x-axis to the top of a plot in matplotlib

tick_params is very useful for setting tick properties. Labels can be moved to the top with:

    ax.tick_params(labelbottom=False,labeltop=True)

How to generate unique IDs for form labels in React?

The id should be placed inside of componentWillMount (update for 2018) constructor, not render. Putting it in render will re-generate new ids unnecessarily.

If you're using underscore or lodash, there is a uniqueId function, so your resulting code should be something like:

constructor(props) {
    super(props);
    this.id = _.uniqueId("prefix-");
}

render() { 
  const id = this.id;
  return (
    <div>
        <input id={id} type="checkbox" />
        <label htmlFor={id}>label</label>
    </div>
  );
}

2019 Hooks update:

import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';

const MyComponent = (props) => {
  // id will be set once when the component initially renders, but never again
  // (unless you assigned and called the second argument of the tuple)
  const [id] = useState(_uniqueId('prefix-'));
  return (
    <div>
      <input id={id} type="checkbox" />
      <label htmlFor={id}>label</label>
    </div>
  );
}

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

Had to install the wheel package. Everything was up to date but still giving the error.

pip install wheel

then

python setup.py bdist_wheel 

Worked without issues.

Move / Copy File Operations in Java

Not yet, but the New NIO (JSR 203) will have support for these common operations.

In the meantime, there are a few things to keep in mind.

File.renameTo generally works only on the same file system volume. I think of this as the equivalent to a "mv" command. Use it if you can, but for general copy and move support, you'll need to have a fallback.

When a rename doesn't work you will need to actually copy the file (deleting the original with File.delete if it's a "move" operation). To do this with the greatest efficiency, use the FileChannel.transferTo or FileChannel.transferFrom methods. The implementation is platform specific, but in general, when copying from one file to another, implementations avoid transporting data back and forth between kernel and user space, yielding a big boost in efficiency.

Is it possible to make abstract classes in Python?

Just a quick addition to @TimGilbert's old-school answer...you can make your abstract base class's init() method throw an exception and that would prevent it from being instantiated, no?

>>> class Abstract(object):
...     def __init__(self):
...         raise NotImplementedError("You can't instantiate this class!")
...
>>> a = Abstract()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
NotImplementedError: You can't instantiate this class! 

ORA-00932: inconsistent datatypes: expected - got CLOB

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

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

How to debug Ruby scripts

printf debugging

There has always been a controversy around debugging techniques, some people like to debug by print statements, some other ones like to dig deep with a debugger.

I'd suggest that you try both approaches.

Actually one of the old Unix men recently said, that printf debugging was a faster way to go for him at some points.

But if you are new at some job and need to understand a big blob of code, then it's really usefull to step throughout there, putting some breakpoints here and there, going along with it how it works.

It should give you some understanding how the code is weaved.

If you are new to some other peoples software, It might help you to step through there.

You'll quickly find out if they arranged it in a clever way, or if that's just a bunch of shit.

How to display a jpg file in Python?

from PIL import Image

image = Image.open('File.jpg')
image.show()

pycharm convert tabs to spaces automatically

For me it was having a file called ~/.editorconfig that was overriding my tab settings. I removed that (surely that will bite me again someday) but it fixed my pycharm issue

Reading/Writing a MS Word file in PHP

Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.

You could use the Microsoft Office XML formats for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.

The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to OpenXML. As databyss pointed out here the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on MSDN regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.

Perhaps you can have a look at PHPExcel which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.

:: (double colon) operator in Java 8

It seems its little late but here are my two cents. A lambda expression is used to create anonymous methods. It does nothing but call an existing method, but it is clearer to refer to the method directly by its name. And method reference enables us to do that using method-reference operator :: .

Consider the following simple class where each employee has a name and grade.

public class Employee {
    private String name;
    private String grade;

    public Employee(String name, String grade) {
        this.name = name;
        this.grade = grade;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }
}

Suppose we have a list of employees returned by some method and we want to sort the employees by their grade. We know we can make use of anonymous class as:

    List<Employee> employeeList = getDummyEmployees();

    // Using anonymous class
    employeeList.sort(new Comparator<Employee>() {
           @Override
           public int compare(Employee e1, Employee e2) {
               return e1.getGrade().compareTo(e2.getGrade());
           }
    });

where getDummyEmployee() is some method as:

private static List<Employee> getDummyEmployees() {
        return Arrays.asList(new Employee("Carrie", "C"),
                new Employee("Fanishwar", "F"),
                new Employee("Brian", "B"),
                new Employee("Donald", "D"),
                new Employee("Adam", "A"),
                new Employee("Evan", "E")
                );
    }

Now we know that Comparator is a Functional Interface. A Functional Interface is the one with exactly one abstract method (though it may contain one or more default or static methods). Lambda expression provides implementation of @FunctionalInterface so a functional interface can have only one abstract method. We can use lambda expression as:

employeeList.sort((e1,e2) -> e1.getGrade().compareTo(e2.getGrade())); // lambda exp

It seems all good but what if the class Employee also provides similar method:

public class Employee {
    private String name;
    private String grade;
    // getter and setter
    public static int compareByGrade(Employee e1, Employee e2) {
        return e1.grade.compareTo(e2.grade);
    }
}

In this case using the method name itself will be more clear. Hence we can directly refer to method by using method reference as:

employeeList.sort(Employee::compareByGrade); // method reference

As per docs there are four kinds of method references:

+----+-------------------------------------------------------+--------------------------------------+
|    | Kind                                                  | Example                              |
+----+-------------------------------------------------------+--------------------------------------+
| 1  | Reference to a static method                          | ContainingClass::staticMethodName    |
+----+-------------------------------------------------------+--------------------------------------+
| 2  |Reference to an instance method of a particular object | containingObject::instanceMethodName | 
+----+-------------------------------------------------------+--------------------------------------+
| 3  | Reference to an instance method of an arbitrary object| ContainingType::methodName           |
|    | of a particular type                                  |                                      |  
+----+-------------------------------------------------------+--------------------------------------+
| 4  |Reference to a constructor                             | ClassName::new                       |
+------------------------------------------------------------+--------------------------------------+

Docker Compose wait for container X before starting Y

restart: on-failure did the trick for me..see below

---
version: '2.1'
services:
  consumer:
    image: golang:alpine
    volumes:
      - ./:/go/src/srv-consumer
    working_dir: /go/src/srv-consumer
    environment:
      AMQP_DSN: "amqp://guest:guest@rabbitmq:5672"
    command: go run cmd/main.go
    links:
          - rabbitmq
    restart: on-failure

  rabbitmq:
    image: rabbitmq:3.7-management-alpine
    ports:
      - "15672:15672"
      - "5672:5672"

Is there a way to check which CSS styles are being used or not used on a web page?

I'm using CSS Dig. It is made for chrome, but I think it is a great tool!

Difference between Xms and Xmx and XX:MaxPermSize

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

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

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

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

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

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Using Python, how can I access a shared folder on windows network?

I had the same issue as OP but none of the current answers solved my issue so to add a slightly different answer that did work for me:

Running Python 3.6.5 on a Windows Machine, I used the format

r"\DriveName\then\file\path\txt.md"

so the combination of double backslashes from reading @Johnsyweb UNC link and adding the r in front as recommended solved my similar to OP's issue.

Reading a binary input stream into a single byte array in Java

You can read it by chunks (byte buffer[] = new byte[2048]) and write the chunks to a ByteArrayOutputStream. From the ByteArrayOutputStream you can retrieve the contents as a byte[], without needing to determine its size beforehand.

SQL Server: use CASE with LIKE

One of the first things you need to learn about SQL (and relational databases) is that you shouldn't store multiple values in a single field.

You should create another table and store one value per row.

This will make your querying easier, and your database structure better.

select 
    case when exists (select countryname from itemcountries where yourtable.id=itemcountries.id and countryname = @country) then 'national' else 'regional' end
from yourtable

How to change values in a tuple?

You can change the value of tuple using copy by reference

>>> tuple1=[20,30,40]

>>> tuple2=tuple1

>>> tuple2
    [20, 30, 40]

>>> tuple2[1]=10

>>> print(tuple2)
    [20, 10, 40]

>>> print(tuple1)
    [20, 10, 40]

Iterate through string array in Java

If you are looking for performance and the order of iteration is not relevant, you can iterate using an optimized reverse loop:

int elemLength = elements.length;
if(elemLength < 2){
  // avoid ArrayIndexOutOfBoundsException ...
} else {
  String elem1, elem2;
  for(int i = elemLength -1; --i >= 0;) {
    elem1 = elements[i];
    elem2 = elements[i+1];
    // do whatever you want with those two strings
  }
}

In such a way you are retrieving the length of the array once, then decrementing the index and comparing with zero in a single operation. Comparing with zero is a very fast operation, often optimized by many architectures (easier / faster than comparing to the length of the array).

Most simple code to populate JTable from ResultSet

This is my approach:

String[] columnNames = {"id", "Nome", "Sobrenome","Email"};

List<Student> students = _repo.getAll();

Object[][] data = new Object[students.size()][4];

int index = 0;
for(Student s : students) {
    data[index][0] = s.getId();
    data[index][1] = s.getFirstName();
    data[index][2] = s.getLastName();
    data[index][3] = s.getEmail();
    index++;
}

DefaultTableModel model = new DefaultTableModel(data, columnNames);

table = new JTable(model);

Appending a list to a list of lists in R

There are two other solutions which involve assigning to an index one past the end of the list. Here is a solution that does use append.

resultsa <- list(1,2,3,4,5)
resultsb <- list(6,7,8,9,10)
resultsc <- list(11,12,13,14,15)

outlist <- list(resultsa)
outlist <- append(outlist, list(resultsb))
outlist <- append(outlist, list(resultsc))

which gives your requested format

> str(outlist)
List of 3
 $ :List of 5
  ..$ : num 1
  ..$ : num 2
  ..$ : num 3
  ..$ : num 4
  ..$ : num 5
 $ :List of 5
  ..$ : num 6
  ..$ : num 7
  ..$ : num 8
  ..$ : num 9
  ..$ : num 10
 $ :List of 5
  ..$ : num 11
  ..$ : num 12
  ..$ : num 13
  ..$ : num 14
  ..$ : num 15

How can I get the assembly file version

There are three versions: assembly, file, and product. They are used by different features and take on different default values if you don't explicit specify them.

string assemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString(); 
string assemblyVersion = Assembly.LoadFile("your assembly file").GetName().Version.ToString(); 
string fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion; 
string productVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

Filter array to have unique values

_x000D_
_x000D_
arr = ["I", "do", "love", "JavaScript", "and", "I", "also", "do", "love", "Java"];_x000D_
_x000D_
uniqueArr = [... new Set(arr)];_x000D_
_x000D_
// or_x000D_
_x000D_
reallyUniqueArr = arr.filter((item, pos, ar) => ar.indexOf(item) === pos)_x000D_
_x000D_
console.log(`${uniqueArr}\n${reallyUniqueArr}`)
_x000D_
_x000D_
_x000D_

How to make an Android device vibrate? with different frequency?

Use this:

import android.os.Vibrator;
     ...
     Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
     // Vibrate for 1000 milliseconds
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            v.vibrate(VibrationEffect.createOneShot(1000,VibrationEffect.DEFAULT_AMPLITUDE));
     }else{
     //deprecated in API 26 
            v.vibrate(1000);
     }

Note:

Don't forget to include permission in AndroidManifest.xml file:

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

How to start and stop android service from a adb shell?

Responding to pzulw's feedback to sandroid about specifying the intent.

The format of the component name is described in the api docs for ComponentName.unflattenFromString

It splits the string at the first '/', taking the part before as the package name and the part after as the class name. As a special convenience (to use, for example, when parsing component names on the command line), if the '/' is immediately followed by a '.' then the final class name will be the concatenation of the package name with the string following the '/'. Thus "com.foo/.Blah" becomes package="com.foo" class="com.foo.Blah".

Angular 2 Sibling Component Communication

Shared service is a good solution for this issue. If you want to store some activity information too, you can add Shared Service to your main modules (app.module) provider list.

@NgModule({
    imports: [
        ...
    ],
    bootstrap: [
        AppComponent
    ],
    declarations: [
        AppComponent,
    ],
    providers: [
        SharedService,
        ...
    ]
});

Then you can directly provide it to your components,

constructor(private sharedService: SharedService)
 

With Shared Service you can either use functions or you can create a Subject to update multiple places at once.

@Injectable()
export class SharedService {
    public clickedItemInformation: Subject<string> = new Subject(); 
}

In your list component you can publish clicked item information,

this.sharedService.clikedItemInformation.next("something");

and then you can fetch this information at your detail component:

this.sharedService.clikedItemInformation.subscribe((information) => {
    // do something
});

Obviously, the data that list component shares can be anything. Hope this helps.

Adb over wireless without usb cable at all for not rooted phones

This might help:

If the adb connection is ever lost:

Make sure that your host is still connected to the same Wi-Fi network your Android device is. Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.) Or if that doesn't work, reset your adb host: adb kill-server and then start over from the beginning.

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

A tricky way is add an empty section for header. Because section has no cell, it will not floating at all.

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

I found the error because i was new to git you must check whether you have entered the correct syntax

i made a mistake and wrote git commit

and got the same error

use git commit -m 'some comment'

and you wont be seeing the page with

C++ string to double conversion

#include <iostream>
#include <string>
using namespace std;

int main()
{
    cout << stod("  99.999  ") << endl;
}

Output: 99.999 (which is double, whitespace was automatically stripped)

Since C++11 converting string to floating-point values (like double) is available with functions:
stof - convert str to a float
stod - convert str to a double
stold - convert str to a long double

As conversion of string to int was also mentioned in the question, there are the following functions in C++11:
stoi - convert str to an int
stol - convert str to a long
stoul - convert str to an unsigned long
stoll - convert str to a long long
stoull - convert str to an unsigned long long

Powershell script does not run via Scheduled Tasks

In my case (the same problem) helped to add -NoProfile in task action command arguments and check checkbox "Run with highest privileges", because on my server UAC is on (active).

More info about it enter link description here

How do I do word Stemming or Lemmatization?

The top python packages (in no specific order) for lemmatization are: spacy, nltk, gensim, pattern, CoreNLP and TextBlob. I prefer spaCy and gensim's implementation (based on pattern) because they identify the POS tag of the word and assigns the appropriate lemma automatically. The gives more relevant lemmas, keeping the meaning intact.

If you plan to use nltk or TextBlob, you need to take care of finding the right POS tag manually and the find the right lemma.

Lemmatization Example with spaCy:

# Run below statements in terminal once. 
pip install spacy
spacy download en

import spacy

# Initialize spacy 'en' model
nlp = spacy.load('en', disable=['parser', 'ner'])

sentence = "The striped bats are hanging on their feet for best"

# Parse
doc = nlp(sentence)

# Extract the lemma
" ".join([token.lemma_ for token in doc])
#> 'the strip bat be hang on -PRON- foot for good'

Lemmatization Example With Gensim:

from gensim.utils import lemmatize
sentence = "The striped bats were hanging on their feet and ate best fishes"
lemmatized_out = [wd.decode('utf-8').split('/')[0] for wd in lemmatize(sentence)]
#> ['striped', 'bat', 'be', 'hang', 'foot', 'eat', 'best', 'fish']

The above examples were borrowed from in this lemmatization page.

How to find the cumulative sum of numbers in a list?

There could be many answers for this depending on the length of the list and the performance. One very simple way which I can think without thinking of the performance is this:

a = [1, 2, 3, 4]
a = [sum(a[0:x:1]) for x in range(len(a)+1)][1:]
print(a)

[1, 3, 6, 10]

This is by using list comprehension and this may work fairly well it is just that here I am adding over the subarray many times, you could possibly improvise on this and make it simple!

Cheers to your endeavor!

How to configure Visual Studio to use Beyond Compare

I use BC3 for my git diff, but I'd also add vscode to the list of useful git diff tools. Some users prefer vscode over vs ide experience.

Using VS Code for Git Diff

git config --global diff.tool vscode
git config --global difftool.vscode.cmd "code --wait --diff $LOCAL $REMOTE"

Python Requests throwing SSLError

If the request calls are buried somewhere deep in the code and you do not want to install the server certificate, then, just for debug purposes only, it's possible to monkeypatch requests:

import requests.api
import warnings


def requestspatch(method, url, **kwargs):
    kwargs['verify'] = False
    return _origcall(method, url, **kwargs)

_origcall = requests.api.request
requests.api.request = requestspatch
warnings.warn('Patched requests: SSL verification disabled!')

Never use in production!

How can I sort a std::map first by value, then by key?

std::map already sorts the values using a predicate you define or std::less if you don't provide one. std::set will also store items in order of the of a define comparator. However neither set nor map allow you to have multiple keys. I would suggest defining a std::map<int,std::set<string> if you want to accomplish this using your data structure alone. You should also realize that std::less for string will sort lexicographically not alphabetically.

What's the difference between <b> and <strong>, <i> and <em>?

As the others have stated, the difference is that <b> and <i> hardcode font styles, whereas <strong> and <em> dictate semantic meaning, with the font style (or speaking browser intonation, or what-have-you) to be determined at the time the text is rendered (or spoken).

You can think of this as a difference between a “physical” font style and a “logical” style, if you will. At some later time, you may wish to change the way <strong> and <em> text are displayed, say, by altering properties in a style sheet to add color and size changes, or even to use different font faces entirely. If you've used “logical” markup instead of hardcoded “physical” markup, then you can simply change the display properties in one place each in your style sheet, and then all of the pages that reference that style sheet get changed automatically, without ever having to edit them.

Pretty slick, huh?

This is also the rationale behind defining sub-styles (referenced using the style= property in text tags) for paragraphs, table cells, header text, captions, etc., and using <div> tags. You can define physical representation for your logical styles in the style sheet, and the changes are automatically reflected in the web pages that reference that style sheet. Want a different representation for source code? Redefine the font, size, weight, spacing, etc. for your "code" style.

If you use XHTML, you can even define your own semantic tags, and your style sheet would do the conversions to physical font styles and layouts for you.

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

How to draw rounded rectangle in Android UI?

In your layout xml do the following:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">

    <solid android:color="@android:color/holo_red_dark" />

    <corners android:radius="32dp" />

</shape>

By changing the android:radius you can change the amount of "radius" of the corners.

<solid> is used to define the color of the drawable.

You can use replace android:radius with android:bottomLeftRadius, android:bottomRightRadius, android:topLeftRadius and android:topRightRadius to define radius for each corner.

How can I generate UUID in C#

Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid parts.

If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray() and encode it. You'll need to Array.Reverse the first three parts (Data1-3).

I do it this way:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

See this answer for the specific .NET implementation details.

Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray().

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

I also had the same problem. I use "Postman" for JSON request. The code itself is not wrong. I simply set the content type to JSON (application/json) and it worked, as you can see on the image below

My Code

How to check if a column exists in Pandas

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

MySQL "WITH" clause

MariaDB is now supporting WITH. MySQL for now is not. https://mariadb.com/kb/en/mariadb/with/

How to overwrite the output directory in spark

since df.save(path, source, mode) is deprecated, (http://spark.apache.org/docs/1.5.0/api/scala/index.html#org.apache.spark.sql.DataFrame)

use df.write.format(source).mode("overwrite").save(path)
where df.write is DataFrameWriter

'source' can be ("com.databricks.spark.avro" | "parquet" | "json")

django change default runserver port

This is an old post but for those who are interested:

If you want to change the default port number so when you run the "runserver" command you start with your preferred port do this:

  1. Find your python installation. (you can have multiple pythons installed and you can have your virtual environment version as well so make sure you find the right one)
  2. Inside the python folder locate the site-packages folder. Inside that you will find your django installation
  3. Open the django folder-> core -> management -> commands
  4. Inside the commands folder open up the runserver.py script with a text editor
  5. Find the DEFAULT_PORT field. it is equal to 8000 by default. Change it to whatever you like DEFAULT_PORT = "8080"
  6. Restart your server: python manage.py runserver and see that it uses your set port number

It works with python 2.7 but it should work with newer versions of python as well. Good luck

Custom HTTP headers : naming conventions

Modifying, or more correctly, adding additional HTTP headers is a great code debugging tool if nothing else.

When a URL request returns a redirect or an image there is no html "page" to temporarily write the results of debug code to - at least not one that is visible in a browser.

One approach is to write the data to a local log file and view that file later. Another is to temporarily add HTTP headers reflecting the data and variables being debugged.

I regularly add extra HTTP headers like X-fubar-somevar: or X-testing-someresult: to test things out - and have found a lot of bugs that would have otherwise been very difficult to trace.

How to check if a textbox is empty using javascript

<pre><form name="myform"  method="post" enctype="multipart/form-data">
    <input type="text"   id="name"   name="name" /> 
<input type="submit"/>
</form></pre>

<script language="JavaScript" type="text/javascript">
 var frmvalidator  = new Validator("myform");
    frmvalidator.EnableFocusOnError(false); 
    frmvalidator.EnableMsgsTogether(); 
    frmvalidator.addValidation("name","req","Plese Enter Name"); 

</script>

Note: before using the code above you have to add the gen_validatorv31.js file.

Change Twitter Bootstrap Tooltip content on click

I couldn't get any of the answers working, here's a workaround:

$('#'+$(element).attr('aria-describedby')+' .tooltip-inner').html(newTitle);

How I can print to stderr in C?

Some examples of formatted output to stdout and stderr:

printf("%s", "Hello world\n");              // "Hello world" on stdout (using printf)
fprintf(stdout, "%s", "Hello world\n");     // "Hello world" on stdout (using fprintf)
fprintf(stderr, "%s", "Stack overflow!\n"); // Error message on stderr (using fprintf)

Creating a system overlay window (always on top)

This is an old Question but recently Android has a support for Bubbles. Bubbles are soon going to be launched but currently developers can start using them.They are designed to be an alternative to using SYSTEM_ALERT_WINDOW. Apps like (Facebook Messenger and MusiXMatch use the same concept).

Bubbles

Bubbles are created via the Notification API, you send your notification as normal. If you want it to bubble you need to attach some extra data to it. For more information about Bubbles you can go to the official Android Developer Guide on Bubbles.

Visual C++: How to disable specific linker warnings?

For the benefit of others, I though I'd include what I did.

Since you cannot get Visual Studio (2010 in my case) to ignore the LNK4204 warnings, my approach was to give it what it wanted: the pdb files. As I was using open source libraries in my case, I have the code building the pdb files already.

BUT, the default is to name all of the PDF files the same thing: vc100.pdb in my case. As you need a .pdb for each and every .lib, this creates a problem, especially if you are using something like ImageMagik, which creates about 20 static .lib files. You cannot have 20 lib files in one directory (which your application's linker references to link in the libraries from) and have all the 20 .pdb files called the same thing.

My solution was to go and rebuild my static library files, and configure VS2010 to name the .pdb file with respect to the PROJECT. This way, each .lib gets a similarly named .pdb, and you can put all of the LIBs and PDBs in one directory for your project to use.

So for the "Debug" configuraton, I edited:

Properties->Configuration Properties -> C/C++ -> Output Files -> Program Database File Name from

$(IntDir)vc$(PlatformToolsetVersion).pdb

to be the following value:

$(OutDir)vc$(PlatformToolsetVersion)D$(ProjectName).pdb

Now rather than somewhere in the intermediate directory, the .pdb files are written to the output directory, where the .lib files are also being written, AND most importantly, they are named with a suffix of D+project name. This means each library project produduces a project .lib and a project specific .pdb.

I'm now able to copy all of my release .lib files, my debug .lib files and the debug .pdb files into one place on my development system, and the project that uses that 3rd party library in debug mode, has the pdb files it needs in debug mode.

How to implement a queue using two stacks?

Two stacks in the queue are defined as stack1 and stack2.

Enqueue: The euqueued elements are always pushed into stack1

Dequeue: The top of stack2 can be popped out since it is the first element inserted into queue when stack2 is not empty. When stack2 is empty, we pop all elements from stack1 and push them into stack2 one by one. The first element in a queue is pushed into the bottom of stack1. It can be popped out directly after popping and pushing operations since it is on the top of stack2.

The following is same C++ sample code:

template <typename T> class CQueue
{
public:
    CQueue(void);
    ~CQueue(void);

    void appendTail(const T& node); 
    T deleteHead();                 

private:
    stack<T> stack1;
    stack<T> stack2;
};

template<typename T> void CQueue<T>::appendTail(const T& element) {
    stack1.push(element);
} 

template<typename T> T CQueue<T>::deleteHead() {
    if(stack2.size()<= 0) {
        while(stack1.size()>0) {
            T& data = stack1.top();
            stack1.pop();
            stack2.push(data);
        }
    }


    if(stack2.size() == 0)
        throw new exception("queue is empty");


    T head = stack2.top();
    stack2.pop();


    return head;
}

This solution is borrowed from my blog. More detailed analysis with step-by-step operation simulations is available in my blog webpage.

StringUtils.isBlank() vs String.isEmpty()

The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,

StringUtils.isBlank()

 StringUtils.isBlank(null)      = true
 StringUtils.isBlank("")        = true  
 StringUtils.isBlank(" ")       = true  
 StringUtils.isBlank("bob")     = false  
 StringUtils.isBlank("  bob  ") = false

StringUtils.isEmpty

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true  
 StringUtils.isEmpty(" ")       = false  
 StringUtils.isEmpty("bob")     = false  
 StringUtils.isEmpty("  bob  ") = false

How to detect if multiple keys are pressed at once using JavaScript?

case 65: //A
jp = 1;
setTimeout("jp = 0;", 100);

if(pj > 0) {
ABFunction();
pj = 0;
}
break;

case 66: //B
pj = 1;
setTimeout("pj = 0;", 100);

if(jp > 0) {
ABFunction();
jp = 0;
}
break;

Not the best way, I know.

How to load a jar file at runtime

I was asked to build a java system that will have the ability to load new code while running

You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.

Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,

Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.

Add Relations Tab - SQL Server Compact Tool Box

How to close a window using jQuery

This will only work for windows which are opened by using window.open(); method. Try this

var tmp=window.open(params);
tmp.close();

Eclipse error: "The import XXX cannot be resolved"

I solved this problem using the JPA JAR from Maven repository, adding it on the build path of project.

Java String.split() Regex

You could split on a word boundary with \b

Form Google Maps URL that searches for a specific places near specific coordinates

Yeah, I had the same question for a long time and I found the perfect one. Here are some parameters from it.

https://maps.google.com/?parameter=value



q=

Used to specify the search query in Google maps search.
eg :

https://maps.google.com/?q=newyork or
https://maps.google.com/?q=51.03841,-114.01679

near=

Used to specify the location instead of putting it into q. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if q is a business or suchlike.

z=

Zoom level. Can be set 19 normally, but in certain cases can go up to 23.

ll=

Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.

sll=

Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.

t=

Sets the kind of map shown. Can be set to:

m – normal  map
k – satellite
h – hybrid
p – terrain

saddr=

Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.

daddr=

Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.

via=

Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.

doflg=

Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.

msa=

Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.

reference : http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

Relative instead of Absolute paths in Excel VBA

You could use one of these for the relative path root:

ActiveWorkbook.Path
ThisWorkbook.Path
App.Path

Android soft keyboard covers EditText field

Why not try to add a ScrollView to wrap whatever it is you want to scroll. Here is how I have done it, where I actually leave a header on top which does not scroll, while the dialog widgets (in particular the EditTexts) scroll when you open soft keypad.

<LinearLayout android:id="@+id/HeaderLayout" >
  <!-- Here add a header or whatever will not be scrolled. -->
</LinearLayout>
<ScrollView android:id="@+id/MainForm" >
  <!-- Here add your edittexts or whatever will scroll. -->
</ScrollView>

I would typically have a LinearLayout inside the ScrollView, but that is up to you. Also, setting Scrollbar style to outsideInset helps, at least on my devices.

Angular, content type is not being sent with $http

You need to include a body with the request. Angular removes the content-type header otherwise.

Add data: '' to the argument to $http.

Build error: "The process cannot access the file because it is being used by another process"

For those who are developing in VS with Docker, restart the docker for windows service and the problem will be solved immediately.

Before restarting docker I tried all the mentioned answers, didn't find a msbuild.exe process running, also tried restarting VS without avail, only restarting docker worked.

How can two strings be concatenated?

glue is a new function, data class, and package that has been developed as part of the tidyverse, with a lot of extended functionality. It combines features from paste, sprintf, and the previous other answers.

tmp <- tibble::tibble(firststring = "GAD", secondstring = "AB")
(tmp_new <- glue::glue_data(tmp, "{firststring},{secondstring}"))
#> GAD,AB

Created on 2019-03-06 by the reprex package (v0.2.1)

Yes, it's overkill for the simple example in this question, but powerful for many situations. (see https://glue.tidyverse.org/)

Quick example compared to paste with with below. The glue code was a bit easier to type and looks a bit easier to read.

tmp <- tibble::tibble(firststring = c("GAD", "GAD2", "GAD3"), secondstring = c("AB1", "AB2", "AB3"))
(tmp_new <- glue::glue_data(tmp, "{firststring} and {secondstring} went to the park for a walk. {firststring} forgot his keys."))
#> GAD and AB1 went to the park for a walk. GAD forgot his keys.
#> GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys.
#> GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys.
(with(tmp, paste(firststring, "and", secondstring, "went to the park for a walk.", firststring, "forgot his keys.")))
#> [1] "GAD and AB1 went to the park for a walk. GAD forgot his keys."  
#> [2] "GAD2 and AB2 went to the park for a walk. GAD2 forgot his keys."
#> [3] "GAD3 and AB3 went to the park for a walk. GAD3 forgot his keys."

Created on 2019-03-06 by the reprex package (v0.2.1)

How do I get the current username in .NET using C#?

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

What is the "N+1 selects problem" in ORM (Object-Relational Mapping)?

I can't comment directly on other answers, because I don't have enough reputation. But it's worth noting that the problem essentially only arises because, historically, a lot of dbms have been quite poor when it comes to handling joins (MySQL being a particularly noteworthy example). So n+1 has, often, been notably faster than a join. And then there are ways to improve on n+1 but still without needing a join, which is what the original problem relates to.

However, MySQL is now a lot better than it used to be when it comes to joins. When I first learned MySQL, I used joins a lot. Then I discovered how slow they are, and switched to n+1 in the code instead. But, recently, I've been moving back to joins, because MySQL is now a heck of a lot better at handling them than it was when I first started using it.

These days, a simple join on a properly indexed set of tables is rarely a problem, in performance terms. And if it does give a performance hit, then the use of index hints often solves them.

This is discussed here by one of the MySQL development team:

http://jorgenloland.blogspot.co.uk/2013/02/dbt-3-q3-6-x-performance-in-mysql-5610.html

So the summary is: If you've been avoiding joins in the past because of MySQL's abysmal performance with them, then try again on the latest versions. You'll probably be pleasantly surprised.

Create pandas Dataframe by appending one row at a time

You can use generator object to create Dataframe, which will be more memory efficient over the list.

num = 10

# Generator function to generate generator object
def numgen_func(num):
    for i in range(num):
        yield ('name_{}'.format(i), (i*i), (i*i*i))

# Generator expression to generate generator object (Only once data get populated, can not be re used)
numgen_expression = (('name_{}'.format(i), (i*i), (i*i*i)) for i in range(num) )

df = pd.DataFrame(data=numgen_func(num), columns=('lib', 'qty1', 'qty2'))

To add raw to existing DataFrame you can use append method.

df = df.append([{ 'lib': "name_20", 'qty1': 20, 'qty2': 400  }])

How to drop a list of rows from Pandas dataframe?

Consider an example dataframe

df =     
index    column1
0           00
1           10
2           20
3           30

we want to drop 2nd and 3rd index rows.

Approach 1:

df = df.drop(df.index[2,3])
 or 
df.drop(df.index[2,3],inplace=True)
print(df)

df =     
index    column1
0           00
3           30

 #This approach removes the rows as we wanted but the index remains unordered

Approach 2

df.drop(df.index[2,3],inplace=True,ignore_index=True)
print(df)
df =     
index    column1
0           00
1           30
#This approach removes the rows as we wanted and resets the index. 

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

No REAL easy way to do this. Lots of ideas out there, though.

Best one I've found:

SELECT table_name, LEFT(column_names , LEN(column_names )-1) AS column_names
FROM information_schema.columns AS extern
CROSS APPLY
(
    SELECT column_name + ','
    FROM information_schema.columns AS intern
    WHERE extern.table_name = intern.table_name
    FOR XML PATH('')
) pre_trimmed (column_names)
GROUP BY table_name, column_names;

Or a version that works correctly if the data might contain characters such as <

WITH extern
     AS (SELECT DISTINCT table_name
         FROM   INFORMATION_SCHEMA.COLUMNS)
SELECT table_name,
       LEFT(y.column_names, LEN(y.column_names) - 1) AS column_names
FROM   extern
       CROSS APPLY (SELECT column_name + ','
                    FROM   INFORMATION_SCHEMA.COLUMNS AS intern
                    WHERE  extern.table_name = intern.table_name
                    FOR XML PATH(''), TYPE) x (column_names)
       CROSS APPLY (SELECT x.column_names.value('.', 'NVARCHAR(MAX)')) y(column_names) 

mySQL :: insert into table, data from another table?

INSERT INTO Table1 SELECT * FROM Table2

How to create a responsive image that also scales up in Bootstrap 3

If setting a fixed width on the image is not an option, here's an alternative solution.

Having a parent div with display: table & table-layout: fixed. Then setting the image to display: table-cell and max-width to 100%. That way the image will fit to the width of its parent.

Example:

<style>
    .wrapper { float: left; clear: left; display: table; table-layout: fixed; }
    img.img-responsive { display: table-cell; max-width: 100%; }
</style>
<div class="wrapper col-md-3">
    <img class="img-responsive" src="https://www.google.co.uk/images/srpr/logo11w.png"/>
</div>

Fiddle: http://jsfiddle.net/5y62c4af/

htaccess redirect if URL contains a certain string

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/foobar/i$ index.php [NE,L]

Method has the same erasure as another method in type

Define a single Method without type like void add(Set ii){}

You can mention the type while calling the method based on your choice. It will work for any type of set.

How to output in CLI during execution of PHP Unit tests?

UPDATE

Just realized another way to do this that works much better than the --verbose command line option:

class TestSomething extends PHPUnit_Framework_TestCase {
    function testSomething() {
        $myDebugVar = array(1, 2, 3);
        fwrite(STDERR, print_r($myDebugVar, TRUE));
    }
}

This lets you dump anything to your console at any time without all the unwanted output that comes along with the --verbose CLI option.


As other answers have noted, it's best to test output using the built-in methods like:

$this->expectOutputString('foo');

However, sometimes it's helpful to be naughty and see one-off/temporary debugging output from within your test cases. There is no need for the var_dump hack/workaround, though. This can easily be accomplished by setting the --verbose command line option when running your test suite. For example:

$ phpunit --verbose -c phpunit.xml

This will display output from inside your test methods when running in the CLI environment.

See: Writing Tests for PHPUnit - Testing Output.

jQuery: read text file from file system

specify the full path of the file url

What are some resources for getting started in operating system development?

One reasonably simple OS to study would be µC/OS. The book has a floppy with the source on it.

http://en.wikipedia.org/wiki/MicroC/OS-II

Coding Conventions - Naming Enums

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

Replace non ASCII character from string

You can try something like this. Special Characters range for alphabets starts from 192, so you can avoid such characters in the result.

String name = "A função";

StringBuilder result = new StringBuilder();
for(char val : name.toCharArray()) {
    if(val < 192) result.append(val);
}
System.out.println("Result "+result.toString());

Python speed testing - Time Difference - milliseconds

I am not a Python programmer, but I do know how to use Google and here's what I found: you use the "-" operator. To complete your code:

from datetime import datetime

tstart = datetime.now()

# code to speed test

tend = datetime.now()
print tend - tstart

Additionally, it looks like you can use the strftime() function to format the timespan calculation in order to render the time however makes you happy.

How to use SQL Select statement with IF EXISTS sub query?

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

How do I keep the screen on in my App?

Add one line of code after setContentView() in onCreate()

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flag);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

android set button background programmatically

You can set your desired color to the button programmatically like:

Button11.setBackgroundColor(Android.Graphics.Color.parseColor("#738b28"));

Also you can give the text color for a button like:

Button11.setTextColor(Android.Graphics.Color.parseColor("#FFFFFF"));

Replace all spaces in a string with '+'

You need the /g (global) option, like this:

var replaced = str.replace(/ /g, '+');

You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.

How to call python script on excel vba?

You can also try ExcelPython which allows you to manipulate Python object and call code from VBA.

Select query with date condition

Be careful, you're unwittingly asking "where the date is greater than one divided by nine, divided by two thousand and eight".

Put # signs around the date, like this #1/09/2008#

jQuery/JavaScript to replace broken images

I think I have a more elegant way with event delegation and event capturing on window's error even when the backup image fail to load.

_x000D_
_x000D_
img {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<script>_x000D_
  window.addEventListener('error', windowErrorCb, {_x000D_
    capture: true_x000D_
  }, true)_x000D_
_x000D_
  function windowErrorCb(event) {_x000D_
    let target = event.target_x000D_
    let isImg = target.tagName.toLowerCase() === 'img'_x000D_
    if (isImg) {_x000D_
      imgErrorCb()_x000D_
      return_x000D_
    }_x000D_
_x000D_
    function imgErrorCb() {_x000D_
      let isImgErrorHandled = target.hasAttribute('data-src-error')_x000D_
      if (!isImgErrorHandled) {_x000D_
        target.setAttribute('data-src-error', 'handled')_x000D_
        target.src = 'backup.png'_x000D_
      } else {_x000D_
        //anything you want to do_x000D_
        console.log(target.alt, 'both origin and backup image fail to load!');_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
</script>_x000D_
<img id="img" src="error1.png" alt="error1">_x000D_
<img id="img" src="error2.png" alt="error2">_x000D_
<img id="img" src="https://i.stack.imgur.com/ZXCE2.jpg" alt="avatar">
_x000D_
_x000D_
_x000D_

The point is :

  1. Put the code in the head and executed as the first inline script. So, it will listen the errors happen after the script.

  2. Use event capturing to catch the errors, especially for those events which don't bubble.

  3. Use event delegation which avoids binding events on each image.

  4. Give the error img element an attribute after giving them a backup.png to avoid disappearance of the backup.png and subsequent infinite loop like below:

img error->backup.png->error->backup.png->error->,,,,,

jQuery window scroll event does not fire up

$('#div').scroll(function () {
   if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight-1) {

     //fire your event


    }
}

Change bootstrap navbar background color and font color

Most likely these classes are already defined by Bootstrap, make sure that your CSS file that you want to override the classes with is called AFTER the Bootstrap CSS.

<link rel="stylesheet" href="css/bootstrap.css" /> <!-- Call Bootstrap first -->
<link rel="stylesheet" href="css/bootstrap-override.css" /> <!-- Call override CSS second -->

Otherwise, you can put !important at the end of your CSS like this: color:#ffffff!important; but I would advise against using !important at all costs.

Pushing from local repository to GitHub hosted remote

You push your local repository to the remote repository using the git push command after first establishing a relationship between the two with the git remote add [alias] [url] command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:

git remote add origin [email protected]:username/reponame.git

Unless you started by running git clone against the remote repository, in which case this step has been done for you already.

And after that, you'll type:

git push origin master

After your first push, you can simply type:

git push

when you want to update the remote repository in the future.

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

The reason that MFC favors protected, is because it is a framework. You probably want to subclass the MFC classes and in that case a protected interface is needed to access methods that are not visible to general use of the class.

How to fill the whole canvas with specific color?

We don't need to access the canvas context.

Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8'). But my preferred method requires converting the kabab-case to camelCase.

canvas.style.backgroundColor = '#00F8'

Are HTTPS URLs encrypted?

Yes and no.

The server address portion is NOT encrypted since it is used to set up the connection.

This may change in future with encrypted SNI and DNS but as of 2018 both technologies are not commonly in use.

The path, query string etc. are encrypted.

Note for GET requests the user will still be able to cut and paste the URL out of the location bar, and you will probably not want to put confidential information in there that can be seen by anyone looking at the screen.

No module named 'openpyxl' - Python 3.4 - Ubuntu

I still was not able to import 'openpyxl' after successfully installing it via both conda and pip. I discovered that it was installed in '/usr/lib/python3/dist-packages', so this https://stackoverflow.com/a/59861933/10794682 worked for me:

import sys 
sys.path.append('/usr/lib/python3/dist-packages')

Hope this might be useful for others.

Prepare for Segue in Swift

Provided you aren't using the same destination view controller with different identifiers, the code can be more concise than the other solutions (and avoids the as! in some of the other answers):

override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
    if let myViewController = segue.destinationController as? MyViewController { 
        // Set up the VC
    }
}

how can I copy a conditional formatting in Excel 2010 to other cells, which is based on a other cells content?

You can do this in the 'Conditional Formatting' tool in the Home tab of Excel 2010.

Assuming the existing rule is 'Use a formula to dtermine which cells to format':

Edit the existing rule, so that the 'Formula' refers to relative rows and columns (i.e. remove $s), and then in the 'Applies to' box, click the icon to make the sheet current and select the cells you want the formatting to apply to (absolute cell references are ok here), then go back to the tool panel and click Apply.

This will work assuming the relative offsets are appropriate throughout your desired apply-to range.

You can copy conditional formatting from one cell to another or a range using copy and paste-special with formatting only, assuming you do not mind copying the normal formats.

ES6 exporting/importing in index file

Also, bear in mind that if you need to export multiple functions at once, like actions you can use

export * from './XThingActions';

Adding a new entry to the PATH variable in ZSH

Actually, using ZSH allows you to use special mapping of environment variables. So you can simply do:

# append
path+=('/home/david/pear/bin')
# or prepend
path=('/home/david/pear/bin' $path)
# export to sub-processes (make it inherited by child processes)
export PATH

For me that's a very neat feature which can be propagated to other variables. Example:

typeset -T LD_LIBRARY_PATH ld_library_path :

Why is "throws Exception" necessary when calling a function?

package javaexception;


public class JavaException {
   void show() throws Exception
    {
        throw new Exception("my.own.Exception");
    }

void show2() throws Exception  // Why throws is necessary here ?
{
    show();
}

void show3() throws Exception  // Why throws is necessary here ?
{
    show2();
}
public static void main(String[] args) {

   JavaException a = new JavaException();

   try{
   a.show3();
   }catch(Exception e){
       System.out.println(e.getMessage());
   }
}

Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.

Search text in stored procedure in SQL Server

Good practice to work with SQL Server.

Create below stored procedure and set short key,

CREATE PROCEDURE [dbo].[Searchinall]       
(@strFind AS VARCHAR(MAX))
AS
BEGIN
    SET NOCOUNT ON; 
    --TO FIND STRING IN ALL PROCEDURES        
    BEGIN
        SELECT OBJECT_NAME(OBJECT_ID) SP_Name
              ,OBJECT_DEFINITION(OBJECT_ID) SP_Definition
        FROM   sys.procedures
        WHERE  OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
    END 

    --TO FIND STRING IN ALL VIEWS        
    BEGIN
        SELECT OBJECT_NAME(OBJECT_ID) View_Name
              ,OBJECT_DEFINITION(OBJECT_ID) View_Definition
        FROM   sys.views
        WHERE  OBJECT_DEFINITION(OBJECT_ID) LIKE '%'+@strFind+'%'
    END 

    --TO FIND STRING IN ALL FUNCTION        
    BEGIN
        SELECT ROUTINE_NAME           Function_Name
              ,ROUTINE_DEFINITION     Function_definition
        FROM   INFORMATION_SCHEMA.ROUTINES
        WHERE  ROUTINE_DEFINITION LIKE '%'+@strFind+'%'
               AND ROUTINE_TYPE = 'FUNCTION'
        ORDER BY
               ROUTINE_NAME
    END

    --TO FIND STRING IN ALL TABLES OF DATABASE.    
    BEGIN
        SELECT t.name      AS Table_Name
              ,c.name      AS COLUMN_NAME
        FROM   sys.tables  AS t
               INNER JOIN sys.columns c
                    ON  t.OBJECT_ID = c.OBJECT_ID
        WHERE  c.name LIKE '%'+@strFind+'%'
        ORDER BY
               Table_Name
    END
END

Now - Set short key as below,

enter image description here

So next time whenever you want to find a particular text in any of the four objects like Store procedure, Views, Functions and Tables. You just need to write that keyword and press shortcut key.

For example: I want to search 'PaymentTable' then write 'PaymentTable' and make sure you select or highlight the written keyword in query editor and press shortcut key ctrl+4 - it will provide you full result.

c# - approach for saving user settings in a WPF application?

Update: Nowadays I would use JSON.

I also prefer to go with serialization to file. XML files fits mostly all requirements. You can use the ApplicationSettings build in but those have some restrictions and a defined but (for me) very strange behavior where they stored. I used them a lot and they work. But if you want to have full control how and where they stored I use another approach.

  1. Make a class Somewhere with all your settings. I named it MySettings
  2. Implement Save and Read for persistence
  3. Use them in you application-code

Advantages:

  • Very Simple approach.
  • One Class for Settings. Load. Save.
  • All your Settings are type safe.
  • You can simplify or extend the logic to your needs (Versioning, many Profiles per User, etc.)
  • It works very well in any case (Database, WinForms, WPF, Service, etc...)
  • You can define where to store the XML files.
  • You can find them and manipulate them either by code or manual
  • It works for any deployment method I can imagine.

Disadvantages: - You have to think about where to store your settings files. (But you can just use your installation folder)

Here is a simple example (not tested)-

public class MySettings
{
    public string Setting1 { get; set; }
    public List<string> Setting2 { get; set; }

    public void Save(string filename)
    {
        using (StreamWriter sw = new StreamWriter(filename))
        {
            XmlSerializer xmls = new XmlSerializer(typeof(MySettings));
            xmls.Serialize(sw, this);
        }
    }
    public MySettings Read(string filename)
    {
        using (StreamReader sw = new StreamReader(filename))
        {
            XmlSerializer xmls = new XmlSerializer(typeof(MySettings));
            return xmls.Deserialize(sw) as MySettings;
        }
    }
}

And here is how to use it. It's possible to load default values or override them with the user's settings by just checking if user settings exist:

public class MyApplicationLogic
{
    public const string UserSettingsFilename = "settings.xml";
    public string _DefaultSettingspath = 
        Assembly.GetEntryAssembly().Location + 
        "\\Settings\\" + UserSettingsFilename;

    public string _UserSettingsPath = 
        Assembly.GetEntryAssembly().Location + 
        "\\Settings\\UserSettings\\" + 
        UserSettingsFilename;

    public MyApplicationLogic()
    {
        // if default settings exist
        if (File.Exists(_UserSettingsPath))
            this.Settings = Settings.Read(_UserSettingsPath);
        else
            this.Settings = Settings.Read(_DefaultSettingspath);
    }
    public MySettings Settings { get; private set; }

    public void SaveUserSettings()
    {
        Settings.Save(_UserSettingsPath);
    }
}

maybe someone get's inspired by this approach. This is how I do it now for many years and I'm quite happy with that.

How do I hide an element on a click event anywhere outside of the element?

Just 2 small improvements to the above suggestions:

  • unbind the document.click when done
  • stop propagation on the event that triggered this, assuming its a click

    jQuery(thelink).click(function(e){
        jQuery(thepop).show();
    
        // bind the hide controls
        var jpop=jQuery(thepop);
        jQuery(document).bind("click.hidethepop", function() {
                jpop.hide();
                // unbind the hide controls
                jQuery(document).unbind("click.hidethepop");
        });
        // dont close thepop when you click on thepop
        jQuery(thepop).click(function(e) {
            e.stopPropagation();
        });
        // and dont close thepop now 
        e.stopPropagation();
    });
    

How to convert a private key to an RSA private key?

This may be of some help (do not literally write out the backslashes '\' in the commands, they are meant to indicate that "everything has to be on one line"):

Which Command to Apply When

It seems that all the commands (in grey) take any type of key file (in green) as "in" argument. Which is nice.

Here are the commands again for easier copy-pasting:

openssl rsa                                                -in $FF -out $TF
openssl rsa -aes256                                        -in $FF -out $TF
openssl pkcs8 -topk8 -nocrypt                              -in $FF -out $TF
openssl pkcs8 -topk8 -v2 aes-256-cbc -v2prf hmacWithSHA256 -in $FF -out $TF

and

openssl rsa -check -in $FF
openssl rsa -text  -in $FF

How do I declare a namespace in JavaScript?

You can declare a simple function to provide namespaces.

function namespace(namespace) {
    var object = this, tokens = namespace.split("."), token;

    while (tokens.length > 0) {
        token = tokens.shift();

        if (typeof object[token] === "undefined") {
            object[token] = {};
        }

        object = object[token];
    }

    return object;
}

// Usage example
namespace("foo.bar").baz = "I'm a value!";

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

Adding minutes to date time in PHP

You can do this with native functions easily:

strtotime('+59 minutes', strtotime('2011-11-17 05:05'));

I'd recommend the DateTime class method though, just posted by Tim.

.htaccess not working on localhost with XAMPP

Edit the .htaccess file, so the first line reads 'Test.':

Test.

Set the default handler

DirectoryIndex index.php index.html index.htm

...

Count distinct value pairs in multiple columns in SQL

To get a count of the number of unique combinations of id, name and address:

SELECT Count(*)
FROM   (
        SELECT DISTINCT
               id
             , name
             , address
        FROM   your_table
       ) As distinctified

How do I generate random numbers in Dart?

A secure random API was just added to dart:math

new Random.secure()

dart:math Random added a secure constructor returning a cryptographically secure random generator which reads from the entropy source provided by the embedder for every generated random value.

which delegates to window.crypto.getRandomValues() in the browser and to the OS (like urandom on the server)

Asynchronous method call in Python?

You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:

apply_async(func[, args[, kwds[, callback]]])

E.g.:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.

PHP: Call to undefined function: simplexml_load_string()

I also faced this issue. My Operating system is Ubuntu 18.04 and my PHP version is PHP 7.2.

Here's how I solved it:

Install Simplexml on your Ubuntu Server:

sudo apt-get install php7.2-simplexml

Restart Apache Server

sudo systemctl restart apache2

That's all.

I hope this helps

How to recover corrupted Eclipse workspace?

One more solution that I've discovered by accident, and may help someone:

  1. Back up the corrupted workspace.
  2. Move half of you projects to some temporary location.
  3. Start Eclipse, if it works, go to step 5.
  4. Move the half of projects you've removed back into the workspace, move out the other half. If you've already done that, keep removing/readding your projects in a binary search manner. Go to step 3.
  5. Exit Eclipse, move back all your projects, and start it again. You should see now that some of your projects are closed (and in the wrong working sets). Re-open your projects and move them to the correct working sets.

In my case, it was a project that got corrupted, and not the entire workspace (attempting to import said project into a fresh workspace caused it to fail as well). So, I've started to search for the faulty project - instead, I got the result described above.

Getting hold of the outer class object from the inner class object

The more general answer to this question involves shadowed variables and how they are accessed.

In the following example (from Oracle), the variable x in main() is shadowing Test.x:

class Test {
    static int x = 1;
    public static void main(String[] args) {
        InnerClass innerClassInstance = new InnerClass()
        {
            public void printX()
            {
                System.out.print("x=" + x);
                System.out.println(", Test.this.x=" + Test.this.x);
            }
        }
        innerClassInstance.printX();
    }

    public abstract static class InnerClass
    {
        int x = 0;

        public InnerClass() { }

        public abstract void printX();
    }
}

Running this program will print:

x=0, Test.this.x=1

More at: http://docs.oracle.com/javase/specs/jls/se7/html/jls-6.html#jls-6.6

Handling NULL values in Hive

What is the datatype for column1 in your Hive table? Please note that if your column is STRING it won't be having a NULL value even though your external file does not have any data for that column.

Why do I need to explicitly push a new branch?

The actual reason is that, in a new repo (git init), there is no branch (no master, no branch at all, zero branches)

So when you are pushing for the first time to an empty upstream repo (generally a bare one), that upstream repo has no branch of the same name.

And:

In both cases, since the upstream empty repo has no branch:

  • there is no matching named branch yet
  • there is no upstream branch at all (with or without the same name! Tracking or not)

That means your local first push has no idea:

  • where to push
  • what to push (since it cannot find any upstream branch being either recorded as a remote tracking branch, and/or having the same name)

So you need at least to do a:

git push origin master

But if you do only that, you:

  • will create an upstream master branch on the upstream (now non-empty repo): good.
  • won't record that the local branch 'master' needs to be pushed to upstream (origin) 'master' (upstream branch): bad.

That is why it is recommended, for the first push, to do a:

git push -u origin master

That will record origin/master as a remote tracking branch, and will enable the next push to automatically push master to origin/master.

git checkout master
git push

And that will work too with push policies 'current' or 'upstream'.
In each case, after the initial git push -u origin master, a simple git push will be enough to continue pushing master to the right upstream branch.

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

SQL command to display history of queries

try

 cat ~/.mysql_history

this will show you all mysql commands ran on the system

Updating and committing only a file's permissions using git version control

By default, git will update execute file permissions if you change them. It will not change or track any other permissions.

If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.

Look into your project, in the .git folder for the config file and you should see something like this:

[core]
    filemode = false

You can either change it to true in your favorite text editor, or run:

git config core.filemode true

Then, you should be able to commit normally your files. It will only commit the permission changes.

Javascript get Object property Name

I was searching to get a result for this either and I ended up with;

const MyObject = {
    SubObject: {
        'eu': [0, "asd", true, undefined],
        'us': [0, "asd", false, null],
        'aus': [0, "asd", false, 0]
    }
};

For those who wanted the result as a string:

Object.keys(MyObject.SubObject).toString()

output: "eu,us,aus"

For those who wanted the result as an array:

Array.from(Object.keys(MyObject))

output: Array ["eu", "us", "aus"]

For those who are looking for a "contains" type method: as numeric result:

console.log(Object.keys(MyObject.SubObject).indexOf("k"));

output: -1

console.log(Object.keys(MyObject.SubObject).indexOf("eu"));

output: 0

console.log(Object.keys(MyObject.SubObject).indexOf("us"));

output: 3

as boolean result:

console.log(Object.keys(MyObject.SubObject).includes("eu"));

output: true


In your case;

_x000D_
_x000D_
var myVar = { typeA: { option1: "one", option2: "two" } }_x000D_
_x000D_
    // Example 1_x000D_
    console.log(Object.keys(myVar.typeA).toString()); // Result: "option1, option2"_x000D_
_x000D_
    // Example 2_x000D_
    console.log(Array.from(Object.keys(myVar.typeA))); // Result: Array ["option1", "option2" ]_x000D_
    _x000D_
    // Example 3 as numeric_x000D_
    console.log((Object.keys(myVar.typeA).indexOf("option1")>=0)?'Exist!':'Does not exist!'); // Result: Exist!_x000D_
    _x000D_
    // Example 3 as boolean_x000D_
    console.log(Object.keys(myVar.typeA).includes("option2")); // Result: True!_x000D_
    _x000D_
    // if you would like to know about SubObjects_x000D_
    for(var key in myVar){_x000D_
      // do smt with SubObject_x000D_
      console.log(key); // Result: typeA_x000D_
    }_x000D_
_x000D_
    // if you already know your "SubObject"_x000D_
    for(var key in myVar.typeA){_x000D_
      // do smt with option1, option2_x000D_
      console.log(key); // Result: option1 // Result: option2_x000D_
    }
_x000D_
_x000D_
_x000D_