Programs & Examples On #Authsub

Google AuthSub authentication for Google endpoints.

Default interface methods are only supported starting with Android N

This also happened to me but using Dynamic Features. I already had Java 8 compatibility enabled in the app module but I had to add this compatibility lines to the Dynamic Feature module and then it worked.

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

Example with glob() function. It will delete all files and folders recursively, including files that starts with dot.

delete_all( 'folder' );

function delete_all( $item ) {
    if ( is_dir( $item ) ) {
        array_map( 'delete_all', array_diff( glob( "$item/{,.}*", GLOB_BRACE ), array( "$item/.", "$item/.." ) ) );
        rmdir( $item );
    } else {
        unlink( $item );
    }
};

php error: Class 'Imagick' not found

Debian 9

I just did the following and everything else needed got automatically installed as well.

sudo apt-get -y -f install php-imagick
sudo /etc/init.d/apache2 restart

How to compile a static library in Linux?

See Creating a shared and static library with the gnu compiler [gcc]

gcc -c -o out.o out.c

-c means to create an intermediary object file, rather than an executable.

ar rcs libout.a out.o

This creates the static library. r means to insert with replacement, c means to create a new archive, and s means to write an index. As always, see the man page for more info.

Iterate over the lines of a string

If I read Modules/cStringIO.c correctly, this should be quite efficient (although somewhat verbose):

from cStringIO import StringIO

def iterbuf(buf):
    stri = StringIO(buf)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip()
        else:
            raise StopIteration

Check if String contains only letters

First import Pattern :

import java.util.regex.Pattern;

Then use this simple code:

String s = "smith23";
if (Pattern.matches("[a-zA-Z]+",s)) { 
  // Do something
  System.out.println("Yes, string contains letters only");
}else{
  System.out.println("Nope, Other characters detected");    
}

This will output:

Nope, Other characters detected

Visual Studio 2012 Web Publish doesn't copy files

FIXED - various solutions offered didn't work for me. What did work for me with VS Community 2017, Windows Server 2012 R2 was to change the TEMP and TMP environmental variables for the user and then restart the system and deploy again (restarting VS was not enough). These temp variables are where VS does the temp publish.

enter image description here

enter image description here

enter image description here

Restarting visual studio after changing temp variables didn't do the trick, had to reboot system.

What is the equivalent of the C++ Pair<L,R> in Java?

Simple way Object [] - can be use as an? dimention tuple

How do I detect if software keyboard is visible on Android Device or not?

final View activityRootView = findViewById(R.id.rootlayout);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {

            Rect r = new Rect();
            activityRootView.getWindowVisibleDisplayFrame(r);

            int screenHeight = activityRootView.getRootView().getHeight();
            Log.e("screenHeight", String.valueOf(screenHeight));
            int heightDiff = screenHeight - (r.bottom - r.top);
            Log.e("heightDiff", String.valueOf(heightDiff));
            boolean visible = heightDiff > screenHeight / 3;
            Log.e("visible", String.valueOf(visible));
            if (visible) {
                Toast.makeText(LabRegister.this, "I am here 1", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(LabRegister.this, "I am here 2", Toast.LENGTH_SHORT).show();
            }
        }
});

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

If you're using MVC 3 and Razor you can also use the following:

@Html.RadioButtonFor(model => model.blah, true) Yes
@Html.RadioButtonFor(model => model.blah, false) No

Python List vs. Array - when to use?

Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t).

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).

array.array is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray.

However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.

To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.

Is there a sleep function in JavaScript?

A naive, CPU-intensive method to block execution for a number of milliseconds:

/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

Mercurial stuck "waiting for lock"

I had the same problem on Win 7. The solution was to remove following files:

  1. .hg/store/phaseroots
  2. .hg/wlock

As for .hg/store/lock - there was no such file.

Create Directory When Writing To File In Node.js

Node > 10.12.0

fs.mkdir now accepts a { recursive: true } option like so:

// Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
fs.mkdir('/tmp/a/apple', { recursive: true }, (err) => {
  if (err) throw err;
});

or with a promise:

fs.promises.mkdir('/tmp/a/apple', { recursive: true }).catch(console.error);

Node <= 10.11.0

You can solve this with a package like mkdirp or fs-extra. If you don't want to install a package, please see Tiago Peres França's answer below.

How does Trello access the user's clipboard?

Disclosure: I wrote the code that Trello uses; the code below is the actual source code Trello uses to accomplish the clipboard trick.


We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press Ctrl+C.

Sounds like you've figured it out; we take advantage of the fact that when you want to hit Ctrl+C, you have to hit the Ctrl key first. When the Ctrl key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the C key is hit. (Then we hide the textarea when the Ctrl key comes up.)

Specifically, Trello does this:

TrelloClipboard = new class
  constructor: ->
    @value = ""

    $(document).keydown (e) =>
      # Only do this if there's something to be put on the clipboard, and it
      # looks like they're starting a copy shortcut
      if !@value || !(e.ctrlKey || e.metaKey)
        return

      if $(e.target).is("input:visible,textarea:visible")
        return

      # Abort if it looks like they've selected some text (maybe they're trying
      # to copy out a bit of the description or something)
      if window.getSelection?()?.toString()
        return

      if document.selection?.createRange().text
        return

      _.defer =>
        $clipboardContainer = $("#clipboard-container")
        $clipboardContainer.empty().show()
        $("<textarea id='clipboard'></textarea>")
        .val(@value)
        .appendTo($clipboardContainer)
        .focus()
        .select()

    $(document).keyup (e) ->
      if $(e.target).is("#clipboard")
        $("#clipboard-container").empty().hide()

  set: (@value) ->

In the DOM we've got:

<div id="clipboard-container"><textarea id="clipboard"></textarea></div>

CSS for the clipboard stuff:

#clipboard-container {
  position: fixed;
  left: 0px;
  top: 0px;
  width: 0px;
  height: 0px;
  z-index: 100;
  display: none;
  opacity: 0;
}
#clipboard {
  width: 1px;
  height: 1px;
  padding: 0px;
}

... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.

When you hover over a card, it calls

TrelloClipboard.set(cardUrl)

... so then the clipboard helper knows what to select when the Ctrl key is pressed.

FileNotFoundError: [Errno 2] No such file or directory

For people who are still getting error despite of passing absolute path, should check that if file has a valid name. For me I was trying to create a file with '/' in the file name. As soon as I removed '/', I was able to create the file.

Checking something isEmpty in Javascript?

I see potential shortcomings in many solutions posted above, so I decided to compile my own.
Note: it uses Array.prototype.some, check your browser support.

Solution below considers variable empty if one of the following is true:

  1. JS thinks that variable is equal to false, which already covers many things like 0, "", [], and even [""] and [0]
  2. Value is null or it's type is 'undefined'
  3. It is an empty Object
  4. It is an Object/Array consisting only of values that are empty themselves (i.e. broken down to primitives each part of it equals false). Checks drill recursively into Object/Array structure. E.g.

    isEmpty({"": 0}) // true
    isEmpty({"": 1}) // false
    isEmpty([{}, {}])  // true
    isEmpty(["", 0, {0: false}]) //true
    

Function code:

/**
 * Checks if value is empty. Deep-checks arrays and objects
 * Note: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false
 * @param value
 * @returns {boolean}
 */
function isEmpty(value){
  var isEmptyObject = function(a) {
    if (typeof a.length === 'undefined') { // it's an Object, not an Array
      var hasNonempty = Object.keys(a).some(function nonEmpty(element){
        return !isEmpty(a[element]);
      });
      return hasNonempty ? false : isEmptyObject(Object.keys(a));
    }

    return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks
      return !isEmpty(element); // at least one element should be non-empty
    });
  };
  return (
    value == false
    || typeof value === 'undefined'
    || value == null
    || (typeof value === 'object' && isEmptyObject(value))
  );
}

Bootstrap button - remove outline on Chrome OS X

.btn.active or .btn.focus alone cannot override Bootstrap's styles. For default theme:

.btn.active.focus, .btn.active:focus,
.btn.focus, .btn:active.focus, 
.btn:active:focus, .btn:focus {
      outline: none;
}

How to add a "sleep" or "wait" to my Lua Script?

if you're using a MacBook or UNIX based system, use this:

function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()

CSS how to make scrollable list

As per your question vertical listing have a scrollbar effect.

CSS / HTML :

_x000D_
_x000D_
nav ul{height:200px; width:18%;}_x000D_
nav ul{overflow:hidden; overflow-y:scroll;}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <meta charset="utf-8">_x000D_
        <title>JS Bin</title>_x000D_
    </head>_x000D_
    <body>_x000D_
        <header>header area</header>_x000D_
        <nav>_x000D_
            <ul>_x000D_
                <li>Link 1</li>_x000D_
                <li>Link 2</li>_x000D_
                <li>Link 3</li>_x000D_
                <li>Link 4</li>_x000D_
                <li>Link 5</li>_x000D_
                <li>Link 6</li> _x000D_
                <li>Link 7</li> _x000D_
                <li>Link 8</li>_x000D_
                <li>Link 9</li>_x000D_
                <li>Link 10</li>_x000D_
                <li>Link 11</li>_x000D_
                <li>Link 13</li>_x000D_
                <li>Link 13</li>_x000D_
_x000D_
            </ul>_x000D_
        </nav>_x000D_
        _x000D_
        <footer>footer area</footer>_x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

I'm pretty sure this is just a bug in iOS 8.0. It's reproducible with the simplest of POC apps that does nothing more than attempt to present a UIImagePickerController like you're doing above. Furthermore, there's no alternative pattern to displaying the image picker/camera, to my knowledge. You can even download Apple's Using UIImagePickerController sample app, run it, and it will generate the same error out of the box.

That said, the functionality still works for me. Other than the warning/error, do you have issues with the functioning of your app?

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.

SELECT 
a.[CUSTOMER ID], 
a.[NAME], 
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a

How to set limits for axes in ggplot2 R plots?

Quick note: if you're also using coord_flip() to flip the x and the y axis, you won't be able to set range limits using coord_cartesian() because those two functions are exclusive (see here).

Fortunately, this is an easy fix; set your limits within coord_flip() like so:

p + coord_flip(ylim = c(3,5), xlim = c(100, 400))

This just alters the visible range (i.e. doesn't remove data points).

How to "grep" out specific line ranges of a file

Line numbers are OK if you can guarantee the position of what you want. Over the years, my favorite flavor of this has been something like this:

sed "/First Line of Text/,/Last Line of Text/d" filename

which deletes all lines from the first matched line to the last match, including those lines.

Use sed -n with "p" instead of "d" to print those lines instead. Way more useful for me, as I usually don't know where those lines are.

Convert comma separated string to array in PL/SQL

Yes, it is very frustrating that dbms_utility.comma_to_table only supports comma delimieted lists and then only when elements in the list are valid PL/SQL identifies (so numbers cause an error).

I have created a generic parsing package that will do what you need (pasted below). It is part of my "demo.zip" file, a repository of over 2000 files that support my training materials, all available at PL/SQL Obsession: www.toadworld.com/SF.

Regards, Steven Feuerstein www.plsqlchallenge.com (daily PL/SQL quiz)

    CREATE OR REPLACE PACKAGE parse
/*
   Generalized delimited string parsing package

   Author: Steven Feuerstein, [email protected]

   Latest version always available on PL/SQL Obsession: 

   www.ToadWorld.com/SF

   Click on "Trainings, Seminars and Presentations" and
   then download the demo.zip file.

   Modification History
      Date          Change
      10-APR-2009   Add support for nested list variations

   Notes:
     * This package does not validate correct use of delimiters.
       It assumes valid construction of lists.
     * Import the Q##PARSE.qut file into an installation of 
       Quest Code Tester 1.8.3 or higher in order to run
       the regression test for this package.

*/
IS
   SUBTYPE maxvarchar2_t IS VARCHAR2 (32767);

   /*
   Each of the collection types below correspond to (are returned by)
   one of the parse functions.

   items_tt - a simple list of strings
   nested_items_tt - a list of lists of strings
   named_nested_items_tt - a list of named lists of strings

   This last type also demonstrates the power and elegance of string-indexed
   collections. The name of the list of elements is the index value for
   the "outer" collection.
   */
   TYPE items_tt IS TABLE OF maxvarchar2_t
                       INDEX BY PLS_INTEGER;

   TYPE nested_items_tt IS TABLE OF items_tt
                              INDEX BY PLS_INTEGER;

   TYPE named_nested_items_tt IS TABLE OF items_tt
                                    INDEX BY maxvarchar2_t;

   /*
   Parse lists with a single delimiter.
   Example: a,b,c,d

   Here is an example of using this function:

   DECLARE
      l_list parse.items_tt;
   BEGIN
      l_list := parse.string_to_list ('a,b,c,d', ',');
   END;
   */
   FUNCTION string_to_list (string_in IN VARCHAR2, delim_in IN VARCHAR2)
      RETURN items_tt;

   /*
   Parse lists with nested delimiters.
   Example: a,b,c,d|1,2,3|x,y,z

   Here is an example of using this function:

   DECLARE
      l_list parse.nested_items_tt;
   BEGIN
      l_list := parse.string_to_list ('a,b,c,d|1,2,3,4', '|', ',');
   END;
   */
   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN nested_items_tt;

   /*
   Parse named lists with nested delimiters.
   Example: letters:a,b,c,d|numbers:1,2,3|names:steven,george

   Here is an example of using this function:

   DECLARE
      l_list parse.named_nested_items_tt;
   BEGIN
   l_list := parse.string_to_list ('letters:a,b,c,d|numbers:1,2,3,4', '|', ':', ',');
   END;
   */
   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , name_delim_in  IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN named_nested_items_tt;

   PROCEDURE display_list (string_in IN VARCHAR2
                         , delim_in  IN VARCHAR2:= ','
                          );

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          );

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , name_delim_in  IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          );

   PROCEDURE show_variations;

   /* Helper function for automated testing */
   FUNCTION nested_eq (list1_in    IN items_tt
                     , list2_in    IN items_tt
                     , nulls_eq_in IN BOOLEAN
                      )
      RETURN BOOLEAN;

END parse;
/

CREATE OR REPLACE PACKAGE BODY parse
IS
   FUNCTION string_to_list (string_in IN VARCHAR2, delim_in IN VARCHAR2)
      RETURN items_tt
   IS
      c_end_of_list   CONSTANT PLS_INTEGER := -99;
      l_item          maxvarchar2_t;
      l_startloc      PLS_INTEGER := 1;
      items_out       items_tt;

      PROCEDURE add_item (item_in IN VARCHAR2)
      IS
      BEGIN
         IF item_in = delim_in
         THEN
            /* We don't put delimiters into the collection. */
            NULL;
         ELSE
            items_out (items_out.COUNT + 1) := item_in;
         END IF;
      END;

      PROCEDURE get_next_item (string_in         IN     VARCHAR2
                             , start_location_io IN OUT PLS_INTEGER
                             , item_out             OUT VARCHAR2
                              )
      IS
         l_loc   PLS_INTEGER;
      BEGIN
         l_loc := INSTR (string_in, delim_in, start_location_io);

         IF l_loc = start_location_io
         THEN
            /* A null item (two consecutive delimiters) */
            item_out := NULL;
         ELSIF l_loc = 0
         THEN
            /* We are at the last item in the list. */
            item_out := SUBSTR (string_in, start_location_io);
         ELSE
            /* Extract the element between the two positions. */
            item_out :=
               SUBSTR (string_in
                     , start_location_io
                     , l_loc - start_location_io
                      );
         END IF;

         IF l_loc = 0
         THEN
            /* If the delimiter was not found, send back indication
               that we are at the end of the list. */

            start_location_io := c_end_of_list;
         ELSE
            /* Move the starting point for the INSTR search forward. */
            start_location_io := l_loc + 1;
         END IF;
      END get_next_item;
   BEGIN
      IF string_in IS NULL OR delim_in IS NULL
      THEN
         /* Nothing to do except pass back the empty collection. */
         NULL;
      ELSE
         LOOP
            get_next_item (string_in, l_startloc, l_item);
            add_item (l_item);
            EXIT WHEN l_startloc = c_end_of_list;
         END LOOP;
      END IF;

      RETURN items_out;
   END string_to_list;

   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN nested_items_tt
   IS
      l_elements   items_tt;
      l_return     nested_items_tt;
   BEGIN
      /* Separate out the different lists. */
      l_elements := string_to_list (string_in, outer_delim_in);

      /* For each list, parse out the separate items
         and add them to the end of the list of items
         for that list. */   
      FOR indx IN 1 .. l_elements.COUNT
      LOOP
         l_return (l_return.COUNT + 1) :=
            string_to_list (l_elements (indx), inner_delim_in);
      END LOOP;

      RETURN l_return;
   END string_to_list;

   FUNCTION string_to_list (string_in      IN VARCHAR2
                          , outer_delim_in IN VARCHAR2
                          , name_delim_in  IN VARCHAR2
                          , inner_delim_in IN VARCHAR2
                           )
      RETURN named_nested_items_tt
   IS
      c_name_position constant pls_integer := 1;
      c_items_position constant pls_integer := 2;
      l_elements          items_tt;
      l_name_and_values   items_tt;
      l_return            named_nested_items_tt;
   BEGIN
      /* Separate out the different lists. */
      l_elements := string_to_list (string_in, outer_delim_in);

      FOR indx IN 1 .. l_elements.COUNT
      LOOP
         /* Extract the name and the list of items that go with 
            the name. This collection always has just two elements:
              index 1 - the name
              index 2 - the list of values
         */
         l_name_and_values :=
            string_to_list (l_elements (indx), name_delim_in);
         /*
         Use the name as the index value for this list.
         */
         l_return (l_name_and_values (c_name_position)) :=
            string_to_list (l_name_and_values (c_items_position), inner_delim_in);
      END LOOP;

      RETURN l_return;
   END string_to_list;

   PROCEDURE display_list (string_in IN VARCHAR2
                         , delim_in  IN VARCHAR2:= ','
                          )
   IS
      l_items   items_tt;
   BEGIN
      DBMS_OUTPUT.put_line (
         'Parse "' || string_in || '" using "' || delim_in || '"'
      );

      l_items := string_to_list (string_in, delim_in);

      FOR indx IN 1 .. l_items.COUNT
      LOOP
         DBMS_OUTPUT.put_line ('> ' || indx || ' = ' || l_items (indx));
      END LOOP;
   END display_list;

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          )
   IS
      l_items   nested_items_tt;
   BEGIN
      DBMS_OUTPUT.put_line(   'Parse "'
                           || string_in
                           || '" using "'
                           || outer_delim_in
                           || '-'
                           || inner_delim_in
                           || '"');
      l_items := string_to_list (string_in, outer_delim_in, inner_delim_in);


      FOR outer_index IN 1 .. l_items.COUNT
      LOOP
         DBMS_OUTPUT.put_line(   'List '
                              || outer_index
                              || ' contains '
                              || l_items (outer_index).COUNT
                              || ' elements');

         FOR inner_index IN 1 .. l_items (outer_index).COUNT
         LOOP
            DBMS_OUTPUT.put_line(   '> Value '
                                 || inner_index
                                 || ' = '
                                 || l_items (outer_index) (inner_index));
         END LOOP;
      END LOOP;
   END display_list;

   PROCEDURE display_list (string_in      IN VARCHAR2
                         , outer_delim_in IN VARCHAR2
                         , name_delim_in  IN VARCHAR2
                         , inner_delim_in IN VARCHAR2
                          )
   IS
      l_items   named_nested_items_tt;
      l_index   maxvarchar2_t;
   BEGIN
      DBMS_OUTPUT.put_line(   'Parse "'
                           || string_in
                           || '" using "'
                           || outer_delim_in
                           || '-'
                           || name_delim_in
                           || '-'
                           || inner_delim_in
                           || '"');
      l_items :=
         string_to_list (string_in
                       , outer_delim_in
                       , name_delim_in
                       , inner_delim_in
                        );

      l_index := l_items.FIRST;

      WHILE (l_index IS NOT NULL)
      LOOP
         DBMS_OUTPUT.put_line(   'List "'
                              || l_index
                              || '" contains '
                              || l_items (l_index).COUNT
                              || ' elements');

         FOR inner_index IN 1 .. l_items (l_index).COUNT
         LOOP
            DBMS_OUTPUT.put_line(   '> Value '
                                 || inner_index
                                 || ' = '
                                 || l_items (l_index) (inner_index));
         END LOOP;

         l_index := l_items.NEXT (l_index);
      END LOOP;
   END display_list;

   PROCEDURE show_variations
   IS
      PROCEDURE show_header (title_in IN VARCHAR2)
      IS
      BEGIN
         DBMS_OUTPUT.put_line (RPAD ('=', 60, '='));
         DBMS_OUTPUT.put_line (title_in);
         DBMS_OUTPUT.put_line (RPAD ('=', 60, '='));
      END show_header;
   BEGIN
      show_header ('Single Delimiter Lists');
      display_list ('a,b,c');
      display_list ('a;b;c', ';');
      display_list ('a,,b,c');
      display_list (',,b,c,,');

      show_header ('Nested Lists');
      display_list ('a,b,c,d|1,2,3|x,y,z', '|', ',');

      show_header ('Named, Nested Lists');
      display_list ('letters:a,b,c,d|numbers:1,2,3|names:steven,george'
                  , '|'
                  , ':'
                  , ','
                   );
   END;

   FUNCTION nested_eq (list1_in    IN items_tt
                     , list2_in    IN items_tt
                     , nulls_eq_in IN BOOLEAN
                      )
      RETURN BOOLEAN
   IS
      l_return   BOOLEAN := list1_in.COUNT = list2_in.COUNT;
      l_index    PLS_INTEGER := 1;
   BEGIN
      WHILE (l_return AND l_index IS NOT NULL)
      LOOP
         l_return := list1_in (l_index) = list2_in (l_index);
         l_index := list1_in.NEXT (l_index);
      END LOOP;

      RETURN l_return;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         RETURN FALSE;
   END nested_eq;
END;
/

Xcode Objective-C | iOS: delay function / NSTimer help?

sleep doesn't work because the display can only be updated after your main thread returns to the system. NSTimer is the way to go. To do this, you need to implement methods which will be called by the timer to change the buttons. An example:

- (void)button_circleBusy:(id)sender {
    firstButton.enabled = NO;
    // 60 milliseconds is .06 seconds
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
}
- (void)goToSecondButton:(id)sender {
    firstButton.enabled = YES;
    secondButton.enabled = NO;
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO];
}
...

Reading data from XML

Try GetElementsByTagName method of XMLDocument class to read specific data or LoadXml method to read all data to xml document.

"Operation must use an updateable query" error in MS Access

I used a temp table and finally got this to work. Here is the logic that is used once you create the temp table:

UPDATE your_table, temp
SET your_table.value = temp.value
WHERE your_table.id = temp.id

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

How do you do relative time in Rails?

Another approach is to unload some logic from the backend and maek the browser do the job by using Javascript plugins such as:

jQuery time ago or its Rails Gem adaptation

Removing trailing newline character from fgets() input

The steps to remove the newline character in the perhaps most obvious way:

  1. Determine the length of the string inside NAME by using strlen(), header string.h. Note that strlen() does not count the terminating \0.
size_t sl = strlen(NAME);

  1. Look if the string begins with or only includes one \0 character (empty string). In this case sl would be 0 since strlen() as I said above doesn´t count the \0 and stops at the first occurrence of it:
if(sl == 0)
{
   // Skip the newline replacement process.
}

  1. Check if the last character of the proper string is a newline character '\n'. If this is the case, replace \n with a \0. Note that index counts start at 0 so we will need to do NAME[sl - 1]:
if(NAME[sl - 1] == '\n')
{
   NAME[sl - 1] = '\0';
}

Note if you only pressed Enter at the fgets() string request (the string content was only consisted of a newline character) the string in NAME will be an empty string thereafter.


  1. We can combine step 2. and 3. together in just one if-statement by using the logic operator &&:
if(sl > 0 && NAME[sl - 1] == '\n')
{
   NAME[sl - 1] = '\0';
}

  1. The finished code:
size_t sl = strlen(NAME);
if(sl > 0 && NAME[sl - 1] == '\n')
{
   NAME[sl - 1] = '\0';
}

If you rather like a function for use this technique by handling fgets output strings in general without retyping each and every time, here is fgets_newline_kill:

void fgets_newline_kill(char a[])
{
    size_t sl = strlen(a);

    if(sl > 0 && a[sl - 1] == '\n')
    {
       a[sl - 1] = '\0';
    }
}

In your provided example, it would be:

printf("Enter your Name: ");

if (fgets(Name, sizeof Name, stdin) == NULL) {
    fprintf(stderr, "Error reading Name.\n");
    exit(1);
}
else {
    fgets_newline_kill(NAME);
}

Note that this method does not work if the input string has embedded \0s in it. If that would be the case strlen() would only return the amount of characters until the first \0. But this isn´t quite a common approach, since the most string-reading functions usually stop at the first \0 and take the string until that null character.

Aside from the question on its own. Try to avoid double negations that make your code unclearer: if (!(fgets(Name, sizeof Name, stdin) != NULL) {}. You can simply do if (fgets(Name, sizeof Name, stdin) == NULL) {}.

Difference between / and /* in servlet mapping url pattern

<url-pattern>/*</url-pattern>

The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().

<url-pattern>/</url-pattern>

The / doesn't override any other servlet. It only replaces the servletcontainer's builtin default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's builtin default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's builtin JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.

<url-pattern></url-pattern>

Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.

Front Controller

In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a builtin static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?

What is the difference among col-lg-*, col-md-* and col-sm-* in Bootstrap?

enter image description here

I think this image is pretty good to understand the concept better!

for more detail understanding please go though below link:

https://getbootstrap.com/docs/3.4/css/

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

How can I check for IsPostBack in JavaScript?

You can create a hidden textbox with a value of 0. Put the onLoad() code in a if block that checks to make sure the hidden text box value is 0. if it is execute the code and set the textbox value to 1.

How to clear an ImageView in Android?

As kwasi wrote and golu edited, you can use transparent, instead of white:

File drawable/transparent.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/transparent"/>
</shape>

Inside an activity, view, etc:

view.setImageResource(R.drawable.transparent);

How do I detect "shift+enter" and generate a new line in Textarea?

Using ReactJS ES6 here's the simplest way

shift + enter New Line at any position

enter Blocked

_x000D_
_x000D_
class App extends React.Component {_x000D_
_x000D_
 constructor(){_x000D_
    super();_x000D_
    this.state = {_x000D_
      message: 'Enter is blocked'_x000D_
    }_x000D_
  }_x000D_
  onKeyPress = (e) => {_x000D_
     if (e.keyCode === 13 && e.shiftKey) {_x000D_
        e.preventDefault();_x000D_
        let start = e.target.selectionStart,_x000D_
            end = e.target.selectionEnd;_x000D_
        this.setState(prevState => ({ message:_x000D_
            prevState.message.substring(0, start)_x000D_
            + '\n' +_x000D_
            prevState.message.substring(end)_x000D_
        }),()=>{_x000D_
            this.input.selectionStart = this.input.selectionEnd = start + 1;_x000D_
        })_x000D_
    }else if (e.keyCode === 13) { // block enter_x000D_
      e.preventDefault();_x000D_
    }_x000D_
    _x000D_
  };_x000D_
_x000D_
  render(){_x000D_
    return(_x000D_
      <div>_x000D_
      New line with shift enter at any position<br />_x000D_
       <textarea _x000D_
       value={this.state.message}_x000D_
       ref={(input)=> this.input = input}_x000D_
       onChange={(e)=>this.setState({ message: e.target.value })}_x000D_
       onKeyDown={this.onKeyPress}/>_x000D_
      </div>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

Error: "an object reference is required for the non-static field, method or property..."

You just need to make the siprimo and volteado methods static.

private static bool siprimo(long a)

and

private static long volteado(long a)

Check/Uncheck a checkbox on datagridview

All of the casting causes errors, nothing here I tried worked, so I fiddled around and got this to work.

  foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            if (row.Cells[0].Value != null && (bool)row.Cells[0].Value)
            {
                Console.WriteLine(row.Cells[0].Value);
            }

        }

Make $JAVA_HOME easily changable in Ubuntu

Take a look at bash(1), you need a login shell to pickup the ~/.profile, i.e. the -l option.

Create Log File in Powershell

Using this Log-Entry framework:

Script:

Function Main {
    Log -File "D:\Apps\Logs\$Env:computername.log"

    $tcp = (get-childitem c:\windows\system32\drivers\tcpip.sys).Versioninfo.ProductVersionRaw
    $dfs = (get-childitem C:\Windows\Microsoft.NET\Framework\v2.0.50727\dfsvc.exe).Versioninfo.ProductVersionRaw

    Log "TCPIP.sys Version on $computer is:" $tcp
    Log "DFSVC.exe Version on $computer is:" $dfs

    If (get-wmiobject win32_share | where-object {$_.Name -eq "REMINST"}) {Log "The REMINST share exists on $computer"}
    Else {Log "The REMINST share DOES NOT exist on $computer - Please create as per standards"}

    "KB2450944", "KB3150513", "KB3176935" | ForEach {
        $hotfix = Get-HotFix -Id $_ -ErrorAction SilentlyContinue
        If ($hotfix) {Log -Color Green Hotfix $_ is installed}
        Else {Log -Color Red Hotfix $_ " is NOT installed - Please ensure you install this hotfix"}
    }
}

Screen output: Screen output

Log File (at D:\Apps\Logs\<computername>.log):

2017-05-31  Write-Log (version: 01.00.02, PowerShell version: 5.1.14393.1198)
19:19:29.00 C:\Users\User\PowerShell\Write-Log\Check.ps1 
19:19:29.47 TCPIP.sys Version on  is: {Major: 10, Minor: 0, Build: 14393, Revision: 1066, MajorRevision: 0, MinorRevision: 1066}
19:19:29.50 DFSVC.exe Version on  is: {Major: 2, Minor: 0, Build: 50727, Revision: 8745, MajorRevision: 0, MinorRevision: 8745}
19:19:29.60 The REMINST share DOES NOT exist on  - Please create as per standards
Error at 25,13: Cannot find the requested hotfix on the 'localhost' computer. Verify the input and run the command again.
19:19:33.41 Hotfix KB2450944 is NOT installed - Please ensure you install this hotfix
19:19:37.03 Hotfix KB3150513 is installed
19:19:40.77 Hotfix KB3176935 is installed
19:19:40.77 End

How do you use script variables in psql?

FWIW, the real problem was that I had included a semicolon at the end of my \set command:

\set owner_password 'thepassword';

The semicolon was interpreted as an actual character in the variable:

\echo :owner_password thepassword;

So when I tried to use it:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD :owner_password NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

...I got this:

CREATE ROLE myrole LOGIN UNENCRYPTED PASSWORD thepassword; NOINHERIT CREATEDB CREATEROLE VALID UNTIL 'infinity';

That not only failed to set the quotes around the literal, but split the command into 2 parts (the second of which was invalid as it started with "NOINHERIT").

The moral of this story: PostgreSQL "variables" are really macros used in text expansion, not true values. I'm sure that comes in handy, but it's tricky at first.

Numpy: Creating a complex array from 2 real ones?

This seems to do what you want:

numpy.apply_along_axis(lambda args: [complex(*args)], 3, Data)

Here is another solution:

# The ellipsis is equivalent here to ":,:,:"...
numpy.vectorize(complex)(Data[...,0], Data[...,1])

And yet another simpler solution:

Data[...,0] + 1j * Data[...,1]

PS: If you want to save memory (no intermediate array):

result = 1j*Data[...,1]; result += Data[...,0]

devS' solution below is also fast.

Error message Strict standards: Non-static method should not be called statically in php

I think this may answer your question.

Non-static method ..... should not be called statically

If the method is not static you need to initialize it like so:

$var = new ClassName();
$var->method();

Or, in PHP 5.4+, you can use this syntax:

(new ClassName)->method();

How to change menu item text dynamically in Android

You can do it like this, and no need to dedicate variable:

Toolbar toolbar = findViewById(R.id.toolbar);
Menu menu = toolbar.getMenu();
MenuItem menuItem = menu.findItem(R.id.some_action);
menuItem.setTitle("New title");

Or a little simplified:

MenuItem menuItem = ((Toolbar)findViewById(R.id.toolbar)).getMenu().findItem(R.id.some_action);
menuItem.setTitle("New title");

It works only - after the menu created.

database vs. flat files

Databases all the way.

However, if you still have a need for storing files, don't have the capacity to take on a new RDBMS (like Oracle, SQLServer, etc), than look into XML.

XML is a structure file format which offers you the ability to store things as a file but give you query power over the file and data within it. XML Files are easier to read than flat files and can be easily transformed applying an XSLT for even better human-readability. XML is also a great way to transport data around if you must.

I strongly suggest a DB, but if you can't go that route, XML is an ok second.

Handling InterruptedException in Java

The correct default choice is add InterruptedException to your throws list. An Interrupt indicates that another thread wishes your thread to end. The reason for this request is not made evident and is entirely contextual, so if you don't have any additional knowledge you should assume it's just a friendly shutdown, and anything that avoids that shutdown is a non-friendly response.

Java will not randomly throw InterruptedException's, all advice will not affect your application but I have run into a case where developer's following the "swallow" strategy became very inconvenient. A team had developed a large set of tests and used Thread.Sleep a lot. Now we started to run the tests in our CI server, and sometimes due to defects in the code would get stuck into permanent waits. To make the situation worse, when attempting to cancel the CI job it never closed because the Thread.Interrupt that was intended to abort the test did not abort the job. We had to login to the box and manually kill the processes.

So long story short, if you simply throw the InterruptedException you are matching the default intent that your thread should end. If you can't add InterruptedException to your throw list, I'd wrap it in a RuntimeException.

There is a very rational argument to be made that InterruptedException should be a RuntimeException itself, since that would encourage a better "default" handling. It's not a RuntimeException only because the designers stuck to a categorical rule that a RuntimeException should represent an error in your code. Since an InterruptedException does not arise directly from an error in your code, it's not. But the reality is that often an InterruptedException arises because there is an error in your code, (i.e. endless loop, dead-lock), and the Interrupt is some other thread's method for dealing with that error.

If you know there is rational cleanup to be done, then do it. If you know a deeper cause for the Interrupt, you can take on more comprehensive handling.

So in summary your choices for handling should follow this list:

  1. By default, add to throws.
  2. If not allowed to add to throws, throw RuntimeException(e). (Best choice of multiple bad options)
  3. Only when you know an explicit cause of the Interrupt, handle as desired. If your handling is local to your method, then reset interrupted by a call to Thread.currentThread().interrupt().

MySQL vs MongoDB 1000 reads

Here is a little research that explored RDBMS vs NoSQL using MySQL vs Mongo, the conclusions were inline with @Sean Reilly's response. In short, the benefit comes from the design, not some raw speed difference. Conclusion on page 35-36:

RDBMS vs NoSQL: Performance and Scaling Comparison

The project tested, analysed and compared the performance and scalability of the two database types. The experiments done included running different numbers and types of queries, some more complex than others, in order to analyse how the databases scaled with increased load. The most important factor in this case was the query type used as MongoDB could handle more complex queries faster due mainly to its simpler schema at the sacrifice of data duplication meaning that a NoSQL database may contain large amounts of data duplicates. Although a schema directly migrated from the RDBMS could be used this would eliminate the advantage of MongoDB’s underlying data representation of subdocuments which allowed the use of less queries towards the database as tables were combined. Despite the performance gain which MongoDB had over MySQL in these complex queries, when the benchmark modelled the MySQL query similarly to the MongoDB complex query by using nested SELECTs MySQL performed best although at higher numbers of connections the two behaved similarly. The last type of query benchmarked which was the complex query containing two JOINS and and a subquery showed the advantage MongoDB has over MySQL due to its use of subdocuments. This advantage comes at the cost of data duplication which causes an increase in the database size. If such queries are typical in an application then it is important to consider NoSQL databases as alternatives while taking in account the cost in storage and memory size resulting from the larger database size.

How to detect iPhone 5 (widescreen devices)?

this is the macro for my cocos2d project. should be the same for other apps.

#define WIDTH_IPAD 1024
#define WIDTH_IPHONE_5 568
#define WIDTH_IPHONE_4 480
#define HEIGHT_IPAD 768
#define HEIGHT_IPHONE 320

#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

//width is height!
#define IS_IPHONE_5 ( [ [ UIScreen mainScreen ] bounds ].size.height == WIDTH_IPHONE_5 )
#define IS_IPHONE_4 ( [ [ UIScreen mainScreen ] bounds ].size.height == WIDTH_IPHONE_4 )

#define cp_ph4(__X__, __Y__) ccp(cx_ph4(__X__), cy_ph4(__Y__))
#define cx_ph4(__X__) (IS_IPAD ? (__X__ * WIDTH_IPAD / WIDTH_IPHONE_4) : (IS_IPHONE_5 ? (__X__ * WIDTH_IPHONE_5 / WIDTH_IPHONE_4) : (__X__)))
#define cy_ph4(__Y__) (IS_IPAD ? (__Y__ * HEIGHT_IPAD / HEIGHT_IPHONE) : (__Y__))

#define cp_pad(__X__, __Y__) ccp(cx_pad(__X__), cy_pad(__Y__))
#define cx_pad(__X__) (IS_IPAD ? (__X__) : (IS_IPHONE_5 ? (__X__ * WIDTH_IPHONE_5 / WIDTH_IPAD) : (__X__ * WIDTH_IPHONE_4 / WIDTH_IPAD)))
#define cy_pad(__Y__) (IS_IPAD ? (__Y__) : (__Y__ * HEIGHT_IPHONE / HEIGHT_IPAD))

Largest and smallest number in an array

Int[] number ={1,2,3,4,5,6,7,8,9,10};
Int? Result = null;
 foreach(Int i in number)

    {
       If(!Result.HasValue || i< Result)

        { 

            Result =i;
         }
     }

     Console.WriteLine(Result);
   }

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

How to call Android contacts list?

Looking around for an API Level 5 solution using ContactsContract API you could slightly modify the code above with the following:

  Intent intent = new Intent(Intent.ACTION_PICK);
  intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
  startActivityForResult(intent, PICK_CONTACT);

And then in onActivityResult use the column name:

  ContactsContract.Contacts.DISPLAY_NAME

TortoiseSVN icons overlay not showing after updating to Windows 10

I fixed my problems with TortoiseSVN icons not showing up in Windows 10, for the special case where my repository was on a removable drive.

There is a Tortoise setting that determines which Drive Types the icons are used with: Drives A: and B:, Removable drives, Network drives, Fixed drives, CD-ROM, RAM drives, and Unknown drives.

It was NOT a problem with the naming of the icon overlays in the Windows Registry.

The names were automatically prefixed with "1", "2", etc.

to force them (in my computer) alphabetically at the top of the list just before the OneDrive icons.

So, all of the icons were within the top 15. To get to the Tortoise settings, right click on Desktop or a folder and then choose TortoiseSVN > Settings.

In Settings, choose Icon Overlays. There'll you find the Drive Types settings.

Timeout for python requests.get entire response

I came up with a more direct solution that is admittedly ugly but fixes the real problem. It goes a bit like this:

resp = requests.get(some_url, stream=True)
resp.raw._fp.fp._sock.settimeout(read_timeout)
# This will load the entire response even though stream is set
content = resp.content

You can read the full explanation here

Creating a new directory in C

I want to write a program that (...) creates the directory and a (...) file inside of it

because this is a very common question, here is the code to create multiple levels of directories and than call fopen. I'm using a gnu extension to print the error message with printf.

void rek_mkdir(char *path) {
    char *sep = strrchr(path, '/');
    if(sep != NULL) {
        *sep = 0;
        rek_mkdir(path);
        *sep = '/';
    }
    if(mkdir(path, 0777) && errno != EEXIST)
        printf("error while trying to create '%s'\n%m\n", path); 
}

FILE *fopen_mkdir(char *path, char *mode) {
    char *sep = strrchr(path, '/');
    if(sep) { 
        char *path0 = strdup(path);
        path0[ sep - path ] = 0;
        rek_mkdir(path0);
        free(path0);
    }
    return fopen(path,mode);
}

How can I render Partial views in asp.net mvc 3?

<%= Html.Partial("PartialName", Model) %>

how to filter out a null value from spark dataframe

From the hint from Michael Kopaniov, below works

df.where(df("id").isNotNull).show

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

CSS transition shorthand with multiple properties?

This helped me understand / streamline, only what I needed to animate:

// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}

.base {
  max-width: 0vw;
  opacity: 0;

  transition-property: max-width, opacity; // relative order
  transition-duration: 2s, 4s; // effects relatively ordered animation properties
  transition-delay: 6s; // effects delay of all animation properties
  animation-timing-function: ease;

  &:hover {
    max-width: 100vw;
    opacity: 1;

    transition-duration: 5s; // effects duration of all aniomation properties
    transition-delay: 2s, 7s; // effects relatively ordered animation properties
  }
}

~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class

Removing viewcontrollers from navigation stack

This solution worked for me in swift 4:

let VCCount = self.navigationController!.viewControllers.count
self.navigationController?.viewControllers.removeSubrange(Range(VCCount-3..<VCCount - 1))

your current view controller index in stack is:

self.navigationController!.viewControllers.count - 1

Get height and width of a layout programmatically

As I just ran into this problem thought I would write it for kotlin,

my_view.viewTreeObserver.addOnGlobalLayoutListener {
       // here your view is measured
       // get height using my_view.height
       // get width using my_view.width
    }

or

my_view.post {
       // here your view is measured
       // get height using my_view.height
       // get width using my_view.width
    }

ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)

Give hibernate.connection.url as "jdbc:oracle:thin:@127.0.0.1:1521:xe" then you can solve above issue. Because oracle's default SID is "xe" so we should give like this. When I gave like this data has been inserted into DB without any SQL exceptions, it's my real time experience.

Developing for Android in Eclipse: R.java not regenerating

First of all, check the Console output.
Then, check if your xml layout files names are lower-case only.
Correct xml errors.
Check Project properties -> Android for something unfamiliar

How to get first/top row of the table in Sqlite via Sql Query

LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

How can I create objects while adding them into a vector?

// create a vector of unknown players.
std::vector<player> players;

// resize said vector to only contain 6 players.
players.resize(6);

Values are always initialized, so a vector of 6 players is a vector of 6 valid player objects.

As for the second part, you need to use pointers. Instantiating c++ interface as a child class

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

How to write hello world in assembler under Windows?

The best examples are those with fasm, because fasm doesn't use a linker, which hides the complexity of windows programming by another opaque layer of complexity. If you're content with a program that writes into a gui window, then there is an example for that in fasm's example directory.

If you want a console program, that allows redirection of standard in and standard out that is also possible. There is a (helas highly non-trivial) example program available that doesn't use a gui, and works strictly with the console, that is fasm itself. This can be thinned out to the essentials. (I've written a forth compiler which is another non-gui example, but it is also non-trivial).

Such a program has the following command to generate a proper header for 32-bit executable, normally done by a linker.

FORMAT PE CONSOLE 

A section called '.idata' contains a table that helps windows during startup to couple names of functions to the runtimes addresses. It also contains a reference to KERNEL.DLL which is the Windows Operating System.

 section '.idata' import data readable writeable
    dd 0,0,0,rva kernel_name,rva kernel_table
    dd 0,0,0,0,0

  kernel_table:
    _ExitProcess@4    DD rva _ExitProcess
    CreateFile        DD rva _CreateFileA
        ...
        ...
    _GetStdHandle@4   DD rva _GetStdHandle
                      DD 0

The table format is imposed by windows and contains names that are looked up in system files, when the program is started. FASM hides some of the complexity behind the rva keyword. So _ExitProcess@4 is a fasm label and _exitProcess is a string that is looked up by Windows.

Your program is in section '.text'. If you declare that section readable writeable and executable, it is the only section you need to add.

    section '.text' code executable readable writable

You can call all the facilities you declared in the .idata section. For a console program you need _GetStdHandle to find he filedescriptors for standard in and standardout (using symbolic names like STD_INPUT_HANDLE which fasm finds in the include file win32a.inc). Once you have the file descriptors you can do WriteFile and ReadFile. All functions are described in the kernel32 documentation. You are probably aware of that or you wouldn't try assembler programming.

In summary: There is a table with asci names that couple to the windows OS. During startup this is transformed into a table of callable addresses, which you use in your program.

White space at top of page

overflow: auto

Using overflow: auto on the <body> tag is a cleaner solution and will work a charm.

Creating a textarea with auto-resize

For those who want the textarea to be auto resized on both width and height:

HTML:

<textarea class='textbox'></textarea>
<div>
  <span class='tmp_textbox'></span>
</div>

CSS:

.textbox,
.tmp_textbox {
  font-family: 'Arial';
  font-size: 12px;
  resize: none;
  overflow:hidden;
}

.tmp_textbox {
  display: none;
}

jQuery:

$(function(){
  //alert($('.textbox').css('padding'))
  $('.textbox').on('keyup change', checkSize)
  $('.textbox').trigger('keyup')

  function checkSize(){
    var str = $(this).val().replace(/\r?\n/g, '<br/>');
    $('.tmp_textbox').html( str )
    console.log($(this).val())

    var strArr = str.split('<br/>')
    var row = strArr.length
    $('.textbox').attr('rows', row)
    $('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
  }
})

Codepen:

http://codepen.io/anon/pen/yNpvJJ

Cheers,

Check if the number is integer

Another alternative is to check the fractional part:

x%%1==0

or, if you want to check within a certain tolerance:

min(abs(c(x%%1, x%%1-1))) < tol

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

Java error: Implicit super constructor is undefined for default constructor

For those who Google for this error and arrive here: there might be another reason for receiving it. Eclipse gives this error when you have project setup - system configuration mismatch.

For example, if you import Java 1.7 project to Eclipse and you do not have 1.7 correctly set up then you will get this error. Then you can either go to Project - Preference - Java - Compiler and switch to 1.6 or earlier; or go to Window - Preferences - Java - Installed JREs and add/fix your JRE 1.7 installation.

Vertically align text to top within a UILabel

Just in case it's of any help to anyone, I had the same problem but was able to solve the issue simply by switching from using UILabel to using UITextView. I appreciate this isn't for everyone because the functionality is a bit different.

If you do switch to using UITextView, you can turn off all the Scroll View properties as well as User Interaction Enabled... This will force it to act more like a label.

enter image description here

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

Delete cookie by name?

I'm not really sure if that was the situation with Roundcube version from May '12, but for current one the answer is that you can't delete roundcube_sessauth cookie from JavaScript, as it is marked as HttpOnly. And this means it's not accessible from JS client side code and can be removed only by server side script or by direct user action (via some browser mechanics like integrated debugger or some plugin).

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

Using psql how do I list extensions installed in a database?

This SQL query gives output similar to \dx:

SELECT e.extname AS "Name", e.extversion AS "Version", n.nspname AS "Schema", c.description AS "Description" 
FROM pg_catalog.pg_extension e 
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = e.extnamespace 
LEFT JOIN pg_catalog.pg_description c ON c.objoid = e.oid AND c.classoid = 'pg_catalog.pg_extension'::pg_catalog.regclass 
ORDER BY 1;

Thanks to https://blog.dbi-services.com/listing-the-extensions-available-in-postgresql/

How to sort by two fields in Java?

You can use Java 8 Lambda approach to achieve this. Like this:

persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));

Date Comparison using Java

It is easier to compare dates using the java.util.Calendar. Here is what you might do:

Calendar toDate = Calendar.getInstance();
Calendar nowDate = Calendar.getInstance();
toDate.set(<set-year>,<set-month>,<set-day>);  
if(!toDate.before(nowDate)) {
    //display your report
} else {
    // don't display the report
}

How to get the exact local time of client?

Nowadays you can get correct timezone of a user having just one line of code:

const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/resolvedOptions

You can then use moment-timezone to parse timezone like:

const currentTime = moment().tz(timezone).format();

Integer expression expected error in shell script

This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.

For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like "\n" or "\r".

For example:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

This will result in a script error : integer expression expected because $a contains a non-digit newline character "\n". You have to remove this character using the instructions here: How to remove carriage return from a string in Bash

So use something like this:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234\n"
a='1234
'

# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'\t\r\n ']}"

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

You can also use set -xv to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I also wanted this and came up with this solution (I'm only using the date part - a default time makes no sense as a PropertyGrid default):

public class DefaultDateAttribute : DefaultValueAttribute {
  public DefaultDateAttribute(short yearoffset)
    : base(DateTime.Now.AddYears(yearoffset).Date) {
  }
}

This just creates a new attribute that you can add to your DateTime property. E.g. if it defaults to DateTime.Now.Date:

[DefaultDate(0)]

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.

Find object by its property in array of objects with AngularJS way

The solucion that work for me is the following

$filter('filter')(data, {'id':10}) 

"Cross origin requests are only supported for HTTP." error when loading a local file

One way it worked loading local files is using them with in the project folder instead of outside your project folder. Create one folder under your project example files similar to the way we create for images and replace the section where using complete local path other than project path and use relative url of file under project folder . It worked for me

key_load_public: invalid format

There is a simple solution if you can install and use puttygen tool. Below are the steps. You should have the passphrase of the private key.

step 1: Download latest puttygen and open puttygen

step 2: Load your existing private key file, see below image

Load an existing private key

step 3: Enter passphrase for key if asked and hit ok

enter paasphrase

step 4: as shown in the below image select "conversion" menu tab and select "Export OpenSSH key"

save OpenSSH file

Save new private key file at preferred location and use accordingly.

Best way to integrate Python and JavaScript?

PyExecJS is able to use each of PyV8, Node, JavaScriptCore, SpiderMonkey, JScript.

>>> import execjs
>>> execjs.eval("'red yellow blue'.split(' ')")
['red', 'yellow', 'blue']
>>> execjs.get().name
'Node.js (V8)'

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub

How to get MAC address of your machine using a C program?

Expanding on the answer given by @user175104 ...

std::vector<std::string> GetAllFiles(const std::string& folder, bool recursive = false)
{
  // uses opendir, readdir, and struct dirent.
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

bool ReadFileContents(const std::string& folder, const std::string& fname, std::string& contents)
{
  // uses ifstream to read entire contents
  // left as an exercise to the reader, as it isn't the point of this OP and answer.
}

std::vector<std::string> GetAllMacAddresses()
{
  std::vector<std::string> macs;
  std::string address;

  // from: https://stackoverflow.com/questions/9034575/c-c-linux-mac-address-of-all-interfaces
  //  ... just read /sys/class/net/eth0/address

  // NOTE: there may be more than one: /sys/class/net/*/address
  //  (1) so walk /sys/class/net/* to find the names to read the address of.

  std::vector<std::string> nets = GetAllFiles("/sys/class/net/", false);
  for (auto it = nets.begin(); it != nets.end(); ++it)
  {
    // we don't care about the local loopback interface
    if (0 == strcmp((*it).substr(-3).c_str(), "/lo"))
      continue;
    address.clear();
    if (ReadFileContents(*it, "address", address))
    {
      if (!address.empty())
      {
        macs.push_back(address);
      }
    }
  }
  return macs;
}

How can I easily view the contents of a datatable or dataview in the immediate window

The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.

To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a magnifying glass icon. Click on that icon and your DataTable will open up in a grid view.

enter image description here

How to create nested directories using Mkdir in Golang?

An utility method like the following can be used to solve this.

import (
  "os"
  "path/filepath"
  "log"
)

func ensureDir(fileName string) {
  dirName := filepath.Dir(fileName)
  if _, serr := os.Stat(dirName); serr != nil {
    merr := os.MkdirAll(dirName, os.ModePerm)
    if merr != nil {
        panic(merr)
    }
  }
}



func main() {
  _, cerr := os.Create("a/b/c/d.txt")
  if cerr != nil {
    log.Fatal("error creating a/b/c", cerr)
  }
  log.Println("created file in a sub-directory.")
}

How do I comment out a block of tags in XML?

You can wrap the text with a non-existing processing-instruction, e.g.:

<detail>
<?ignore
  <band height="20">
    <staticText>
      <reportElement x="180" y="0" width="200" height="20"/>
      <text><![CDATA[Hello World!]]></text>
    </staticText>
  </band>
?>
</detail>

Nested processing instructions are not allowed and '?>' ends the processing instruction (see http://www.w3.org/TR/REC-xml/#sec-pi)

How to unset (remove) a collection element after fetching it?

Or you can use reject method

$newColection = $collection->reject(function($element) {
    return $item->selected != true;
});

or pull method

$selected = []; 
foreach ($collection as $key => $item) {
      if ($item->selected == true) {
          $selected[] = $collection->pull($key);
      }
}

How to convert CharSequence to String?

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();

Only Add Unique Item To List

Just like the accepted answer says a HashSet doesn't have an order. If order is important you can continue to use a List and check if it contains the item before you add it.

if (_remoteDevices.Contains(rDevice))
    _remoteDevices.Add(rDevice);

Performing List.Contains() on a custom class/object requires implementing IEquatable<T> on the custom class or overriding the Equals. It's a good idea to also implement GetHashCode in the class as well. This is per the documentation at https://msdn.microsoft.com/en-us/library/ms224763.aspx

public class RemoteDevice: IEquatable<RemoteDevice>
{
    private readonly int id;
    public RemoteDevice(int uuid)
    {
        id = id
    }
    public int GetId
    {
        get { return id; }
    }

    // ...

    public bool Equals(RemoteDevice other)
    {
        if (this.GetId == other.GetId)
            return true;
        else
            return false;
    }
    public override int GetHashCode()
    {
        return id;
    }
}

Why would we call cin.clear() and cin.ignore() after reading input?

use cin.ignore(1000,'\n') to clear all of chars of the previous cin.get() in the buffer and it will choose to stop when it meet '\n' or 1000 chars first.

PPT to PNG with transparent background

Insert a coloured box the full size of the slide, set colour to white with 100% transparency. select all, right-click save as picture, select PNG and save.

copy/paste inserted colour box to each slide and repeat

Using setattr() in python

The Python docs say all that needs to be said, as far as I can see.

setattr(object, name, value)

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

If this isn't enough, explain what you don't understand.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

My solotion for responsive/dropdown navbar with angular-ui bootstrap (when update to angular 1.5 and, ui-bootrap 1.2.1)
index.html

     ...    
    <link rel="stylesheet" href="/css/app.css">
</head>
<body>


<nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <input type="checkbox" id="navbar-toggle-cbox">
            <div class="navbar-header">
                <label for="navbar-toggle-cbox" class="navbar-toggle" 
                       ng-init="navCollapsed = true" 
                       ng-click="navCollapsed = !navCollapsed"  
                       aria-controls="navbar">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </label>
                <a class="navbar-brand" href="#">Project name</a>
                 <div id="navbar" class="collapse navbar-collapse"  ng-class="{'in':!navCollapsed}">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="/view1">Home</a></li>
                        <li><a href="/view2">About</a></li>
                        <li><a href="#">Contact</a></li>
                        <li uib-dropdown>
                            <a href="#" uib-dropdown-toggle>Dropdown <b class="caret"></b></a>
                            <ul uib-dropdown-menu role="menu" aria-labelledby="split-button">
                                <li role="menuitem"><a href="#">Action</a></li>
                                <li role="menuitem"><a href="#">Another action</a></li>                                   
                            </ul>
                        </li>

                    </ul>
                 </div>
            </div>
        </div>
    </nav>

app.css

/* show the collapse when navbar toggle is checked */
#navbar-toggle-cbox:checked ~ .collapse {
    display: block;
}

/* the checkbox used only internally; don't display it */
#navbar-toggle-cbox {
  display:none
}

How to randomize (or permute) a dataframe rowwise and columnwise?

Take a look at permatswap() in the vegan package. Here is an example maintaining both row and column totals, but you can relax that and fix only one of the row or column sums.

mat <- matrix(c(1,1,0,0,0,0,0,1,1,0,0,0,1,1,1,0,1,0,1,1), ncol = 5)
set.seed(4)
out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")

This gives:

R> out$perm[[1]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    1    1    1
[2,]    0    1    0    1    0
[3,]    0    0    0    1    1
[4,]    1    0    0    0    1
R> out$perm[[2]]
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    1    0    1    1
[2,]    0    0    0    1    1
[3,]    1    0    0    1    0
[4,]    0    0    1    0    1

To explain the call:

out <- permatswap(mat, times = 99, burnin = 20000, thin = 500, mtype = "prab")
  1. times is the number of randomised matrices you want, here 99
  2. burnin is the number of swaps made before we start taking random samples. This allows the matrix from which we sample to be quite random before we start taking each of our randomised matrices
  3. thin says only take a random draw every thin swaps
  4. mtype = "prab" says treat the matrix as presence/absence, i.e. binary 0/1 data.

A couple of things to note, this doesn't guarantee that any column or row has been randomised, but if burnin is long enough there should be a good chance of that having happened. Also, you could draw more random matrices than you need and discard ones that don't match all your requirements.

Your requirement to have different numbers of changes per row, also isn't covered here. Again you could sample more matrices than you want and then discard the ones that don't meet this requirement also.

How do I debug error ECONNRESET in Node.js?

I just figured this out, at least in my use case.

I was getting ECONNRESET. It turned out that the way my client was set up, it was hitting the server with an API call a ton of times really quickly -- and it only needed to hit the endpoint once.

When I fixed that, the error was gone.

List Git commits not pushed to the origin yet

git log origin/master..master

or, more generally:

git log <since>..<until>

You can use this with grep to check for a specific, known commit:

git log <since>..<until> | grep <commit-hash>

Or you can also use git-rev-list to search for a specific commit:

git rev-list origin/master | grep <commit-hash>

What is the correct way to read a serial port using .NET framework?

I used similar code to @MethodMan but I had to keep track of the data the serial port was sending and look for a terminating character to know when the serial port was done sending data.

private string buffer { get; set; }
private SerialPort _port { get; set; }

public Port() 
{
    _port = new SerialPort();
    _port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
    buffer = string.Empty;
}

private void dataReceived(object sender, SerialDataReceivedEventArgs e)
{    
    buffer += _port.ReadExisting();

    //test for termination character in buffer
    if (buffer.Contains("\r\n"))
    {
        //run code on data received from serial port
    }
}

What is the difference between buffer and cache memory in Linux?

Seth Robertson's Link 2 said "For thorough understanding of those terms, refer to Linux kernel book like Linux Kernel Development by Robert M. Love."

I found some contents about 'buffer' in the 2nd edition of the book.

Although the physical device itself is addressable at the sector level, the kernel performs all disk operations in terms of blocks.

When a block is stored in memory (say, after a read or pending a write), it is stored in a 'buffer'. Each 'buffer' is associated with exactly one block. The 'buffer' serves as the object that represents a disk block in memory.

A 'buffer' is the in-memory representation of a single physical disk block.

Block I/O operations manipulate a single disk block at a time. A common block I/O operation is reading and writing inodes. The kernel provides the bread() function to perform a low-level read of a single block from disk. Via 'buffers', disk blocks are mapped to their associated in-memory pages. "

How can I search sub-folders using glob.glob module?

There's a lot of confusion on this topic. Let me see if I can clarify it (Python 3.7):

  1. glob.glob('*.txt') :matches all files ending in '.txt' in current directory
  2. glob.glob('*/*.txt') :same as 1
  3. glob.glob('**/*.txt') :matches all files ending in '.txt' in the immediate subdirectories only, but not in the current directory
  4. glob.glob('*.txt',recursive=True) :same as 1
  5. glob.glob('*/*.txt',recursive=True) :same as 3
  6. glob.glob('**/*.txt',recursive=True):matches all files ending in '.txt' in the current directory and in all subdirectories

So it's best to always specify recursive=True.

Disable PHP in directory (including all sub-directories) with .htaccess

To disable all access to sub dirs (safest) use:

<Directory full-path-to/USERS>
     Order Deny,Allow
     Deny from All
 </Directory>

If you want to block only PHP files from being served directly, then do:

1 - Make sure you know what file extensions the server recognizes as PHP (and dont' allow people to override in htaccess). One of my servers is set to:

# Example of existing recognized extenstions:
AddType application/x-httpd-php .php .phtml .php3

2 - Based on the extensions add a Regular Expression to FilesMatch (or LocationMatch)

 <Directory full-path-to/USERS>
     <FilesMatch "(?i)\.(php|php3?|phtml)$">
            Order Deny,Allow
            Deny from All
    </FilesMatch>
 </Directory>

Or use Location to match php files (I prefer the above files approach)

<LocationMatch "/USERS/.*(?i)\.(php3?|phtml)$">
     Order Deny,Allow
     Deny from All
</LocationMatch>

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

Android Studio doesn't see device

I was facing the same issue. Turned out to be a faulty data cable. The device would start charging but would not show up in connected devices in Android Studio.

Trying another cable worked fine.

Try another cable first if you have been using your current one for a while.

How to find list of possible words from a letter matrix [Boggle Solver]

You could split the problem up into two pieces:

  1. Some kind of search algorithm that will enumerate possible strings in the grid.
  2. A way of testing whether a string is a valid word.

Ideally, (2) should also include a way of testing whether a string is a prefix of a valid word – this will allow you to prune your search and save a whole heap of time.

Adam Rosenfield's Trie is a solution to (2). It's elegant and probably what your algorithms specialist would prefer, but with modern languages and modern computers, we can be a bit lazier. Also, as Kent suggests, we can reduce our dictionary size by discarding words that have letters not present in the grid. Here's some python:

def make_lookups(grid, fn='dict.txt'):
    # Make set of valid characters.
    chars = set()
    for word in grid:
        chars.update(word)

    words = set(x.strip() for x in open(fn) if set(x.strip()) <= chars)
    prefixes = set()
    for w in words:
        for i in range(len(w)+1):
            prefixes.add(w[:i])

    return words, prefixes

Wow; constant-time prefix testing. It takes a couple of seconds to load the dictionary you linked, but only a couple :-) (notice that words <= prefixes)

Now, for part (1), I'm inclined to think in terms of graphs. So I'll build a dictionary that looks something like this:

graph = { (x, y):set([(x0,y0), (x1,y1), (x2,y2)]), }

i.e. graph[(x, y)] is the set of coordinates that you can reach from position (x, y). I'll also add a dummy node None which will connect to everything.

Building it's a bit clumsy, because there's 8 possible positions and you have to do bounds checking. Here's some correspondingly-clumsy python code:

def make_graph(grid):
    root = None
    graph = { root:set() }
    chardict = { root:'' }

    for i, row in enumerate(grid):
        for j, char in enumerate(row):
            chardict[(i, j)] = char
            node = (i, j)
            children = set()
            graph[node] = children
            graph[root].add(node)
            add_children(node, children, grid)

    return graph, chardict

def add_children(node, children, grid):
    x0, y0 = node
    for i in [-1,0,1]:
        x = x0 + i
        if not (0 <= x < len(grid)):
            continue
        for j in [-1,0,1]:
            y = y0 + j
            if not (0 <= y < len(grid[0])) or (i == j == 0):
                continue

            children.add((x,y))

This code also builds up a dictionary mapping (x,y) to the corresponding character. This lets me turn a list of positions into a word:

def to_word(chardict, pos_list):
    return ''.join(chardict[x] for x in pos_list)

Finally, we do a depth-first search. The basic procedure is:

  1. The search arrives at a particular node.
  2. Check if the path so far could be part of a word. If not, don't explore this branch any further.
  3. Check if the path so far is a word. If so, add to the list of results.
  4. Explore all children not part of the path so far.

Python:

def find_words(graph, chardict, position, prefix, results, words, prefixes):
    """ Arguments:
      graph :: mapping (x,y) to set of reachable positions
      chardict :: mapping (x,y) to character
      position :: current position (x,y) -- equals prefix[-1]
      prefix :: list of positions in current string
      results :: set of words found
      words :: set of valid words in the dictionary
      prefixes :: set of valid words or prefixes thereof
    """
    word = to_word(chardict, prefix)

    if word not in prefixes:
        return

    if word in words:
        results.add(word)

    for child in graph[position]:
        if child not in prefix:
            find_words(graph, chardict, child, prefix+[child], results, words, prefixes)

Run the code as:

grid = ['fxie', 'amlo', 'ewbx', 'astu']
g, c = make_graph(grid)
w, p = make_lookups(grid)
res = set()
find_words(g, c, None, [], res, w, p)

and inspect res to see the answers. Here's a list of words found for your example, sorted by size:

 ['a', 'b', 'e', 'f', 'i', 'l', 'm', 'o', 's', 't',
 'u', 'w', 'x', 'ae', 'am', 'as', 'aw', 'ax', 'bo',
 'bu', 'ea', 'el', 'em', 'es', 'fa', 'ie', 'io', 'li',
 'lo', 'ma', 'me', 'mi', 'oe', 'ox', 'sa', 'se', 'st',
 'tu', 'ut', 'wa', 'we', 'xi', 'aes', 'ame', 'ami',
 'ase', 'ast', 'awa', 'awe', 'awl', 'blo', 'but', 'elb',
 'elm', 'fae', 'fam', 'lei', 'lie', 'lim', 'lob', 'lox',
 'mae', 'maw', 'mew', 'mil', 'mix', 'oil', 'olm', 'saw',
 'sea', 'sew', 'swa', 'tub', 'tux', 'twa', 'wae', 'was',
 'wax', 'wem', 'ambo', 'amil', 'amli', 'asem', 'axil',
 'axle', 'bleo', 'boil', 'bole', 'east', 'fame', 'limb',
 'lime', 'mesa', 'mewl', 'mile', 'milo', 'oime', 'sawt',
 'seam', 'seax', 'semi', 'stub', 'swam', 'twae', 'twas',
 'wame', 'wase', 'wast', 'weam', 'west', 'amble', 'awest',
 'axile', 'embox', 'limbo', 'limes', 'swami', 'embole',
 'famble', 'semble', 'wamble']

The code takes (literally) a couple of seconds to load the dictionary, but the rest is instant on my machine.

Change R default library path using .libPaths in Rprofile.site fails to work

The proper solution is to set environment variable R_LIBS_USER to the value of the file path to your desired library folder as opposed to getting RStudio to recognize a Rprofile.site file.

To set environment variable R_LIBS_USER in Windows, go to the Control Panel (System Properties -> Advanced system properties -> Environment Variables -> User Variables) to a desired value (the path to your library folder), e.g.

Variable name: R_LIBS_USER 
Variable value: C:/software/Rpackages  

If for some reason you do not have access to the control panel, you can try running rundll32 sysdm.cpl,EditEnvironmentVariables from the command line on Windows and add the environment variable from there.

Setting R_LIBS_USER will ensure that the library shows up first in .libPaths() regardless of starting RStudio directly or by right-clicking an file and "Open With" to start RStudio.

The Rprofile solution can work if RStudio is always started by clicking the RStudio shortcut. In this case, setting the default working directory to the directory that houses your Rprofile will be sufficient. The Rprofile solution does not work when clicking on a file to start RStudio because that changes the working directory away from the default working directory.

How to set session timeout in web.config

If you want to set the timeout to 20 minutes, use something like this:

    <configuration>
      <system.web>
         <sessionState timeout="20"></sessionState>
      </system.web>
    </configuration>

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

Ruby capitalize every word first letter

"hello world".split.each{|i| i.capitalize!}.join(' ')

Inner Joining three tables

Just do the same thing agin but then for TableC

SELECT *
FROM dbo.tableA A 
INNER JOIN dbo.TableB B ON A.common = B.common
INNER JOIN dbo.TableC C ON A.common = C.common

PHP cURL not working - WAMP on Windows 7 64 bit

This is what worked for me

Answered by Soren from another SO thread - CURL for WAMP

"There seems to be a bug somewhere. If you are experiencing this on Win 7 64 bit then try installing apache addon version 2.2.9 and php addon version 5.3.1 and switching to those in WAMP and then activating the CURL extension. That worked for me."

How to increment variable under DOS?

Directly from the command line:

 for /L %n in (1,1,100) do @echo %n

Using a batch file:

 @echo off
 for /L %%n in (1,1,100) do echo %%n

Displays:

 1
 2
 3
 ...
 100

Link to all Visual Studio $ variables

If you need to find values for variables other than those standard VS macros, you could do that easily using Process Explorer. Start it, find the process your Visual Studio instance runs in, right click, Properties ? Environment. It lists all those $ vars as key-value pairs: enter image description here

BAT file to map to network drive without running as admin

This .vbs code creates a .bat file with the current mapped network drives. Then, just put the created file into the machine which you want to re-create the mappings and double-click it. It will try to create all mappings using the same drive letters (errors can occur if any letter is in use). This method also can be used as a backup of the current mappings. Save the code bellow as a .vbs file (e.g. Mappings.vbs) and double-click it.

' ********** My Code **********
Set wshShell = CreateObject( "WScript.Shell" )

' ********** Get ComputerName
strComputer = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )

' ********** Get Domain 
sUserDomain = createobject("wscript.network").UserDomain

Set Connect = GetObject("winmgmts://"&strComputer)
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections

' ********** Current Path
sCurrentPath = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

' ********** Blank the report message
strMsg = ""

' ********** Set objects 
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objWbem = GetObject("winmgmts:")
Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")

' ********** Get UserName
sUser = CreateObject("WScript.Network").UserName

' ********** Print user and computer
'strMsg = strMsg & "    User: " & sUser & VbCrLf
'strMsg = strMsg & "Computer: " & strComputer & VbCrLf & VbCrLf

strMsg = strMsg & "###  COPIED FROM " & strComputer & " ###" & VbCrLf& VbCrLf
strMsg = strMsg & "@echo off" & vbCrLf

For i = 0 to oDrives.Count - 1 Step 2
    strMsg = strMsg & "net use " & oDrives.Item(i) & " " & oDrives.Item(i+1) & " /user:" & sUserDomain & "\" & sUser & " /persistent:yes" & VbCrLf
Next
strMsg = strMsg & ":exit" & VbCrLf
strMsg = strMsg & "@pause" & VbCrLf

' ********** write the file to disk.
strDirectory = sCurrentPath 
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
    ' Procede
Else
    Set objFolder = objFSO.CreateFolder(strDirectory)
End if

' ********** Calculate date serial for filename **********
intMonth = month(now)
if intMonth < 10 then
    strThisMonth = "0" & intMonth
else
    strThisMonth = intMOnth
end if
intDay = Day(now)
if intDay < 10 then
    strThisDay = "0" & intDay
else
    strThisDay = intDay
end if
strFilenameDateSerial = year(now) & strThisMonth & strThisDay
    sFileName = strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".bat"
    Set objFile = objFSO.CreateTextFile(sFileName,True) 
objFile.Write strMsg & vbCrLf

' ********** Ask to view file
strFinish = "End: A .bat was generated. " & VbCrLf & "Copy the generated file  (" & sFileName & ")  into the machine where you want to recreate the mappings and double-click it." & VbCrLf & VbCrLf 
MsgBox(strFinish)

Convert List(of object) to List(of string)

This works for all types.

List<object> objects = new List<object>();
List<string> strings = objects.Select(s => (string)s).ToList();

Creating Threads in python

Did you override the run() method? If you overrided __init__, did you make sure to call the base threading.Thread.__init__()?

After starting the two threads, does the main thread continue to do work indefinitely/block/join on the child threads so that main thread execution does not end before the child threads complete their tasks?

And finally, are you getting any unhandled exceptions?

How to install pip in CentOS 7?

Update 2019

I tried easy_install at first but it doesn't install packages in a clean and intuitive way. Also when it comes time to remove packages it left a lot of artifacts that needed to be cleaned up.

sudo yum install epel-release
sudo yum install python34-pip
pip install package

Was the solution that worked for me, it installs "pip3" as pip on the system. It also uses standard rpm structure so it clean in its removal. I am not sure what process you would need to take if you want both python2 and python3 package manager on your system.

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

you have to add vm argument while running the program. This should be like

-Dwebdriver.firefox.bin=/custom/path/of/firefox/exe

In IntelliJ IDE much simpler Goto Run ? Edit Configurations... In VM options add the above.

IntelliJ Run Configurations

Eclipse also have the options to give vm argument while running. This way I am using portable Firefox with selenium.

hasOwnProperty in JavaScript

Try this:

function welcomeMessage()
{
    var shape1 = new Shape();
    //alert(shape1.draw());
    alert(shape1.hasOwnProperty("name"));
}

When working with reflection in JavaScript, member objects are always refered to as the name as a string. For example:

for(i in obj) { ... }

The loop iterator i will be hold a string value with the name of the property. To use that in code you have to address the property using the array operator like this:

 for(i in obj) {
   alert("The value of obj." + i + " = " + obj[i]);
 }

SQL Server : converting varchar to INT

This question has got 91,000 views so perhaps many people are looking for a more generic solution to the issue in the title "error converting varchar to INT"

If you are on SQL Server 2012+ one way of handling this invalid data is to use TRY_CAST

SELECT TRY_CAST (userID AS INT)
FROM   audit 

On previous versions you could use

SELECT CASE
         WHEN ISNUMERIC(RTRIM(userID) + '.0e0') = 1
              AND LEN(userID) <= 11
           THEN CAST(userID AS INT)
       END
FROM   audit 

Both return NULL if the value cannot be cast.

In the specific case that you have in your question with known bad values I would use the following however.

CAST(REPLACE(userID COLLATE Latin1_General_Bin, CHAR(0),'') AS INT)

Trying to replace the null character is often problematic except if using a binary collation.

How to gzip all files in all sub-directories into one compressed file in bash

@amitchhajer 's post works for GNU tar. If someone finds this post and needs it to work on a NON GNU system, they can do this:

tar cvf - folderToCompress | gzip > compressFileName

To expand the archive:

zcat compressFileName | tar xvf -

How to convert JSON to string?

Try to Use JSON.stringify

Regards

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

How to change the default docker registry from docker.io to my private registry?

I'm adding up to the original answer given by Guy which is still valid today (soon 2020).

Overriding the default docker registry, like you would do with maven, is actually not a good practice.

When using maven, you pull artifacts from Maven Central Repository through your local repository management system that will act as a proxy. These artifacts are plain, raw libs (jars) and it is quite unlikely that you will push jars with the same name.

On the other hand, docker images are fully operational, runnable, environments, and it makes total sens to pull an image from the Docker Hub, modify it and push this image in your local registry management system with the same name, because it is exactly what its name says it is, just in your enterprise context. In this case, the only distinction between the two images would precisely be its path!!

Therefore the need to set the following rule: the prefix of an image indicates its origin; by default if an image does not have a prefix, it is pulled from Docker Hub.

Cross-Origin Request Blocked

You have to placed this code in application.rb

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}

ValidateAntiForgeryToken purpose, explanation and example

Microsoft provides us built-in functionality which we use in our application for security purposes, so no one can hack our site or invade some critical information.

From Purpose Of ValidateAntiForgeryToken In MVC Application by Harpreet Singh:

Use of ValidateAntiForgeryToken

Let’s try with a simple example to understand this concept. I do not want to make it too complicated, that’s why I am going to use a template of an MVC application, already available in Visual Studio. We will do this step by step. Let’s start.

  1. Step 1 - Create two MVC applications with default internet template and give those names as CrossSite_RequestForgery and Attack_Application respectively.

  2. Now, open CrossSite_RequestForgery application's Web Config and change the connection string with the one given below and then save.

`

<connectionStrings> <add name="DefaultConnection" connectionString="Data Source=local\SQLEXPRESS;Initial Catalog=CSRF;
Integrated Security=true;" providerName="System.Data.SqlClient" /> 
 </connectionStrings>
  1. Now, click on Tools >> NuGet Package Manager, then Package Manager Console

  2. Now, run the below mentioned three commands in Package Manager Console to create the database.

Enable-Migrations add-migration first update-database

Important Notes - I have created database with code first approach because I want to make this example in the way developers work. You can create database manually also. It's your choice.

  1. Now, open Account Controller. Here, you will see a register method whose type is post. Above this method, there should be an attribute available as [ValidateAntiForgeryToken]. Comment this attribute. Now, right click on register and click go to View. There again, you will find an html helper as @Html.AntiForgeryToken() . Comment this one also. Run the application and click on register button. The URL will be open as:

http://localhost:52269/Account/Register

Notes- I know now the question being raised in all readers’ minds is why these two helpers need to be commented, as everyone knows these are used to validate request. Then, I just want to let you all know that this is just because I want to show the difference after and before applying these helpers.

  1. Now, open the second application which is Attack_Application. Then, open Register method of Account Controller. Just change the POST method with the simple one, shown below.

    Registration Form
    1. @Html.LabelFor(m => m.UserName) @Html.TextBoxFor(m => m.UserName)
    2. @Html.LabelFor(m => m.Password) @Html.PasswordFor(m => m.Password)
    3. @Html.LabelFor(m => m.ConfirmPassword) @Html.PasswordFor(m => m.ConfirmPassword)

7.Now, suppose you are a hacker and you know the URL from where you can register user in CrossSite_RequestForgery application. Now, you created a Forgery site as Attacker_Application and just put the same URL in post method.

8.Run this application now and fill the register fields and click on register. You will see you are registered in CrossSite_RequestForgery application. If you check the database of CrossSite_RequestForgery application then you will see and entry you have entered.

  1. Important - Now, open CrossSite_RequestForgery application and comment out the token in Account Controller and register the View. Try to register again with the same process. Then, an error will occur as below.

Server Error in '/' Application. ________________________________________ The required anti-forgery cookie "__RequestVerificationToken" is not present.

This is what the concept says. What we add in View i.e. @Html.AntiForgeryToken() generates __RequestVerificationToken on load time and [ValidateAntiForgeryToken] available on Controller method. Match this token on post time. If token is the same, then it means this is a valid request.

How do I change the string representation of a Python class?

This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

'""'

and not

'"a"'

as would be expected.

EDIT: answering mchicago's comment:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

b = A('b') print b

produces

'a'

while

json.dumps({'b': b})

produces

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

Pass correct "this" context to setTimeout callback?

NOTE: This won't work in IE

var ob = {
    p: "ob.p"
}

var p = "window.p";

setTimeout(function(){
    console.log(this.p); // will print "window.p"
},1000); 

setTimeout(function(){
    console.log(this.p); // will print "ob.p"
}.bind(ob),1000);

How does the modulus operator work?

in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined). For example:

5 % 2 = 1
13 % 5 = 3

With this knowledge we can try to understand your code. Condition count % 6 == 5 means that newline will be written when remainder of division count by 6 is five. How often does that happen? Exactly 6 lines apart (excercise : write numbers 1..30 and underline the ones that satisfy this condition), starting at 6-th line (count = 5).

To get desired behaviour from your code, you should change condition to count % 5 == 4, what will give you newline every 5 lines, starting at 5-th line (count = 4).

What's the best way to build a string of delimited items in Java?

I would use Google Collections. There is a nice Join facility.
http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/base/Join.html

But if I wanted to write it on my own,

package util;

import java.util.ArrayList;
import java.util.Iterable;
import java.util.Collections;
import java.util.Iterator;

public class Utils {
    // accept a collection of objects, since all objects have toString()
    public static String join(String delimiter, Iterable<? extends Object> objs) {
        if (objs.isEmpty()) {
            return "";
        }
        Iterator<? extends Object> iter = objs.iterator();
        StringBuilder buffer = new StringBuilder();
        buffer.append(iter.next());
        while (iter.hasNext()) {
            buffer.append(delimiter).append(iter.next());
        }
        return buffer.toString();
    }

    // for convenience
    public static String join(String delimiter, Object... objs) {
        ArrayList<Object> list = new ArrayList<Object>();
        Collections.addAll(list, objs);
        return join(delimiter, list);
    }
}

I think it works better with an object collection, since now you don't have to convert your objects to strings before you join them.

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }

How to use Morgan logger?

I think I have a way where you may not get exactly get what you want, but you can integrate Morgan's logging with log4js -- in other words, all your logging activity can go to the same place. I hope this digest from an Express server is more or less self-explanatory:

var express = require("express");
var log4js = require("log4js");
var morgan = require("morgan");
...
var theAppLog = log4js.getLogger();
var theHTTPLog = morgan({
  "format": "default",
  "stream": {
    write: function(str) { theAppLog.debug(str); }
  }
});
....
var theServer = express();
theServer.use(theHTTPLog);

Now you can write whatever you want to theAppLog and Morgan will write what it wants to the same place, using the same appenders etc etc. Of course, you can call info() or whatever you like in the stream wrapper instead of debug() -- that just reflects the logging level you want to give to Morgan's req/res logging.

$.ajax - dataType

  • contentType is the HTTP header sent to the server, specifying a particular format.
    Example: I'm sending JSON or XML
  • dataType is you telling jQuery what kind of response to expect.
    Expecting JSON, or XML, or HTML, etc. The default is for jQuery to try and figure it out.

The $.ajax() documentation has full descriptions of these as well.


In your particular case, the first is asking for the response to be in UTF-8, the second doesn't care. Also the first is treating the response as a JavaScript object, the second is going to treat it as a string.

So the first would be:

success: function(data) {
  // get data, e.g. data.title;
}

The second:

success: function(data) {
  alert("Here's lots of data, just a string: " + data);
}

PHP: Inserting Values from the Form into MySQL

Try this:

dbConfig.php

<?php
$mysqli = new mysqli('localhost', 'root', 'pwd', 'yr db name');
    if($mysqli->connect_error)
        {
        echo $mysqli->connect_error;
        }
    ?>

Index.php

<html>
<head><title>Inserting data in database table </title>
</head>
<body>
<form action="control_table.php" method="post">
<table border="1" background="red" align="center">
<tr>
<td>Login Name</td>
<td><input type="text" name="txtname" /></td>
</tr>
<br>
<tr>
<td>Password</td>
<td><input type="text" name="txtpwd" /></td>
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" name="txtbutton" value="SUBMIT" /></td>
</tr>
</table>
control_table.php
<?php include 'config.php'; ?>
<?php
$name=$pwd="";
    if(isset($_POST['txtbutton']))
        {
            $name = $_POST['txtname'];
            $pwd = $_POST['txtpwd'];
            $mysqli->query("insert into users(name,pwd) values('$name', '$pwd')");
        if(!$mysqli) 
        { echo mysqli_error(); }
    else
    {
        echo "Successfully Inserted <br />";
        echo "<a href='show.php'>View Result</a>";
    }

         }  

    ?>

How to make a dropdown readonly using jquery?

Try to make empty string when "keypress up"

The Html is:

<input id="cf_1268591" style="width:60px;line-height:16px;border:1px solid #ccc">

The Jquery is:

$("#cf_1268591").combobox({
  url:"your url",
  valueField:"id",
  textField:"text",
  panelWidth: "350",
  panelHeight: "200",
});

// make after keyup with empty string

var tb = $("#cf_1268591").combobox("textbox");
  tb.bind("keyup",function(e){
  this.value = "";
});

Install opencv for Python 3.3

Yes support for Python 3 it is still not available in current version, but it will be available from version 3.0, (see this ticket). If you really want to have python 3 try using development version, you can download it from GitHub.

EDIT (18/07/2015): version 3.0 is now released and python 3 support is now officially available

How to see if a directory exists or not in Perl?

Use -d (full list of file tests)

if (-d "cgi-bin") {
    # directory called cgi-bin exists
}
elsif (-e "cgi-bin") {
    # cgi-bin exists but is not a directory
}
else {
    # nothing called cgi-bin exists
}

As a note, -e doesn't distinguish between files and directories. To check if something exists and is a plain file, use -f.

How to enable assembly bind failure logging (Fusion) in .NET

Add the following values to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion
Add:
DWORD ForceLog set value to 1
DWORD LogFailures set value to 1
DWORD LogResourceBinds set value to 1
DWORD EnableLog set value to 1
String LogPath set value to folder for logs (e.g. C:\FusionLog\)

Make sure you include the backslash after the folder name and that the Folder exists.

You need to restart the program that you're running to force it to read those registry settings.

By the way, don't forget to turn off fusion logging when not needed.

enter image description here

How to Correctly handle Weak Self in Swift Blocks with Arguments

EDIT: Reference to an updated solution by LightMan

See LightMan's solution. Until now I was using:

input.action = { [weak self] value in
    guard let this = self else { return }
    this.someCall(value) // 'this' isn't nil
}

Or:

input.action = { [weak self] value in
    self?.someCall(value) // call is done if self isn't nil
}

Usually you don't need to specify the parameter type if it's inferred.

You can omit the parameter altogether if there is none or if you refer to it as $0 in the closure:

input.action = { [weak self] in
    self?.someCall($0) // call is done if self isn't nil
}

Just for completeness; if you're passing the closure to a function and the parameter is not @escaping, you don't need a weak self:

[1,2,3,4,5].forEach { self.someCall($0) }

Where can I find Android source code online?

2020: The official AOSP code search https://cs.android.com/


You can view the source code through http://developer.android.com, when you're reading the API there will be a link to the matching source code on GitHub, you just need to add the Android SDK Reference Search Plugin on Chrome.

I blogged about it here:
http://blog.blundellapps.com/add-source-code-links-to-android-apis/

enter image description here

jQuery check if Cookie exists, if not create it

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });

Getting error in console : Failed to load resource: net::ERR_CONNECTION_RESET

I'm using chrome too and facing same problem on my localhost. I did a lot of things like clear using CCleaner and restart OS. But my problem was solved with clearing cookie. In order to clear cookie:

  1. Go to Chrome settings > Privacy > Content Settings > Cookie > All cookie and Site Data > Delete domain problem

OR

  1. Right Click > Inspect Element > Tab Resources > Cookie (Left Menu) > Select domain > Delete All cookie One By One (Right Menu)

What are 'get' and 'set' in Swift?

The getting and setting of variables within classes refers to either retrieving ("getting") or altering ("setting") their contents.

Consider a variable members of a class family. Naturally, this variable would need to be an integer, since a family can never consist of two point something people.

So you would probably go ahead by defining the members variable like this:

class family {
   var members:Int
}

This, however, will give people using this class the possibility to set the number of family members to something like 0 or 1. And since there is no such thing as a family of 1 or 0, this is quite unfortunate.

This is where the getters and setters come in. This way you can decide for yourself how variables can be altered and what values they can receive, as well as deciding what content they return.

Returning to our family class, let's make sure nobody can set the members value to anything less than 2:

class family {
  var _members:Int = 2
  var members:Int {
   get {
     return _members
   }
   set (newVal) {
     if newVal >= 2 {
       _members = newVal
     } else {
       println('error: cannot have family with less than 2 members')
     }
   }
  }
}

Now we can access the members variable as before, by typing instanceOfFamily.members, and thanks to the setter function, we can also set it's value as before, by typing, for example: instanceOfFamily.members = 3. What has changed, however, is the fact that we cannot set this variable to anything smaller than 2 anymore.

Note the introduction of the _members variable, which is the actual variable to store the value that we set through the members setter function. The original members has now become a computed property, meaning that it only acts as an interface to deal with our actual variable.

Angularjs: input[text] ngChange fires while the value is changing

For anyone struggling with IE8 (it doesn't like the unbind('input'), I found a way around it.

Inject $sniffer into your directive and use:

if($sniffer.hasEvent('input')){
    elm.unbind('input');
}

IE8 calms down if you do this :)

How to find the default JMX port number?

Now I need to connect that application from my local computer, but I don't know the JMX port number of the remote computer. Where can I find it? Or, must I restart that application with some VM parameters to specify the port number?

By default JMX does not publish on a port unless you specify the arguments from this page: How to activate JMX...

-Dcom.sun.management.jmxremote # no longer required for JDK6
-Dcom.sun.management.jmxremote.port=9010
-Dcom.sun.management.jmxremote.local.only=false # careful with security implications
-Dcom.sun.management.jmxremote.authenticate=false # careful with security implications

If you are running you should be able to access any of those system properties to see if they have been set:

if (System.getProperty("com.sun.management.jmxremote") == null) {
    System.out.println("JMX remote is disabled");
} else [
    String portString = System.getProperty("com.sun.management.jmxremote.port");
    if (portString != null) {
        System.out.println("JMX running on port "
            + Integer.parseInt(portString));
    }
}

Depending on how the server is connected, you might also have to specify the following parameter. As part of the initial JMX connection, jconsole connects up to the RMI port to determine which port the JMX server is running on. When you initially start up a JMX enabled application, it looks its own hostname to determine what address to return in that initial RMI transaction. If your hostname is not in /etc/hosts or if it is set to an incorrect interface address then you can override it with the following:

-Djava.rmi.server.hostname=<IP address>

As an aside, my SimpleJMX package allows you to define both the JMX server and the RMI port or set them both to the same port. The above port defined with com.sun.management.jmxremote.port is actually the RMI port. This tells the client what port the JMX server is running on.

Delete element in a slice

I'm getting an index out of range error with the accepted answer solution. Reason: When range start, it is not iterate value one by one, it is iterate by index. If you modified a slice while it is in range, it will induce some problem.

Old Answer:

chars := []string{"a", "a", "b"}

for i, v := range chars {
    fmt.Printf("%+v, %d, %s\n", chars, i, v)
    if v == "a" {
        chars = append(chars[:i], chars[i+1:]...)
    }
}
fmt.Printf("%+v", chars)

Expected :

[a a b], 0, a
[a b], 0, a
[b], 0, b
Result: [b]

Actual:

// Autual
[a a b], 0, a
[a b], 1, b
[a b], 2, b
Result: [a b]

Correct Way (Solution):

chars := []string{"a", "a", "b"}

for i := 0; i < len(chars); i++ {
    if chars[i] == "a" {
        chars = append(chars[:i], chars[i+1:]...)
        i-- // form the remove item index to start iterate next item
    }
}

fmt.Printf("%+v", chars)

Source: https://dinolai.com/notes/golang/golang-delete-slice-item-in-range-problem.html

Xpath: select div that contains class AND whose specific child element contains text

To find a div of a certain class that contains a span at any depth containing certain text, try:

//div[contains(@class, 'measure-tab') and contains(.//span, 'someText')]

That said, this solution looks extremely fragile. If the table happens to contain a span with the text you're looking for, the div containing the table will be matched, too. I'd suggest to find a more robust way of filtering the elements. For example by using IDs or top-level document structure.

What is the meaning of Bus: error 10 in C

For one, you can't modify string literals. It's undefined behavior.

To fix that you can make str a local array:

char str[] = "First string";

Now, you will have a second problem, is that str isn't large enough to hold str2. So you will need to increase the length of it. Otherwise, you will overrun str - which is also undefined behavior.

To get around this second problem, you either need to make str at least as long as str2. Or allocate it dynamically:

char *str2 = "Second string";
char *str = malloc(strlen(str2) + 1);  //  Allocate memory
//  Maybe check for NULL.

strcpy(str, str2);

//  Always remember to free it.
free(str);

There are other more elegant ways to do this involving VLAs (in C99) and stack allocation, but I won't go into those as their use is somewhat questionable.


As @SangeethSaravanaraj pointed out in the comments, everyone missed the #import. It should be #include:

#include <stdio.h>
#include <string.h>

Can I do Android Programming in C++, C?

Yes, you can program Android apps in C++ (for the most part), using the Native Development Kit (NDK), although Java is the primary/preferred language for programming Android, and your C++ code will likely have to interface with Java components, and you'll likely need to read and understand the documentation for Java components, as well. Therefore, I'd advise you to use Java unless you have some existing C++ code base that you need to port and that isn't practical to rewrite in Java.

Java is very similar to C++, I don't think you will have any problems picking it up... going from C++ to Java is incredibly easy; going from Java to C++ is a little more difficult, though not terrible. Java for C++ Programmers does a pretty good job at explaining the differences. Writing your Android code in Java will be more idiomatic and will also make the development process easier for you (as the tooling for the Java Android SDK is significantly better than the corresponding NDK tooling)

In terms of setup, Google provides the Android Studio IDE for both Java and C++ Android development (with Gradle as the build system), but you are free to use whatever IDE or build system you want so long as, under the hood, you are using the Android SDK / NDK to produce the final outputs.

How to clear jQuery validation error messages?

None of the other solutions worked for me. resetForm() is clearly documented to reset the actual form, e.g. remove the data from the form, which is not what I want. It just happens to sometimes not do that, but just remove the errors. What finally worked for me is this:

validator.hideThese(validator.errors());

Can't access Eclipse marketplace

in my case the solution was to set the proxy to "native" I had configured the proxy under linux with cntlm and also in Firefox (used as eclipse browser also.

Error using eclipse for Android - No resource found that matches the given name

One general solution to such tiny errors is that you close eclipse and start is again.. 3 irritating problems were solved.. its the problem with eclipse.. some times it didn resolve "R.id", the it didn find @string/somebutton, and then again some random thing... if nothing logical comes in your mind, try this, n conjure d result.. :)

Center Div inside another (100% width) div

for detail info, let's say the code below will make a div aligned center:

margin-left: auto;
margin-right: auto;

or simply use:

margin: 0 auto;

but bear in mind, the above CSS code only works when you specify a fixed width (not 100%) on your html element. so the complete solution for your issue would be:

.your-inner-div {
      margin: 0 auto;
      width: 900px;
}

How to watch for form changes in Angular

Expanding on Mark's suggestions...

Method 3

Implement "deep" change detection on the model. The advantages primarily involve the avoidance of incorporating user interface aspects into the component; this also catches programmatic changes made to the model. That said, it would require extra work to implement such things as debouncing as suggested by Thierry, and this will also catch your own programmatic changes, so use with caution.

export class App implements DoCheck {
  person = { first: "Sally", last: "Jones" };
  oldPerson = { ...this.person }; // ES6 shallow clone. Use lodash or something for deep cloning

  ngDoCheck() {
    // Simple shallow property comparison - use fancy recursive deep comparison for more complex needs
    for (let prop in this.person) {
      if (this.oldPerson[prop] !==  this.person[prop]) {
        console.log(`person.${prop} changed: ${this.person[prop]}`);
        this.oldPerson[prop] = this.person[prop];
      }
    }
  }

Try in Plunker

What does "Use of unassigned local variable" mean?

The compiler isn't smart enough to know that at least one of your if blocks will be executed. Therefore, it doesn't see that variables like annualRate will be assigned no matter what. Here's how you can make the compiler understand:

if (creditPlan == "0")
{
    // ...
}
else if (creditPlan == "1")
{
    // ...
}
else if (creditPlan == "2")
{
    // ...
}
else
{
    // ...
}

The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you're assigning the variable in all of the blocks, it won't give the compiler error.

By the way, you can also use a switch statement instead of ifs to maybe make your code cleaner.

multiple figure in latex with captions

Below is an example of multiple figures that I used recently in Latex. You need to call these packages

\usepackage{graphicx}
\usepackage{subfig})


\begin{figure}[H]%

    \centering

    \subfloat[Row1]{{\includegraphics[scale=.36]{1.png} }}%

    \subfloat[Row2]{{\includegraphics[scale=.36]{2.png} }}%

    \subfloat[Row3]{{\includegraphics[scale=.36]{3.png} }}%
    \hfill
    \subfloat[Row4]{{\includegraphics[scale=0.37]{4.png} }}%

    \subfloat[Row5]{{\includegraphics[scale=0.37]{5.png} }}%

    \caption{Multiple figures in latex.}%

    \label{fig:MFL}%

\end{figure}

What is a Question Mark "?" and Colon ":" Operator Used for?

This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.

Here's a good example from Wikipedia demonstrating how it works:

A traditional if-else construct in C, Java and JavaScript is written:

if (a > b) {
    result = x;
} else {
    result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;

Basically it takes the form:

boolean statement ? true result : false result;

So if the boolean statement is true, you get the first part, and if it's false you get the second one.

Try these if that still doesn't make sense:

System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

Just want to share my experience on this.

I, too, encountered this error. I'm using MS Visual Studio 2013 and I have an MS SQL Server 2008, though I have had MS SQL Server 2012 Installed before.

I was banging my head on this error for a day. I tried installing SharedManagementObject, SQLSysClrTypes and Native Client, but it didn't work. Why? Well I finally figured that I was installing 2008 or 2012 version of the said files, while I'm using Visual Studio 2013!! My idea is since it is a database issue, the version of the files should be the same with the MS SQL Server installed on the laptop, but apparently, I should have installed the 2013 version because the error is from the Visual Studio and not from the SQL Server.

How can I undo a mysql statement that I just executed?

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

Cannot connect to MySQL 4.1+ using old authentication

Had the same issue, but executing the queries alone will not help. To fix this I did the following,

  1. Set old_passwords=0 in my.cnf file
  2. Restart mysql
  3. Login to mysql as root user
  4. Execute FLUSH PRIVILEGES;

List all tables in postgresql information_schema

The "\z" COMMAND is also a good way to list tables when inside the interactive psql session.

eg.

# psql -d mcdb -U admin -p 5555
mcdb=# /z
                           Access privileges for database "mcdb"
 Schema |              Name              |   Type   |           Access privileges
--------+--------------------------------+----------+---------------------------------------
 public | activities                     | table    |
 public | activities_id_seq              | sequence |
 public | activities_users_mapping       | table    |
[..]
 public | v_schedules_2                  | view     | {admin=arwdxt/admin,viewuser=r/admin}
 public | v_systems                      | view     |
 public | vapp_backups                   | table    |
 public | vm_client                      | table    |
 public | vm_datastore                   | table    |
 public | vmentity_hle_map               | table    |
(148 rows)

pthread function from a class

My favorite way to handle a thread is to encapsulate it inside a C++ object. Here's an example:

class MyThreadClass
{
public:
   MyThreadClass() {/* empty */}
   virtual ~MyThreadClass() {/* empty */}

   /** Returns true if the thread was successfully started, false if there was an error starting the thread */
   bool StartInternalThread()
   {
      return (pthread_create(&_thread, NULL, InternalThreadEntryFunc, this) == 0);
   }

   /** Will not return until the internal thread has exited. */
   void WaitForInternalThreadToExit()
   {
      (void) pthread_join(_thread, NULL);
   }

protected:
   /** Implement this method in your subclass with the code you want your thread to run. */
   virtual void InternalThreadEntry() = 0;

private:
   static void * InternalThreadEntryFunc(void * This) {((MyThreadClass *)This)->InternalThreadEntry(); return NULL;}

   pthread_t _thread;
};

To use it, you would just create a subclass of MyThreadClass with the InternalThreadEntry() method implemented to contain your thread's event loop. You'd need to call WaitForInternalThreadToExit() on the thread object before deleting the thread object, of course (and have some mechanism to make sure the thread actually exits, otherwise WaitForInternalThreadToExit() would never return)

Utilizing multi core for tar+gzip/bzip compression/decompression

You can use the shortcut -I for tar's --use-compress-program switch, and invoke pbzip2 for bzip2 compression on multiple cores:

tar -I pbzip2 -cf OUTPUT_FILE.tar.bz2 DIRECTORY_TO_COMPRESS/

Null check in VB

Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

How to do 3 table JOIN in UPDATE query?

Yes, you can do a 3 table join for an update statement. Here is an example :

    UPDATE customer_table c 

      JOIN  
          employee_table e
          ON c.city_id = e.city_id  
      JOIN 
          anyother_ table a
          ON a.someID = e.someID

    SET c.active = "Yes"

    WHERE c.city = "New york";

PLS-00103: Encountered the symbol when expecting one of the following:

The IF statement has these forms in PL/SQL:

IF THEN

IF THEN ELSE

IF THEN ELSIF

You have used elseif which in terms of PL/SQL is wrong. That need to be replaced with ELSIF.

DECLARE
  mark NUMBER :=50;
BEGIN
  mark :=& mark;
  IF (mark BETWEEN 85 AND 100) THEN
    dbms_output.put_line('mark is A ');
  elsif (mark BETWEEN 50 AND 65) THEN
    dbms_output.put_line('mark is D ');
  elsif (mark BETWEEN 66 AND 75) THEN
    dbms_output.put_line('mark is C ');
  elsif (mark BETWEEN 76 AND 84) THEN
    dbms_output.put_line('mark is B');
  ELSE
    dbms_output.put_line('mark is F');
  END IF;
END;
/

Hide all elements with class using plain Javascript

In the absence of jQuery, I would use something like this:

<script>
    var divsToHide = document.getElementsByClassName("classname"); //divsToHide is an array
    for(var i = 0; i < divsToHide.length; i++){
        divsToHide[i].style.visibility = "hidden"; // or
        divsToHide[i].style.display = "none"; // depending on what you're doing
    }
<script>

This is taken from this SO question: Hide div by class id, however seeing that you're asking for "old-school" JS solution, I believe that getElementsByClassName is only supported by modern browsers

How to get the current location in Google Maps Android API v2?

At the moment GoogleMap.getMyLocation() always returns null under every circumstance.

There are currently two bug reports towards Google, that I know of, Issue 40932 and Issue 4644.

Implementing a LocationListener as brought up earlier would be incorrect because the LocationListener would be out of sync with the LocationOverlay within the new API that you are trying to use.

Following the tutorial on Vogella's Site, linked earlier by Pramod J George, would give you directions for the Older Google Maps API.

So I apologize for not giving you a method to retrieve your location by that means. For now the locationListener may be the only means to do it, but I'm sure Google is working on fixing the issue within the new API.

Also sorry for not posting more links, StackOverlow thinks I'm spam because I have no rep.

---- Update on February 4th, 2013 ----

Google has stated that the issue will be fixed in the next update to the Google Maps API via Issue 4644. I am not sure when the update will occur, but once it does I will edit this post again.

---- Update on April 10th, 2013 ----

Google has stated the issue has been fixed via Issue 4644. It should work now.

Remove empty lines in a text file via grep

Simplest Answer -----------------------------------------

[root@node1 ~]# cat /etc/sudoers | grep -v -e ^# -e ^$
Defaults   !visiblepw
Defaults    always_set_home
Defaults    match_group_by_gid
Defaults    always_query_group_plugin
Defaults    env_reset
Defaults    env_keep =  "COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS"
Defaults    env_keep += "MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE"
Defaults    env_keep += "LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES"
Defaults    env_keep += "LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE"
Defaults    env_keep += "LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY"
Defaults    secure_path = /sbin:/bin:/usr/sbin:/usr/bin
root    ALL=(ALL)       ALL
%wheel  ALL=(ALL)       ALL
[root@node1 ~]#

Activating Anaconda Environment in VsCode

Just launch the VS Code from the Anaconda Navigator. It works for me.

How can I explicitly free memory in Python?

You can't explicitly free memory. What you need to do is to make sure you don't keep references to objects. They will then be garbage collected, freeing the memory.

In your case, when you need large lists, you typically need to reorganize the code, typically using generators/iterators instead. That way you don't need to have the large lists in memory at all.

http://www.prasannatech.net/2009/07/introduction-python-generators.html

Add an object to a python list

If i am correct in believing that you are adding a variable to the array but when you change that variable outside of the array, it also changes inside the array but you don't want it to then it is a really simple solution.

When you are saving the variable to the array you should turn it into a string by simply putting str(variablename). For example:

array.append(str(variablename))

Using this method your code should look like this:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(str(wM))        #this is the only line that is changed.
    wM.reset()

Check if date is in the past Javascript

To make the answer more re-usable for things other than just the datepicker change function you can create a prototype to handle this for you.

// safety check to see if the prototype name is already defined
Function.prototype.method = function (name, func) {
    if (!this.prototype[name]) {
        this.prototype[name] = func;
        return this;
    }
};
Date.method('inPast', function () {
    return this < new Date($.now());// the $.now() requires jQuery
});

// including this prototype as using in example
Date.method('addDays', function (days) {
    var date = new Date(this);
    date.setDate(date.getDate() + (days));    
    return date;
});

If you dont like the safety check you can use the conventional way to define prototypes:

Date.prototype.inPast = function(){
    return this < new Date($.now());// the $.now() requires jQuery
}

Example Usage

var dt = new Date($.now());
var yesterday = dt.addDays(-1);
var tomorrow = dt.addDays(1);
console.log('Yesterday: ' + yesterday.inPast());
console.log('Tomorrow: ' + tomorrow.inPast());

How does "FOR" work in cmd batch file?

Here is a good guide:

FOR /F - Loop command: against a set of files.

FOR /F - Loop command: against the results of another command.

FOR - Loop command: all options Files, Directory, List.

[The whole guide (Windows XP commands):

http://www.ss64.com/nt/index.html

Edit: Sorry, didn't see that the link was already in the OP, as it appeared to me as a part of the Amazon link.

Get filename and path from URI from mediastore

Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);

filemtime "warning stat failed for"

in my case it was not related to the path or filename. If filemtime(), fileatime() or filectime() don't work, try stat().

$filedate = date_create(date("Y-m-d", filectime($file)));

becomes

$stat = stat($directory.$file);
$filedate = date_create(date("Y-m-d", $stat['ctime']));

that worked for me.

Complete snippet for deleting files by number of days:

$directory = $_SERVER['DOCUMENT_ROOT'].'/directory/';
$files = array_slice(scandir($directory), 2);
foreach($files as $file)
{
    $extension      = substr($file, -3, 3); 
    if ($extension == 'jpg') // in case you only want specific files deleted
    {
        $stat = stat($directory.$file);
        $filedate = date_create(date("Y-m-d", $stat['ctime']));
        $today = date_create(date("Y-m-d"));
        $days = date_diff($filedate, $today, true);
        if ($days->days > 1) 
        { 
            unlink($directory.$file);
        }
    } 
}

Singular matrix issue with Numpy

By definition, by multiplying a 1D vector by its transpose, you've created a singular matrix.

Each row is a linear combination of the first row.

Notice that the second row is just 8x the first row.

Likewise, the third row is 50x the first row.

There's only one independent row in your matrix.

For files in directory, only echo filename (no path)

Use basename:

echo $(basename /foo/bar/stuff)

How to export and import a .sql file from command line with options?

since I have no enough reputation to comment after the highest post, so I add here.

use '|' on linux platform to save disk space.

thx @Hariboo, add events/triggers/routints parameters

mysqldump -x -u [uname] -p[pass]  -C --databases db_name  --events --triggers --routines | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/ '  | awk '{ if (index($0,"GTID_PURGED")) { getline; while (length($0) > 0) { getline; } } else { print $0 } }'  | grep -iv 'set @@' | trickle -u 10240 mysql -u username -p -h localhost DATA-BASE-NAME

some issues/tips:

Error: ......not exist when using LOCK TABLES

# --lock-all-tables,-x , this parameter is to keep data consistency because some transaction may still be working like schedule.
# also you need check and confirm: grant all privileges on *.* to root@"%" identified by "Passwd";

ERROR 2006 (HY000) at line 866: MySQL server has gone away mysqldump: Got errno 32 on write

# set this values big enough on destination mysql server, like: max_allowed_packet=1024*1024*20
# use compress parameter '-C'
# use trickle to limit network bandwidth while write data to destination server

ERROR 1419 (HY000) at line 32730: You do not have the SUPER privilege and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)

# set SET GLOBAL log_bin_trust_function_creators = 1;
# or use super user import data

ERROR 1227 (42000) at line 138: Access denied; you need (at least one of) the SUPER privilege(s) for this operation mysqldump: Got errno 32 on write

# add sed/awk to avoid some privilege issues

hope this help!

change values in array when doing foreach

Javascript is pass by value, and which essentially means part is a copy of the value in the array.

To change the value, access the array itself in your loop.

arr[index] = 'new value';

HTML code for an apostrophe

Firstly, it would appear that &apos; should be avoided - The curse of &apos;

Secondly, if there is ever any chance that you're going to generate markup to be returned via AJAX calls, you should avoid the entity names (As not all of the HTML entities are valid in XML) and use the &#XXXX; syntax instead.

Failure to do so may result in the markup being considered as invalid XML.

The entity that is most likely to be affected by this is &nbsp;, which should be replaced by &#160;

How to sort a list of strings?

Or maybe:

names = ['Jasmine', 'Alberto', 'Ross', 'dig-dog']
print ("The solution for this is about this names being sorted:",sorted(names, key=lambda name:name.lower()))

Is there a way to ignore a single FindBugs warning?

At the time of writing this (May 2018), FindBugs seems to have been replaced by SpotBugs. Using the SuppressFBWarnings annotation requires your code to be compiled with Java 8 or later and introduces a compile time dependency on spotbugs-annotations.jar.

Using a filter file to filter SpotBugs rules has no such issues. The documentation is here.

Why would one use nested classes in C++?

Nested classes are just like regular classes, but:

  • they have additional access restriction (as all definitions inside a class definition do),
  • they don't pollute the given namespace, e.g. global namespace. If you feel that class B is so deeply connected to class A, but the objects of A and B are not necessarily related, then you might want the class B to be only accessible via scoping the A class (it would be referred to as A::Class).

Some examples:

Publicly nesting class to put it in a scope of relevant class


Assume you want to have a class SomeSpecificCollection which would aggregate objects of class Element. You can then either:

  1. declare two classes: SomeSpecificCollection and Element - bad, because the name "Element" is general enough in order to cause a possible name clash

  2. introduce a namespace someSpecificCollection and declare classes someSpecificCollection::Collection and someSpecificCollection::Element. No risk of name clash, but can it get any more verbose?

  3. declare two global classes SomeSpecificCollection and SomeSpecificCollectionElement - which has minor drawbacks, but is probably OK.

  4. declare global class SomeSpecificCollection and class Element as its nested class. Then:

    • you don't risk any name clashes as Element is not in the global namespace,
    • in implementation of SomeSpecificCollection you refer to just Element, and everywhere else as SomeSpecificCollection::Element - which looks +- the same as 3., but more clear
    • it gets plain simple that it's "an element of a specific collection", not "a specific element of a collection"
    • it is visible that SomeSpecificCollection is also a class.

In my opinion, the last variant is definitely the most intuitive and hence best design.

Let me stress - It's not a big difference from making two global classes with more verbose names. It just a tiny little detail, but imho it makes the code more clear.

Introducing another scope inside a class scope


This is especially useful for introducing typedefs or enums. I'll just post a code example here:

class Product {
public:
    enum ProductType {
        FANCY, AWESOME, USEFUL
    };
    enum ProductBoxType {
        BOX, BAG, CRATE
    };
    Product(ProductType t, ProductBoxType b, String name);

    // the rest of the class: fields, methods
};

One then will call:

Product p(Product::FANCY, Product::BOX);

But when looking at code completion proposals for Product::, one will often get all the possible enum values (BOX, FANCY, CRATE) listed and it's easy to make a mistake here (C++0x's strongly typed enums kind of solve that, but never mind).

But if you introduce additional scope for those enums using nested classes, things could look like:

class Product {
public:
    struct ProductType {
        enum Enum { FANCY, AWESOME, USEFUL };
    };
    struct ProductBoxType {
        enum Enum { BOX, BAG, CRATE };
    };
    Product(ProductType::Enum t, ProductBoxType::Enum b, String name);

    // the rest of the class: fields, methods
};

Then the call looks like:

Product p(Product::ProductType::FANCY, Product::ProductBoxType::BOX);

Then by typing Product::ProductType:: in an IDE, one will get only the enums from the desired scope suggested. This also reduces the risk of making a mistake.

Of course this may not be needed for small classes, but if one has a lot of enums, then it makes things easier for the client programmers.

In the same way, you could "organise" a big bunch of typedefs in a template, if you ever had the need to. It's a useful pattern sometimes.

The PIMPL idiom


The PIMPL (short for Pointer to IMPLementation) is an idiom useful to remove the implementation details of a class from the header. This reduces the need of recompiling classes depending on the class' header whenever the "implementation" part of the header changes.

It's usually implemented using a nested class:

X.h:

class X {
public:
    X();
    virtual ~X();
    void publicInterface();
    void publicInterface2();
private:
    struct Impl;
    std::unique_ptr<Impl> impl;
}

X.cpp:

#include "X.h"
#include <windows.h>

struct X::Impl {
    HWND hWnd; // this field is a part of the class, but no need to include windows.h in header
    // all private fields, methods go here

    void privateMethod(HWND wnd);
    void privateMethod();
};

X::X() : impl(new Impl()) {
    // ...
}

// and the rest of definitions go here

This is particularly useful if the full class definition needs the definition of types from some external library which has a heavy or just ugly header file (take WinAPI). If you use PIMPL, then you can enclose any WinAPI-specific functionality only in .cpp and never include it in .h.

How do you add a timed delay to a C++ program?

On Windows you can include the windows library and use "Sleep(0);" to sleep the program. It takes a value that represents milliseconds.

Get difference between two lists

I wanted something that would take two lists and could do what diff in bash does. Since this question pops up first when you search for "python diff two lists" and is not very specific, I will post what I came up with.

Using SequenceMather from difflib you can compare two lists like diff does. None of the other answers will tell you the position where the difference occurs, but this one does. Some answers give the difference in only one direction. Some reorder the elements. Some don't handle duplicates. But this solution gives you a true difference between two lists:

a = 'A quick fox jumps the lazy dog'.split()
b = 'A quick brown mouse jumps over the dog'.split()

from difflib import SequenceMatcher

for tag, i, j, k, l in SequenceMatcher(None, a, b).get_opcodes():
  if tag == 'equal': print('both have', a[i:j])
  if tag in ('delete', 'replace'): print('  1st has', a[i:j])
  if tag in ('insert', 'replace'): print('  2nd has', b[k:l])

This outputs:

both have ['A', 'quick']
  1st has ['fox']
  2nd has ['brown', 'mouse']
both have ['jumps']
  2nd has ['over']
both have ['the']
  1st has ['lazy']
both have ['dog']

Of course, if your application makes the same assumptions the other answers make, you will benefit from them the most. But if you are looking for a true diff functionality, then this is the only way to go.

For example, none of the other answers could handle:

a = [1,2,3,4,5]
b = [5,4,3,2,1]

But this one does:

  2nd has [5, 4, 3, 2]
both have [1]
  1st has [2, 3, 4, 5]

PHP: date function to get month of the current date

as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so

echo date('n'); // "9"

What's NSLocalizedString equivalent in Swift?

When you are developing an SDK. You need some extra operation.

1) create Localizable.strings as usual in YourLocalizeDemoSDK.

2) create the same Localizable.strings in YourLocalizeDemo.

3) find your Bundle Path of YourLocalizeDemoSDK.

Swift4:

// if you use NSLocalizeString in NSObject, you can use it like this
let value = NSLocalizedString("key", tableName: nil, bundle: Bundle(for: type(of: self)), value: "", comment: "")

Bundle(for: type(of: self)) helps you to find the bundle in YourLocalizeDemoSDK. If you use Bundle.main instead, you will get a wrong value(in fact it will be the same string with the key).

But if you want to use the String extension mentioned by dr OX. You need to do some more. The origin extension looks like this.

extension String {
    var localized: String {
        return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "")
    }
}

As we know, we are developing an SDK, Bundle.main will get the bundle of YourLocalizeDemo's bundle. That's not what we want. We need the bundle in YourLocalizeDemoSDK. This is a trick to find it quickly.

Run the code below in a NSObject instance in YourLocalizeDemoSDK. And you will get the URL of YourLocalizeDemoSDK.

let bundleURLOfSDK = Bundle(for: type(of: self)).bundleURL
let mainBundleURL = Bundle.main.bundleURL

Print both of the two url, you will find that we can build bundleURLofSDK base on mainBundleURL. In this case, it will be:

let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main

And the String extension will be:

extension String {
    var localized: String {
        let bundle = Bundle(url: Bundle.main.bundleURL.appendingPathComponent("Frameworks").appendingPathComponent("YourLocalizeDemoSDK.framework")) ?? Bundle.main
        return NSLocalizedString(self, tableName: nil, bundle: bundle, value: "", comment: "")
    }
}

Hope it helps.

Java AES and using my own Key

You should use a KeyGenerator to generate the Key,

AES key lengths are 128, 192, and 256 bit depending on the cipher you want to use.

Take a look at the tutorial here

Here is the code for Password Based Encryption, this has the password being entered through System.in you can change that to use a stored password if you want.

        PBEKeySpec pbeKeySpec;
        PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;

        // Salt
        byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        };

        // Iteration count
        int count = 20;

        // Create PBE parameter set
        pbeParamSpec = new PBEParameterSpec(salt, count);

        // Prompt user for encryption password.
        // Collect user password as char array (using the
        // "readPassword" method from above), and convert
        // it into a SecretKey object, using a PBE key
        // factory.
        System.out.print("Enter encryption password:  ");
        System.out.flush();
        pbeKeySpec = new PBEKeySpec(readPassword(System.in));
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Our cleartext
        byte[] cleartext = "This is another example".getBytes();

        // Encrypt the cleartext
        byte[] ciphertext = pbeCipher.doFinal(cleartext);

Run a single test method with maven

To run a single test method in Maven, you need to provide the command as:

mvn test -Dtest=TestCircle#xyz test

where TestCircle is the test class name and xyz is the test method.

Wild card characters also work; both in the method name and class name.

If you're testing in a multi-module project, specify the module that the test is in with -pl <module-name>.

For integration tests use it.test=... option instead of test=...:

mvn -pl <module-name> -Dit.test=TestCircle#xyz integration-test

Display Yes and No buttons instead of OK and Cancel in Confirm box?

No, it is not possible to change the content of the buttons in the dialog displayed by the confirm function. You can use Javascript to create a dialog that looks similar.