Programs & Examples On #Cfnetwork

Network framework in the core services for iOS & Mac OS X

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I got the same issue (asp, c# - HttpPostedFileBase) when posting a file that was larger than 1MB (even though application doesn't have any limitation for file size), for me the simplification of model class helped. If you got this issue, try to remove some parts of the model, and see if it will help in any way. Sounds strange, but worked for me.

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

Apple hand three categories of certificates: Trusted, Always Ask and Blocked. You'll encounter the issue if your certificate's type on the Blocked and Always Ask list. On Safari it show’s like: enter image description here

And you can find the type of Always Ask certificates on Settings > General > About > Certificate Trust Setting

There is the List of available trusted root certificates in iOS 11

Blocking Trust for WoSign CA Free SSL Certificate G2

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Simply add the following fields in your .plist file

enter image description here

Syntax looks like this:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

CFNetwork SSLHandshake failed iOS 9

The syntax for the Info.plist configuration

   <key>NSAppTransportSecurity</key>
   <dict>
   <key>NSExceptionDomains</key>
    <dict>
    <key>yourserver.com</key>
   <dict>
  <!--Include to allow subdomains-->
  <key>NSIncludesSubdomains</key>
  <true/>
  <!--Include to allow insecure HTTP requests-->
  <key>NSExceptionAllowsInsecureHTTPLoads</key>
  <true/>
  <!--Include to specify minimum TLS version-->
  <key>NSExceptionMinimumTLSVersion</key>
  <string>TLSv1.1</string>
   </dict>
 </dict>

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

Apple Mach-O Linker Error when compiling for device

The problem was that in XCode 4, the dependencies do not assume the architecture settings of the main project, as they previously did in XCode 3. I had to go through all of my dependencies setting them for the correct architecture.

symbol(s) not found for architecture i386

I solved it using the following method (for XCode 4):

1) Select the project in the project navigation window which will show project summary on right

2) Select 4th tab build phases

3) Select Link binary with library option

4) Add framework for which you are getting

5) Move the framework from main folder to the frameworks folder

6) Build it again and errors are gone.

Comparing two java.util.Dates to see if they are in the same day

You can avoid external dependencies and the performance hit of using Calendar by calculating the Julian Day Number for each of the dates and then comparing these:

public static boolean isSameDay(Date date1, Date date2) {

    // Strip out the time part of each date.
    long julianDayNumber1 = date1.getTime() / MILLIS_PER_DAY;
    long julianDayNumber2 = date2.getTime() / MILLIS_PER_DAY;

    // If they now are equal then it is the same day.
    return julianDayNumber1 == julianDayNumber2;
}

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;
/

How to set the env variable for PHP?

You May use set keyword for set the path

set path=%path%;c:/wamp/bin/php/php5.3.0

if all the path are set in path variables

If you want to see all path list. you can use

set %path%

you need to append your php path behind this path.

This is how you can set environment variable.

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Multiple conditions in if statement shell script

You are trying to compare strings inside an arithmetic command (((...))). Use [[ instead.

if [[ $username == "$username1" && $password == "$password1" ]] ||
   [[ $username == "$username2" && $password == "$password2" ]]; then

Note that I've reduced this to two separate tests joined by ||, with the && moved inside the tests. This is because the shell operators && and || have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d is equivalent to the intended ( a && b ) || ( c && d ).

ActiveMQ connection refused

I encountered a similar problem when I was using the below to obtain connection factory ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");

Its resolved when I changed it to the below

ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");

The below then showed that my Q size was increasing.. http://:8161/admin/queues.jsp

Newline character in StringBuilder

For multiple lines the best way I find is to do this:

        IEnumerable<string> lines = new List<string>
        {
            string.Format("{{ line with formatting... {0} }}", id),
            "line 2",
            "line 3"
        };
        StringBuilder sb = new StringBuilder();
        foreach(var line in lines)
            sb.AppendLine(line);

In this way you don't have to clutter the screen with the Environment.NewLine or AppendLine() repeated multiple times. It will also be less error prone than having to remember to type them.

Count how many files in directory PHP

Working Demo

<?php

$directory = "../images/team/harry/"; // dir location
if (glob($directory . "*.*") != false)
{
 $filecount = count(glob($directory . "*.*"));
 echo $filecount;
}
else
{
 echo 0;
}

?>

How do I check if a number is positive or negative in C#?

Of course no-one's actually given the correct answer,

num != 0   // num is positive *or* negative!

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

Not sure, if it's the most efficient solution, but I would loop over all entries, and use a bitset to remember, which numbers are set, and then test for 0 bits.

I like simple solutions - and I even believe, that it might be faster than calculating the sum, or the sum of squares etc.

How to add not null constraint to existing column in MySQL

Try this, you will know the difference between change and modify,

ALTER TABLE table_name CHANGE curr_column_name new_column_name new_column_datatype [constraints]

ALTER TABLE table_name MODIFY column_name new_column_datatype [constraints]
  • You can change name and datatype of the particular column using CHANGE.
  • You can modify the particular column datatype using MODIFY. You cannot change the name of the column using this statement.

Hope, I explained well in detail.

How do I load a file into the python console?

You can just use an import statement:

from file import *

So, for example, if you had a file named my_script.py you'd load it like so:

from my_script import *

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

How to convert an Stream into a byte[] in C#?

I use this extension class:

public static class StreamExtensions
{
    public static byte[] ReadAllBytes(this Stream instream)
    {
        if (instream is MemoryStream)
            return ((MemoryStream) instream).ToArray();

        using (var memoryStream = new MemoryStream())
        {
            instream.CopyTo(memoryStream);
            return memoryStream.ToArray();
        }
    }
}

Just copy the class to your solution and you can use it on every stream:

byte[] bytes = myStream.ReadAllBytes()

Works great for all my streams and saves a lot of code! Of course you can modify this method to use some of the other approaches here to improve performance if needed, but I like to keep it simple.

How to get the range of occupied cells in excel sheet

These two lines on their own wasnt working for me:

xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

You can test by hitting ctrl+end in the sheet and seeing which cell is selected.

I found that adding this line after the first two solved the problem in all instances I've encountered:

Excel.Range xlActiveRange = WorkSheet.UsedRange;

Can I dispatch an action in reducer?

Dispatching and action inside of reducer seems occurs bug.

I made a simple counter example using useReducer which "INCREASE" is dispatched then "SUB" also does.

In the example I expected "INCREASE" is dispatched then also "SUB" does and, set cnt to -1 and then continue "INCREASE" action to set cnt to 0, but it was -1 ("INCREASE" was ignored)

See this: https://codesandbox.io/s/simple-react-context-example-forked-p7po7?file=/src/index.js:144-154

let listener = () => {
  console.log("test");
};
const middleware = (action) => {
  console.log(action);
  if (action.type === "INCREASE") {
    listener();
  }
};

const counterReducer = (state, action) => {
  middleware(action);
  switch (action.type) {
    case "INCREASE":
      return {
        ...state,
        cnt: state.cnt + action.payload
      };
    case "SUB":
      return {
        ...state,
        cnt: state.cnt - action.payload
      };
    default:
      return state;
  }
};

const Test = () => {
  const { cnt, increase, substract } = useContext(CounterContext);

  useEffect(() => {
    listener = substract;
  });

  return (
    <button
      onClick={() => {
        increase();
      }}
    >
      {cnt}
    </button>
  );
};

{type: "INCREASE", payload: 1}
{type: "SUB", payload: 1}
// expected: cnt: 0
// cnt = -1

Verify External Script Is Loaded

If the script creates any variables or functions in the global space you can check for their existance:

External JS (in global scope) --

var myCustomFlag = true;

And to check if this has run:

if (typeof window.myCustomFlag == 'undefined') {
    //the flag was not found, so the code has not run
    $.getScript('<external JS>');
}

Update

You can check for the existence of the <script> tag in question by selecting all of the <script> elements and checking their src attributes:

//get the number of `<script>` elements that have the correct `src` attribute
var len = $('script').filter(function () {
    return ($(this).attr('src') == '<external JS>');
}).length;

//if there are no scripts that match, the load it
if (len === 0) {
    $.getScript('<external JS>');
}

Or you can just bake this .filter() functionality right into the selector:

var len = $('script[src="<external JS>"]').length;

Text editor to open big (giant, huge, large) text files

Free read-only viewers:

  • Large Text File Viewer (Windows) – Fully customizable theming (colors, fonts, word wrap, tab size). Supports horizontal and vertical split view. Also support file following and regex search. Very fast, simple, and has small executable size.
  • klogg (Windows, macOS, Linux) – A maintained fork of glogg, its main feature is regular expression search. It can also watch files, allows the user to mark lines, and has serious optimizations built in. But from a UI standpoint, it's ugly and clunky.
  • LogExpert (Windows) – "A GUI replacement for tail." It's really a log file analyzer, not a large file viewer, and in one test it required 10 seconds and 700 MB of RAM to load a 250 MB file. But its killer features are the columnizer (parse logs that are in CSV, JSONL, etc. and display in a spreadsheet format) and the highlighter (show lines with certain words in certain colors). Also supports file following, tabs, multifiles, bookmarks, search, plugins, and external tools.
  • Lister (Windows) – Very small and minimalist. It's one executable, barely 500 KB, but it still supports searching (with regexes), printing, a hex editor mode, and settings.
  • loxx (Windows) – Supports file following, highlighting, line numbers, huge files, regex, multiple files and views, and much more. The free version can not: process regex, filter files, synchronize timestamps, and save changed files.

Free editors:

  • Your regular editor or IDE. Modern editors can handle surprisingly large files. In particular, Vim (Windows, macOS, Linux), Emacs (Windows, macOS, Linux), Notepad++ (Windows), Sublime Text (Windows, macOS, Linux), and VS Code (Windows, macOS, Linux) support large (~4 GB) files, assuming you have the RAM.
  • Large File Editor (Windows) – Opens and edits TB+ files, supports Unicode, uses little memory, has XML-specific features, and includes a binary mode.
  • GigaEdit (Windows) – Supports searching, character statistics, and font customization. But it's buggy – with large files, it only allows overwriting characters, not inserting them; it doesn't respect LF as a line terminator, only CRLF; and it's slow.

Builtin programs (no installation required):

  • less (macOS, Linux) – The traditional Unix command-line pager tool. Lets you view text files of practically any size. Can be installed on Windows, too.
  • Notepad (Windows) – Decent with large files, especially with word wrap turned off.
  • MORE (Windows) – This refers to the Windows MORE, not the Unix more. A console program that allows you to view a file, one screen at a time.

Web viewers:

Paid editors:

  • 010 Editor (Windows, macOS, Linux) – Opens giant (as large as 50 GB) files.
  • SlickEdit (Windows, macOS, Linux) – Opens large files.
  • UltraEdit (Windows, macOS, Linux) – Opens files of more than 6 GB, but the configuration must be changed for this to be practical: Menu » Advanced » Configuration » File Handling » Temporary Files » Open file without temp file...
  • EmEditor (Windows) – Handles very large text files nicely (officially up to 248 GB, but as much as 900 GB according to one report).
  • BssEditor (Windows) – Handles large files and very long lines. Don’t require an installation. Free for non commercial use.

Duplicate headers received from server

The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.

For example:

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

Remove Safari/Chrome textinput/textarea glow

This effect can occur on non-input elements, too. I've found the following works as a more general solution

:focus {
  outline-color: transparent;
  outline-style: none;
}

Update: You may not have to use the :focus selector. If you have an element, say <div id="mydiv">stuff</div>, and you were getting the outer glow on this div element, just apply like normal:

#mydiv {
  outline-color: transparent;
  outline-style: none;
}

How to save RecyclerView's scroll position using RecyclerView.State?

All layout managers bundled in the support library already know how to save and restore scroll position.

Scroll position is restored on the first layout pass which happens when the following conditions are met:

  • a layout manager is attached to the RecyclerView
  • an adapter is attached to the RecyclerView

Typically you set the layout manager in XML so all you have to do now is

  1. Load the adapter with data
  2. Then attach the adapter to the RecyclerView

You can do this at any time, it's not constrained to Fragment.onCreateView or Activity.onCreate.

Example: Ensure the adapter is attached every time the data is updated.

viewModel.liveData.observe(this) {
    // Load adapter.
    adapter.data = it

    if (list.adapter != adapter) {
        // Only set the adapter if we didn't do it already.
        list.adapter = adapter
    }
}

The saved scroll position is calculated from the following data:

  • Adapter position of the first item on the screen
  • Pixel offset of the top of the item from the top of the list (for vertical layout)

Therefore you can expect a slight mismatch e.g. if your items have different dimensions in portrait and landscape orientation.


The RecyclerView/ScrollView/whatever needs to have an android:id for its state to be saved.

Should 'using' directives be inside or outside the namespace?

According the to StyleCop Documentation:

SA1200: UsingDirectivesMustBePlacedWithinNamespace

Cause A C# using directive is placed outside of a namespace element.

Rule Description A violation of this rule occurs when a using directive or a using-alias directive is placed outside of a namespace element, unless the file does not contain any namespace elements.

For example, the following code would result in two violations of this rule.

using System;
using Guid = System.Guid;

namespace Microsoft.Sample
{
    public class Program
    {
    }
}

The following code, however, would not result in any violations of this rule:

namespace Microsoft.Sample
{
    using System;
    using Guid = System.Guid;

    public class Program
    {
    }
}

This code will compile cleanly, without any compiler errors. However, it is unclear which version of the Guid type is being allocated. If the using directive is moved inside of the namespace, as shown below, a compiler error will occur:

namespace Microsoft.Sample
{
    using Guid = System.Guid;
    public class Guid
    {
        public Guid(string s)
        {
        }
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            Guid g = new Guid("hello");
        }
    }
}

The code fails on the following compiler error, found on the line containing Guid g = new Guid("hello");

CS0576: Namespace 'Microsoft.Sample' contains a definition conflicting with alias 'Guid'

The code creates an alias to the System.Guid type called Guid, and also creates its own type called Guid with a matching constructor interface. Later, the code creates an instance of the type Guid. To create this instance, the compiler must choose between the two different definitions of Guid. When the using-alias directive is placed outside of the namespace element, the compiler will choose the local definition of Guid defined within the local namespace, and completely ignore the using-alias directive defined outside of the namespace. This, unfortunately, is not obvious when reading the code.

When the using-alias directive is positioned within the namespace, however, the compiler has to choose between two different, conflicting Guid types both defined within the same namespace. Both of these types provide a matching constructor. The compiler is unable to make a decision, so it flags the compiler error.

Placing the using-alias directive outside of the namespace is a bad practice because it can lead to confusion in situations such as this, where it is not obvious which version of the type is actually being used. This can potentially lead to a bug which might be difficult to diagnose.

Placing using-alias directives within the namespace element eliminates this as a source of bugs.

  1. Multiple Namespaces

Placing multiple namespace elements within a single file is generally a bad idea, but if and when this is done, it is a good idea to place all using directives within each of the namespace elements, rather than globally at the top of the file. This will scope the namespaces tightly, and will also help to avoid the kind of behavior described above.

It is important to note that when code has been written with using directives placed outside of the namespace, care should be taken when moving these directives within the namespace, to ensure that this is not changing the semantics of the code. As explained above, placing using-alias directives within the namespace element allows the compiler to choose between conflicting types in ways that will not happen when the directives are placed outside of the namespace.

How to Fix Violations To fix a violation of this rule, move all using directives and using-alias directives within the namespace element.

Java Mouse Event Right Click

Yes, take a look at this thread which talks about the differences between platforms.

How to detect right-click event for Mac OS

BUTTON3 is the same across all platforms, being equal to the right mouse button. BUTTON2 is simply ignored if the middle button does not exist.

What is lexical scope?

Lexical scope refers to the lexicon of identifiers (e.g., variables, functions, etc.) visible from the current position in the execution stack.

- global execution context
    - foo
    - bar
    - function1 execution context
        - foo2
        - bar2
        - function2 execution context
            - foo3
            - bar3

foo and bar are always within the lexicon of available identifiers because they are global.

When function1 is executed, it has access to a lexicon of foo2, bar2, foo, and bar.

When function2 is executed, it has access to a lexicon of foo3, bar3, foo2, bar2, foo, and bar.

The reason global and/or outer functions do not have access to an inner functions identifiers is because the execution of that function has not occurred yet and therefore, none of its identifiers have been allocated to memory. What’s more, once that inner context executes, it is removed from the execution stack, meaning that all of it’s identifiers have been garbage collected and are no longer available.

Finally, this is why a nested execution context can ALWAYS access it’s ancestors execution context and thus why it has access to a greater lexicon of identifiers.

See:

Special thanks to @robr3rd for help simplifying the above definition.

Conversion of Char to Binary in C

Your code is very vague and not understandable, but I can provide you with an alternative.

First of all, if you want temp to go through the whole string, you can do something like this:

char *temp;
for (temp = your_string; *temp; ++temp)
    /* do something with *temp */

The term *temp as the for condition simply checks whether you have reached the end of the string or not. If you have, *temp will be '\0' (NUL) and the for ends.

Now, inside the for, you want to find the bits that compose *temp. Let's say we print the bits:

for (as above)
{
    int bit_index;
    for (bit_index = 7; bit_index >= 0; --bit_index)
    {
        int bit = *temp >> bit_index & 1;
        printf("%d", bit);
    }
    printf("\n");
}

To make it a bit more generic, that is to convert any type to bits, you can change the bit_index = 7 to bit_index = sizeof(*temp)*8-1

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):

C:\xampp\php\PEAR\initcontrols\header_myworks.php

providing the path you pasted in the subject is correct. Make sure your file is located there.

For more info you can get and set the include path programmatically.

Increment a database field by 1

I not expert in MySQL but you probably should look on triggers e.g. BEFORE INSERT. In the trigger you can run select query on your original table and if it found something just update the row 'logins' instead of inserting new values. But all this depends on version of MySQL you running.

How do I execute external program within C code in linux with arguments?

For a simple way, use system():

#include <stdlib.h>
...
int status = system("./foo 1 2 3");

system() will wait for foo to complete execution, then return a status variable which you can use to check e.g. exitcode (the command's exitcode gets multiplied by 256, so divide system()'s return value by that to get the actual exitcode: int exitcode = status / 256).

The manpage for wait() (in section 2, man 2 wait on your Linux system) lists the various macros you can use to examine the status, the most interesting ones would be WIFEXITED and WEXITSTATUS.

Alternatively, if you need to read foo's standard output, use popen(3), which returns a file pointer (FILE *); interacting with the command's standard input/output is then the same as reading from or writing to a file.

mysql said: Cannot connect: invalid settings. xampp

I also have the problem but now solved

$cfg['Servers'][$i]['user'] = 'admin'; - I change the user name from 'root' to 'admin'

500.21 Bad module "ManagedPipelineHandler" in its module list

I had this problem every time I deployed a new website or updated an existing one using MSDeploy.

I was able to fix this by unloading the app domain using MSDeploy with the following syntax:

msdeploy.exe -verb:sync -source:recycleApp -dest:recycleApp="Default Web Site/myAppName",recycleMode=UnloadAppDomain

You can also stop, start, or recycle the application pool - more details here: http://technet.microsoft.com/en-us/library/ee522997%28v=ws.10%29.aspx

While Armaan's solution helped get me unstuck, it did not make the problem go away permanently.

MySQL combine two columns into one column

convert(varchar, column_name1) + (varchar, column_name)

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="check1" type="checkbox" checked="" name="copyNewAddrToBilling">
    </body>
    <script language="javascript">
        document.getElementById("check1").checked = true;
        document.getElementById("check1").checked = false;
    </script>
</html>

I have added the language attribute to the script element, but it is unnecessary because all browsers use this as a default, but it leaves no doubt what this example is showing.

If you want to use javascript to access elements, it has a very limited set of GetElement* functions. So you are going to need to get into the habit of giving every element a UNIQUE id attribute.

Converting a list to a set changes element order

Remove duplicates and preserve order by below function

def unique(sequence):
    seen = set()
    return [x for x in sequence if not (x in seen or seen.add(x))]

How to remove duplicates from a list while preserving order in Python

MySQL Job failed to start

To help others who do not have a full disk to troubleshoot this problem, first inspect your error log (for me the path is given in my /etc/mysql/my.cnf file):

tail /var/log/mysql/error.log

My problem turned out to be a new IP address allocated after some network router reconfiguration, so I needed to change the bind-address variable.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I also had similar problem where redirects were giving 404 or 405 randomly on my development server. It was an issue with gunicorn instances.

Turns out that I had not properly shut down the gunicorn instance before starting a new one for testing. Somehow both of the processes were running simultaneously, listening to the same port 8080 and interfering with each other. Strangely enough they continued running in background after I had killed all my terminals. Had to kill them manually using fuser -k 8080/tcp

What are the benefits of learning Vim?

I think it's definitely worth the time and effort to learn vim. To me, it makes typing and navigating around text so efficient, it's hard to imagine going back to emacs or ctrl/shift/alt/meta key combos.

Don't get intimidated by all the fancy features of vim. Once you've used it enough, you'll figure out which commands you use the most, and you'll figure out which things you can forget about.

Add a tooltip to a div

Here's a nice jQuery Tooltip:

https://jqueryui.com/tooltip/

To implement this, just follow these steps:

  1. Add this code in your <head></head> tags:

    <script type="text/javascript" src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>    
    <script type="text/javascript">
    $("[title]").tooltip();
    </script> 
    <style type="text/css"> 
    
    /* tooltip styling. by default the element to be styled is .tooltip  */
    .tooltip {
        display:none;
        background:transparent url(https://dl.dropboxusercontent.com/u/25819920/tooltip/black_arrow.png);
        font-size:12px;
        height:70px;
        width:160px;
        padding:25px;
        color:#fff;
    }
    </style> 
    
  2. On the HTML elements that you want to have the tooltip, just add a title attribute to it. Whatever text is in the title attribute will be in the tooltip.

Note: When JavaScript is disabled, it will fallback to the default browser/operating system tooltip.

Android Intent Cannot resolve constructor

Use

Intent myIntent = new Intent(v.getContext(), MyClass.class);

or

 Intent myIntent = new Intent(MyFragment.this.getActivity(), MyClass.class);

to start a new Activity. This is because you will need to pass Application or component context as a first parameter to the Intent Constructor when you are creating an Intent for a specific component of your application.

How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

Towards the second half of Create REST API using ASP.NET MVC that speaks both JSON and plain XML, to quote:

Now we need to accept JSON and XML payload, delivered via HTTP POST. Sometimes your client might want to upload a collection of objects in one shot for batch processing. So, they can upload objects using either JSON or XML format. There's no native support in ASP.NET MVC to automatically parse posted JSON or XML and automatically map to Action parameters. So, I wrote a filter that does it."

He then implements an action filter that maps the JSON to C# objects with code shown.

Showing all session data at once?

For print session data you do not need to use print_r() function every time .

If you use it then it will be non-readable format.Data will be looks very dirty.

But if you use my function all you have to do is to use p()-Funtion and pass data into it. //create new file into application/cms_helper.php and load helper cms into //autoload or on controller

/*Copy Code for p function from here and paste into cms_helper.php in application/helpers folder */

   //@parram $data-array,$d-if true then die by default it is false
   //@author Your name

    function p($data,$d = false){

          echo "<pre>"; 
             print_r($data);
          echo "</pre>"; 

        if($d == TRUE){
             die();
          } 
      }

Just remember to load cms_helper into your project or controller using $this->load->helper('cms'); use bellow code into your controller or model it will works just GREAT.

 p($this->session->all_userdata()); // it will apply pre to your sesison data and other array as  well

PHP code to get selected text of a combo box

if you fetching it from database then

<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>"; 
$q2=mysql_query($s2); 
while($rw2=mysql_fetch_array($q2)) { 
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>

Send a base64 image in HTML email

Support, unfortunately, is brutal at best. Here's a post on the topic:

https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/

And the post content: enter image description here

Query to display all tablespaces in a database and datafiles

SELECT a.file_name,
       substr(A.tablespace_name,1,14) tablespace_name,
       trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
       trunc(a.bytes/1024/1024) allocated_mb,
       trunc(A.MAXSIZE/1024/1024) capacity,
       a.autoextensible ae
FROM (
     SELECT file_id, file_name,
            tablespace_name,
            autoextensible,
            bytes,
            decode(autoextensible,'YES',maxbytes,bytes) maxsize
     FROM   dba_data_files
     GROUP BY file_id, file_name,
              tablespace_name,
              autoextensible,
              bytes,
              decode(autoextensible,'YES',maxbytes,bytes)
     ) a,
     (SELECT file_id,
             tablespace_name,
             sum(bytes) free
      FROM   dba_free_space
      GROUP BY file_id,
               tablespace_name
      ) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC; 

Passing a varchar full of comma delimited values to a SQL Server IN function

I think a very simple solution could be following:

DECLARE @Ids varchar(50);
SET @Ids = '1,2,3,5,4,6,7,98,234';

SELECT * 
FROM sometable 
WHERE ','+@Ids+',' LIKE '%,'+CONVERT(VARCHAR(50),tableid)+',%';

Format a message using MessageFormat.format() in Java

Just be sure you have used double apostrophe ('')

String text = java.text.MessageFormat.format("You''re about to delete {0} rows.", 5);
System.out.println(text);

Edit:

Within a String, a pair of single quotes can be used to quote any arbitrary characters except single quotes. For example, pattern string "'{0}'" represents string "{0}", not a FormatElement. ...

Any unmatched quote is treated as closed at the end of the given pattern. For example, pattern string "'{0}" is treated as pattern "'{0}'".

Source http://docs.oracle.com/javase/7/docs/api/java/text/MessageFormat.html

git: fatal unable to auto-detect email address

I'm running Ubuntu through Windows Subsystem for Linux and had properly set my credentials through Git Bash, including in VS Code's terminal (where I was getting the error every time I tried to commit.)

Apparently even tho VS is using Bash in the terminal, the UI git controls still run through Windows, where I had not set my credentials.

Setting the credentials in Windows Powershell fixed the issue

FAIL - Application at context path /Hello could not be started

check web.xml file maybe servletContextlistener not doing well . in my case i added servletContextlistener and let him an empty and gave me the same error, i tried to delete it from project files but it still in web.xml file .finally i delete it from the web.xml and save the file . run the project and it stated successfully

Redirect to external URI from ASP.NET MVC controller

Using JavaScript

 public ActionResult Index()
 {
    return Content("<script>window.location = 'http://www.example.com';</script>");
 }

Note: As @Jeremy Ray Brown said , This is not the best option but you might find useful in some situations.

Hope this helps.

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

I just finished setting up my XAMPP on the MAC and had the same trouble. I just fixed it. It is not quite clear what OS you're using but you need to run the XAMPP security. You indicate you've done that, but here it is anyway for the MAC

sudo /Applications/XAMPP/xamppfiles/xampp security 

Set your password on the questions you get.

In you're phpmyadmin import the "create_tables.sql" .. Which can be found in the ./phpmyadmin/sql folder.

Next open the config.inc.php file inside the ./phpmyadmin folder.

$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'you_password';

Make sure to log out and log in to reflect the changes within phpmyadmin

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Adding javafx accessible permission in eclipse oxygen go to project> properties> java build path> libraries> then expand the libraries and double click on> Access rules there you set the permission Resolution : Accessible Rule Pattern : javafx/**

enter image description here

enter image description here

enter image description here

android View not attached to window manager

Why not try catch, like this:

protected void onPostExecute(Object result) {
        try {
            if ((mDialog != null) && mDialog.isShowing()) {
                mDialog.dismiss();
            }
        } catch (Exception ex) {
            Log.e(TAG, ex.getMessage(), ex);
        }
    }

Unicode (UTF-8) reading and writing to files in Python

The \x.. sequence is something that's specific to Python. It's not a universal byte escape sequence.

How you actually enter in UTF-8-encoded non-ASCII depends on your OS and/or your editor. Here's how you do it in Windows. For OS X to enter a with an acute accent you can just hit option + E, then A, and almost all text editors in OS X support UTF-8.

How to retrieve unique count of a field using Kibana + Elastic Search

For Kibana 4 go to this answer

This is easy to do with a terms panel:

Adding a terms panel to Kibana

If you want to select the count of distinct IP that are in your logs, you should specify in the field clientip, you should put a big enough number in length (otherwise, it will join different IP under the same group) and specify in the style table. After adding the panel, you will have a table with IP, and the count of that IP:

Table with IP and count

What is the best way to check for Internet connectivity using .NET?

The accepted answer succeeds quickly but is very slow to fail when there is no connection. So I wanted to build a robust connection check that would fail faster.

Pinging was said to not be supported in all environments, so I started with the accepted answer and added a WebClient from here with a custom timeout. You can pick any timeout, but 3 seconds worked for me while connected via wifi. I tried adding a fast iteration (1 second), then a slow iteration (3 seconds) if the first one fails. But that made no sense since both iterations would always fail (when not connected) or always succeed (when connected).

I'm connecting to AWS since I want to upload a file when the connection test passes.

public static class AwsHelpers
{
    public static bool GetCanConnectToAws()
    {
        try
        {
            using (var client = new WebClientWithShortTimeout())
            using (client.OpenRead("https://aws.amazon.com"))
                return true;
        }
        catch
        {
            return false;
        }
    }
}

public class WebClientWithShortTimeout: WebClient
{
    protected override WebRequest GetWebRequest(Uri uri)
    {
        var webRequest = base.GetWebRequest(uri);
        webRequest.Timeout = 5000;
        return webRequest;
    }
}

How to remove underline from a name on hover

try this:

legend.green-color a:hover{
    text-decoration: none;
}

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Convert Base64 string to an image file?

The problem is that data:image/png;base64, is included in the encoded contents. This will result in invalid image data when the base64 function decodes it. Remove that data in the function before decoding the string, like so.

function base64_to_jpeg($base64_string, $output_file) {
    // open the output file for writing
    $ifp = fopen( $output_file, 'wb' ); 

    // split the string on commas
    // $data[ 0 ] == "data:image/png;base64"
    // $data[ 1 ] == <actual base64 string>
    $data = explode( ',', $base64_string );

    // we could add validation here with ensuring count( $data ) > 1
    fwrite( $ifp, base64_decode( $data[ 1 ] ) );

    // clean up the file resource
    fclose( $ifp ); 

    return $output_file; 
}

Returning JSON response from Servlet to Javascript/JSP page

I used JSONObject as shown below in Servlet.

    JSONObject jsonReturn = new JSONObject();

    NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);

    map = new HashMap<String, String>();
    map.put("Status", "Success");
    map.put("FailureReason", "None");
    map.put("DataElements", "2");

    jsonReturn = new JSONObject();
    jsonReturn.accumulate("Header", map);

    List<String> list = new ArrayList<String>();
    list.add(NhAdminTree);
    list.add(userName);

    jsonReturn.accumulate("Elements", list);

The Servlet returns this JSON object as shown below:

    response.setContentType("application/json");
    response.getWriter().write(jsonReturn.toString());

This Servlet is called from Browser using AngularJs as below

$scope.GetNeighborhoodTreeUsingPost = function(){
    alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );

    $http({

        method: 'POST',
        url : 'http://localhost:8080/EPortal/xlEPortalService',
        headers: {
           'Content-Type': 'application/json'
         },
        data : {
            'action': 64,
            'userName' : $scope.userName
        }
    }).success(function(data, status, headers, config){
        alert("DATA.header.status : " + data.Header.Status);
        alert("DATA.header.FailureReason : " + data.Header.FailureReason);
        alert("DATA.header.DataElements : " + data.Header.DataElements);
        alert("DATA.elements : " + data.Elements);

    }).error(function(data, status, headers, config) {
        alert(data + " : " + status + " : " + headers + " : " + config);
    });

};

This code worked and it is showing correct data in alert dialog box:

Data.header.status : Success

Data.header.FailureReason : None

Data.header.DetailElements : 2

Data.Elements : Coma seperated string values i.e. NhAdminTree, userName

In Subversion can I be a user other than my login name?

Using Subversion with either the Apache module or svnserve. I've been able to perform operations as multiple users using --username.

Each time you invoke a Subversion command as a 'new' user, your $HOME/.subversion/auth/<authentication-method>/ directory will have a new entry cached for that user (assuming you are able to authenticate with the correct password or authentication method for the server you are contacting as that particular user).

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

I'll post this here in case it's useful to anyone…

On iOS Safari, calls to navigator.geolocation.getCurrentPosition would timeout if I had an active navigator.geolocation.watchPosition function running.

Starting and stopping the watchPosition properly using clearWatch() as described here, worked: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition

Add Bean Programmatically to Spring Web App Context

First initialize Property values

MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());

DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);

context.registerBeanDefinition("beanName", connectionFactory);

Add to the list of beans

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));

No server in windows>preferences

If above answers did not work for you then just click this link https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-enterprise-java-developers download according to your OS. And after downloading and extracting the ZIP open the extract folder and click on Eclipse application icon. enter image description here

Then just enter your workspace and get started. Now you will be able to see the servers option in Window->Show View, like this:

enter image description here

Looping over elements in jQuery

don't think you need quotations on this:

var child = $("this");

try:

var child = $(this);

How to strip all whitespace from string

As mentioned by Roger Pate following code worked for me:

s = " \t foo \n bar "
"".join(s.split())
'foobar'

I am using Jupyter Notebook to run following code:

i=0
ProductList=[]
while i < len(new_list): 
   temp=''                            # new_list[i]=temp=' Plain   Utthapam  '
   #temp=new_list[i].strip()          #if we want o/p as: 'Plain Utthapam'
   temp="".join(new_list[i].split())  #o/p: 'PlainUtthapam' 
   temp=temp.upper()                  #o/p:'PLAINUTTHAPAM' 
   ProductList.append(temp)
   i=i+2

"use database_name" command in PostgreSQL

You must specify the database to use on connect; if you want to use psql for your script, you can use "\c name_database"

user_name=# CREATE DATABASE testdatabase; 
user_name=# \c testdatabase 

At this point you might see the following output

You are now connected to database "testdatabase" as user "user_name".
testdatabase=#

Notice how the prompt changes. Cheers, have just been hustling looking for this too, too little information on postgreSQL compared to MySQL and the rest in my view.

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

Access Form - Syntax error (missing operator) in query expression

I was able to quickly fix it by going into Design View of the Form and putting [] around any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.

Is Fortran easier to optimize than C for heavy calculations?

Generally FORTRAN is slower than C. C can use hardware level pointers allowing the programmer to hand-optimize. FORTRAN (in most cases) doesn't have access to hardware memory addressing hacks. (VAX FORTRAN is another story.) I've used FORTRAN on and off since the '70's. (Really.)

However, starting in the 90's FORTRAN has evolved to include specific language constructs that can be optimized into inherently parallel algorithms that can really scream on a multi-core processor. For example, automatic Vectorizing allows multiple processors to handle each element in a vector of data concurrently. 16 processors -- 16 element vector -- processing takes 1/16th the time.

In C, you have to manage your own threads and design your algorithm carefully for multi-processing, and then use a bunch of API calls to make sure that the parallelism happens properly.

In FORTRAN, you only have to design your algorithm carefully for multi-processing. The compiler and run-time can handle the rest for you.

You can read a little about High Performance Fortran, but you find a lot of dead links. You're better off reading about Parallel Programming (like OpenMP.org) and how FORTRAN supports that.

#1064 -You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

Rule 1: You can not add a new table without specifying the primary key constraint[not a good practice if you create it somehow]. So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Rule 2: You are not allowed to use the keywords(words with predefined meaning) as a field name. Here type is something like that is used(commonly used with Join Types). So the code:

CREATE TABLE transactions( 
id int NOT NULL AUTO_INCREMENT, 
location varchar(50) NOT NULL, 
description varchar(50) NOT NULL, 
category varchar(50) NOT NULL, 
amount double(10,9) NOT NULL, 
transaction_type varchar(6) NOT NULL,  
notes varchar(512), 
receipt int(10), 
PRIMARY KEY(id));

Now you please try with this code. First check it in your database user interface(I am running HeidiSQL, or you can try it in your xampp/wamp server also)and make sure this code works. Now delete the table from your db and execute the code in your program. Thank You.

How to get CPU temperature?

For others who may come by here, maybe take a look at : http://openhardwaremonitor.org/

Follow that link and at first you might think, "hey that's an Application, that is why it was removed, the question was how to do this from C# code, not to find an application that can tell me the temperature..." This is where it shows you are not willing to invest enough time in reading what "Open Hardware Monitor" also is.

They also include a Data Interface, here is the description:

Data Interface The Open Hardware Monitor publishes all sensor data to WMI (Windows Management Instrumentation). This allows other applications to read and use the sensor information as well. A preliminary documentation of the interface can be found here(click).

When you download it, it contains the OpenHardwareMonitor.exe application, you're not looking for that one. It also contains the OpenHardwareMonitorLib.dll, you're looking for that one.

It is mostly, if not 100%, just a wrapper around the WinRing0 API, which you could choose to wrap your self if you feel like it.

I have tried this out from a C# app myself, and it works. Although it is still in beta, it seemed rather stable. It is also open source so it could be a good starting point instead.

At the end of the day I find it hard to believe that is not on topic of this question.

Git says local branch is behind remote branch, but it's not

To diagnose it, follow this answer.

But to fix it, knowing you are the only one changing it, do:
1 - backup your project (I did only the files on git, ./src folder)
2 - git pull
3 - restore you backup over the many "messed" files (with merge indicators)

I tried git pull -s recursive -X ours but didnt work the way I wanted, it could be an option tho, but backup first!!!

Make sure the differences/changes (at git gui) are none. This is my case, there is nothing to merge at all, but github keeps saying I should merge...

How do you dynamically allocate a matrix?

The other answer describing arrays of arrays are correct.
BUT if you are planning of doing a anything mathematical with the arrays - or need something special like sparse matrices you should look at one of the many maths libs like TNT before re-inventing too many wheels

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

With TensorFlow release 1.3.0, you need to use Cudnn 6.0 instead of Cudnn 5.0 as Cudnn 5.0 is giving this error. Don't forget to add path variable to Cudnn 6.0 .With cudnn64_6.dll your Tensorflow will work fine. Read the link below. https://github.com/tensorflow/tensorflow/blob/master/RELEASE.md#release-130

Use jQuery to change value of a label

Validation (HTML5): Attribute 'name' is not a valid attribute of element 'label'.

How to show shadow around the linearlayout in Android?

For lollipop and above you can use elevation.

For older versions:

Here is a lazy hack from: http://odedhb.blogspot.com/2013/05/android-layout-shadow-without-9-patch.html

(toast_frame does not work on KitKat, shadow was removed from toasts)

just use:

android:background="@android:drawable/toast_frame"

or:

android:background="@android:drawable/dialog_frame"

as a background

examples:

<TextView
        android:layout_width="fill_parent"
        android:text="I am a simple textview with a shadow"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:padding="16dp"
        android:textColor="#fff"
        android:background="@android:drawable/toast_frame"
        />

and with different bg color:

<LinearLayout
        android:layout_height="64dp"
        android:layout_width="fill_parent"
        android:gravity="center"
        android:background="@android:drawable/toast_frame"
        android:padding="4dp"
        >
    <Button
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="Button shadow"
            android:background="#33b5e5"
            android:textSize="24sp"
            android:textStyle="bold"
            android:textColor="#fff"
            android:layout_gravity="center|bottom"
            />

</LinearLayout>

What is the difference between Html.Hidden and Html.HiddenFor

Html.Hidden('name', 'value') creates a hidden tag with name = 'name' and value = 'value'.

Html.HiddenFor(x => x.nameProp) creates a hidden tag with a name = 'nameProp' and value = x.nameProp.

At face value these appear to do similar things, with one just more convenient than the other. But its actual value is for model binding. When MVC tries to associate the html to the model, it needs to have the name of the property, and for Html.Hidden, we chose 'name', and not 'nameProp', and thus the binding wouldn't work. You'd have to have a custom binding object, or get the values from the form data. If you are redisplaying the page, you'd have to set the model to the values again.

So you can use Html.Hidden, but if you get the name wrong, or if you change the property name in the model, the auto binding will fail when you submit the form. But by using a type checked expression, you'll get code completion, and when you change the property name, you will get a compile time error. And then you are guaranteed to have the correct name in the form.

One of the better features of MVC.

How to create a Multidimensional ArrayList in Java?

Wouldn't List<ArrayList<String>> 2dlist = new ArrayList<ArrayList<String>>(); be a better (more efficient) implementation?

How to put a new line into a wpf TextBlock control?

Using System.Environment.NewLine is the only solution that worked for me. When I tried \r\n, it just repeated the actual \r\n in the text box.

Checking for multiple conditions using "when" on single task in ansible

Adding to https://stackoverflow.com/users/1638814/nvartolomei answer, which will probably fix your error.

Strictly answering your question, I just want to point out that the when: statement is probably correct, but would look easier to read in multiline and still fulfill your logic:

when: 
  - sshkey_result.rc == 1
  - github_username is undefined or 
    github_username |lower == 'none'

https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#the-when-statement

"static const" vs "#define" vs "enum"

In C, specifically? In C the correct answer is: use #define (or, if appropriate, enum)

While it is beneficial to have the scoping and typing properties of a const object, in reality const objects in C (as opposed to C++) are not true constants and therefore are usually useless in most practical cases.

So, in C the choice should be determined by how you plan to use your constant. For example, you can't use a const int object as a case label (while a macro will work). You can't use a const int object as a bit-field width (while a macro will work). In C89/90 you can't use a const object to specify an array size (while a macro will work). Even in C99 you can't use a const object to specify an array size when you need a non-VLA array.

If this is important for you then it will determine your choice. Most of the time, you'll have no choice but to use #define in C. And don't forget another alternative, that produces true constants in C - enum.

In C++ const objects are true constants, so in C++ it is almost always better to prefer the const variant (no need for explicit static in C++ though).

How to use forEach in vueJs?

You can also use .map() as:

var list=[];

response.data.message.map(function(value, key) {
     list.push(value);
   });

SQL split values to multiple rows

If the name column were a JSON array (like '["a","b","c"]'), then you could extract/unpack it with JSON_TABLE() (available since MySQL 8.0.4):

select t.id, j.name
from mytable t
join json_table(
  t.name,
  '$[*]' columns (name varchar(50) path '$')
) j;

Result:

| id  | name |
| --- | ---- |
| 1   | a    |
| 1   | b    |
| 1   | c    |
| 2   | b    |

View on DB Fiddle

If you store the values in a simple CSV format, then you would first need to convert it to JSON:

select t.id, j.name
from mytable t
join json_table(
  replace(json_array(t.name), ',', '","'),
  '$[*]' columns (name varchar(50) path '$')
) j

Result:

| id  | name |
| --- | ---- |
| 1   | a    |
| 1   | b    |
| 1   | c    |
| 2   | b    |

View on DB Fiddle

Mysql 1050 Error "Table already exists" when in fact, it does not

Sounds like you have Schroedinger's table...

Seriously now, you probably have a broken table. Try:

  • DROP TABLE IF EXISTS contenttype
  • REPAIR TABLE contenttype
  • If you have sufficient permissions, delete the data files (in /mysql/data/db_name)

How to prevent a background process from being stopped after closing SSH client in Linux

Personally, I like the 'batch' command.

$ batch
> mycommand -x arg1 -y arg2 -z arg3
> ^D

This stuffs it in to the background, and then mails the results to you. It's a part of cron.

Automatically start a Windows Service on install

You corrupted your designer. ReAdd your Installer Component. It should have a serviceInstaller and a serviceProcessInstaller. The serviceInstaller with property Startup Method set to Automatic will startup when installed and after each reboot.

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

On Windows 10 - This happened for me after the latest update in 2020.

What solved this issue for me was running the following in PowerShell

C:\>Install-Module -Name MicrosoftPowerBIMgmt

Permission denied error on Github Push

For some reason my push and pull origin was changed to HTTPS-url in stead of SSH-url (probably a copy-paste error on my end), but trying to push would give me the following error after trying to login:

Username for 'https://github.com': xxx
Password for 'https://[email protected]': 
remote: Invalid username or password.

Updating the remote origin with the SSH url, solved the problem:

git remote set-url origin [email protected]:<username>/<repo>.git

Hope this helps!

Returning http 200 OK with error within response body

HTTP status codes say something about the HTTP protocol. HTTP 200 means transmission is OK on the HTTP level (i.e request was technically OK and server was able to respond properly). See this wiki page for a list of all codes and their meaning.

HTTP 200 has nothing to do with success or failure of your "business code". In your example the HTTP 200 is an acceptable status to indicate that your "business code error message" was successfully transferred, provided that no technical issues prevented the business logic to run properly.

Alternatively you could let your server respond with HTTP 5xx if technical or unrecoverable problems happened on the server. Or HTTP 4xx if the incoming request had issues (e.g. wrong parameters, unexpected HTTP method...) Again, these all indicate technical errors, whereas HTTP 200 indicates NO technical errors, but makes no guarantee about business logic errors.

To summarize: YES it is valid to send error messages (for non-technical issues) in your http response together with HTTP status 200. Whether this applies to your case is up to you. If for instance the client is asking for a file that isn't there, that would be more like a 404. If there is a misconfiguration on the server that might be a 500. If client asks for a seat on a plane that is booked full, that would be 200 and your "implementation" will dictate how to recognise/handle this (e.g. JSON block with a { "booking","failed" })

FIFO based Queue implementations?

Queue is an interface that extends Collection in Java. It has all the functions needed to support FIFO architecture.

For concrete implementation you may use LinkedList. LinkedList implements Deque which in turn implements Queue. All of these are a part of java.util package.

For details about method with sample example you can refer FIFO based Queue implementation in Java.

PS: Above link goes to my personal blog that has additional details on this.

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

What is the best way to create and populate a numbers table?

If you're just doing this in either SQL Server Management Studio or sqlcmd.exe, you can use the fact that the batch separator allows you to repeat the batch:

CREATE TABLE Number (N INT IDENTITY(1,1) PRIMARY KEY NOT NULL);
GO

INSERT INTO Number DEFAULT VALUES;
GO 100000

This will insert 100000 records into the Numbers table using the default value of the next identity.

It's slow. It compares to METHOD 1 in @KM.'s answer, which is the slowest of the examples. However, it's about as code light as it gets. You could speed it up somewhat by adding the primary key constraint after the insert batch.

Select all DIV text with single mouse click

For content editable stuff (not regular inputs, you need to use selectNodeContents (rather than just selectNode).

NOTE: All the references to "document.selection" and "createTextRange()" are for IE 8 and lower... You'll not likely need to support that monster if you're attempting to do tricky stuff like this.

function selectElemText(elem) {

    //Create a range (a range is a like the selection but invisible)
    var range = document.createRange();

    // Select the entire contents of the element
    range.selectNodeContents(elem);

    // Don't select, just positioning caret:
    // In front 
    // range.collapse();
    // Behind:
    // range.collapse(false);

    // Get the selection object
    var selection = window.getSelection();

    // Remove any current selections
    selection.removeAllRanges();

    // Make the range you have just created the visible selection
    selection.addRange(range);

}

Match at every second occurrence

Suppose the pattern you want is abc+d. You want to match the second occurrence of this pattern in a string.

You would construct the following regex:

abc+d.*?(abc+d)

This would match strings of the form: <your-pattern>...<your-pattern>. Since we're using the reluctant qualifier *? we're safe that there cannot be another match of between the two. Using matcher groups which pretty much all regex implementations provide you would then retrieve the string in the bracketed group which is what you want.

display data from SQL database into php/ html table

Here's a simple function I wrote to display tabular data without having to input each column name: (Also, be aware: Nested looping)

function display_data($data) {
    $output = '<table>';
    foreach($data as $key => $var) {
        $output .= '<tr>';
        foreach($var as $k => $v) {
            if ($key === 0) {
                $output .= '<td><strong>' . $k . '</strong></td>';
            } else {
                $output .= '<td>' . $v . '</td>';
            }
        }
        $output .= '</tr>';
    }
    $output .= '</table>';
    echo $output;
}

UPDATED FUNCTION BELOW

Hi Jack,

your function design is fine, but this function always misses the first dataset in the array. I tested that.

Your function is so fine, that many people will use it, but they will always miss the first dataset. That is why I wrote this amendment.

The missing dataset results from the condition if key === 0. If key = 0 only the columnheaders are written, but not the data which contains $key 0 too. So there is always missing the first dataset of the array.

You can avoid that by moving the if condition above the second foreach loop like this:

function display_data($data) {
    $output = "<table>";
    foreach($data as $key => $var) {
        //$output .= '<tr>';
        if($key===0) {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= "<td>" . $col . '</td>';
            }
            $output .= '</tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
        else {
            $output .= '<tr>';
            foreach($var as $col => $val) {
                $output .= '<td>' . $val . '</td>';
            }
            $output .= '</tr>';
        }
    }
    $output .= '</table>';
    echo $output;
}

Best regards and thanks - Axel Arnold Bangert - Herzogenrath 2016

and another update that removes redundant code blocks that hurt maintainability of the code.

function display_data($data) {
$output = '<table>';
foreach($data as $key => $var) {
    $output .= '<tr>';
    foreach($var as $k => $v) {
        if ($key === 0) {
            $output .= '<td><strong>' . $k . '</strong></td>';
        } else {
            $output .= '<td>' . $v . '</td>';
        }
    }
    $output .= '</tr>';
}
$output .= '</table>';
echo $output;

}

Parse an URL in JavaScript

function parse_url(str, component) {
  //       discuss at: http://phpjs.org/functions/parse_url/
  //      original by: Steven Levithan (http://blog.stevenlevithan.com)
  // reimplemented by: Brett Zamir (http://brett-zamir.me)
  //         input by: Lorenzo Pisani
  //         input by: Tony
  //      improved by: Brett Zamir (http://brett-zamir.me)
  //             note: original by http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: blog post at http://blog.stevenlevithan.com/archives/parseuri
  //             note: demo at http://stevenlevithan.com/demo/parseuri/js/assets/parseuri.js
  //             note: Does not replace invalid characters with '_' as in PHP, nor does it return false with
  //             note: a seriously malformed URL.
  //             note: Besides function name, is essentially the same as parseUri as well as our allowing
  //             note: an extra slash after the scheme/protocol (to allow file:/// as in PHP)
  //        example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
  //        returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}

  var query, key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port',
      'relative', 'path', 'directory', 'file', 'query', 'fragment'
    ],
    ini = (this.php_js && this.php_js.ini) || {},
    mode = (ini['phpjs.parse_url.mode'] &&
      ini['phpjs.parse_url.mode'].local_value) || 'php',
    parser = {
      php: /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
      loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-scheme to catch file:/// (should restrict this)
    };

  var m = parser[mode].exec(str),
    uri = {},
    i = 14;
  while (i--) {
    if (m[i]) {
      uri[key[i]] = m[i];
    }
  }

  if (component) {
    return uri[component.replace('PHP_URL_', '')
      .toLowerCase()];
  }
  if (mode !== 'php') {
    var name = (ini['phpjs.parse_url.queryKey'] &&
      ini['phpjs.parse_url.queryKey'].local_value) || 'queryKey';
    parser = /(?:^|&)([^&=]*)=?([^&]*)/g;
    uri[name] = {};
    query = uri[key[12]] || '';
    query.replace(parser, function($0, $1, $2) {
      if ($1) {
        uri[name][$1] = $2;
      }
    });
  }
  delete uri.source;
  return uri;
}

reference

How to convert a NumPy array to PIL image applying matplotlib colormap

The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:

import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')

np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.

load external css file in body tag

No, it is not okay to put a link element in the body tag. See the specification (links to the HTML4.01 specs, but I believe it is true for all versions of HTML):

“This element defines a link. Unlike A, it may only appear in the HEAD section of a document, although it may appear any number of times.”

How to use a ViewBag to create a dropdownlist?

I do the following

In my action method

    Dictionary<string, string> dictAccounts = ViewModelDropDown.GetAccounts(id);
    ViewBag.accounts = dictAccounts;

In my View Code

 Dictionary<string, string> accounts = (Dictionary<string, string>)ViewBag.accounts;
 @Html.DropDownListFor(model => model.AccountId, new SelectList(accounts, "Value", "Key"), new { style = "width:310px; height: 30px; padding 5px; margin: 5px 0 6px; background: none repeat scroll 0 0 #FFFFFF; vertical-align:middle;" })

Javascript: how to validate dates in format MM-DD-YYYY?

what isn't working about it? here's a tested version:

String.prototype.isValidDate = function()   {

    const match = this.match(/^([0-9]{2})\/([0-9]{2})\/([0-9]{4})$/);
    if (!match || match.length !== 4) {
        return false
    }

    const test = new Date(match[3], match[1] - 1, match[2]);

    return (
        (test.getMonth() == match[1] - 1) &&
        (test.getDate() == match[2]) &&
        (test.getFullYear() == match[3])
    );
}

var date = '12/08/1984'; // Date() is 'Sat Dec 08 1984 00:00:00 GMT-0800 (PST)'
alert(date.isValidDate() ); // true

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

I was been getting that error in mobile safari when using ASP.NET MVC to return a FileResult with the overload that returns a file with a different file name than the original. So,

return File(returnFilePath, contentType, fileName);

would give the error in mobile safari, where as

return File(returnFilePath, contentType);

would not.

I don't even remember why I thought what I was doing was a good idea. Trying to be clever I guess.

Stopping a JavaScript function when a certain condition is met

Use a try...catch statement in your main function and whenever you want to stop the function just use:

throw new Error("Stopping the function!");

Display HTML snippets in HTML

You could try:

_x000D_
_x000D_
Hello! Here is some code:_x000D_
_x000D_
<xmp>_x000D_
<div id="hello">_x000D_
_x000D_
</div>_x000D_
</xmp>
_x000D_
_x000D_
_x000D_

Eclipse "this compilation unit is not on the build path of a java project"

If you're a beginner (like me), the solution may be as simple as making sure the parent folder that the file you're working in is a Java project.

I made the mistake of simply creating a Java folder, then creating a file in the folder and expecting it to work. The file needs to live in a project if you want to avoid this error.

Specifying width and height as percentages without skewing photo proportions in HTML

You can set one or the other (just not both) and that should get the result you want.

<img src="#" height="50%">

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

This exception comes from the client, right? Please perform a forward and reverse DNS lookup of the server hostname. Your server has incorrect DNS entries. They are absolutely crucial for Kerberos. The proper place is your DNS server, in your case: domain controller. Figure out the IP address of your DNS server and contact your admin. The other option is a missing SPN, please check that too.

Jquery Date picker Default Date

Are u using this datepicker http://jqueryui.com/demos/datepicker/ ? if yes there are options to set the default Date.If you didn't change anything , by default it will show the current date.

any way this will gives current date

$( ".selector" ).datepicker({ defaultDate: new Date() });

What is the meaning of 'No bundle URL present' in react-native?

I tried most of answers above. But the only that works for is a watchman command(I use react-native: "0.60.4"):

watchman watch-del-all

Setting attribute disabled on a SPAN element does not prevent click events

@click=" canClick ? doClick : void 0"

User click but nothing happen can meet your

I use it in vuejs work fine

Pass variable to function in jquery AJAX success callback

Try something like this (use this.url to get the url):

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

Taken from here

how to remove multiple columns in r dataframe?

Basic subsetting:

album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7

Conversion failed when converting the nvarchar value ... to data type int

You got this Error because you tried to convert column DataType from String to int which is

leagal if and only if

you dont have row in that table with string content inside that column

so just make sure your previously inserted Rows is compatible with the new changes

How to get text and a variable in a messagebox

I kind of run into the same issue. I wanted my message box to display the message and the vendorcontractexpiration. This is what I did:

Dim ab As String
Dim cd As String

ab = "THE CONTRACT FOR THIS VENDOR WILL EXPIRE ON "
cd = VendorContractExpiration


If InvoiceDate >= VendorContractExpiration - 120 And InvoiceDate < VendorContractExpiration Then

MsgBox [ab] & [cd], vbCritical, "WARNING"

End If

href="file://" doesn't work

The reason your URL is being rewritten to file///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is because you specified http://file://

The http:// at the beginning is the protocol being used, and your browser is stripping out the second colon (:) because it is invalid.

Note

If you link to something like

<a href="file:///K:/yourfile.pdf">yourfile.pdf</a>

The above represents a link to a file called k:/yourfile.pdf on the k: drive on the machine on which you are viewing the URL.

You can do this, for example the below creates a link to C:\temp\test.pdf

<a href="file:///C:/Temp/test.pdf">test.pdf</a>

By specifying file:// you are indicating that this is a local resource. This resource is NOT on the internet.

Most people do not have a K:/ drive.

But, if this is what you are trying to achieve, that's fine, but this is not how a "typical" link on a web page works, and you shouldn't being doing this unless everyone who is going to access your link has access to the (same?) K:/drive (this might be the case with a shared network drive).

You could try

<a href="file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>
<a href="2011-07-05/SOP-SOP-3.0.pdf">test.pdf</a>

Note that http://file:///K:/AmberCRO%20SOP/2011-07-05/SOP-SOP-3.0.pdf is a malformed

Checking for empty result (php, pdo, mysql)

I only found one way that worked...

$quote = $pdomodel->executeQuery("SELECT * FROM MyTable");

//if (!is_array($quote)) {  didn't work
//if (!isset($quote)) {  didn't work

if (count($quote) == 0) {   //yep the count worked.
    echo 'Record does not exist.';
    die;
}

Convert all strings in a list to int

You can do it simply in one line when taking input.

[int(i) for i in input().split("")]

Split it where you want.

If you want to convert a list not list simply put your list name in the place of input().split("").

How to restart remote MySQL server running on Ubuntu linux?

  1. SSH into the machine. Using the proper credentials and ip address, ssh [email protected]. This should provide you with shell access to the Ubuntu server.
  2. Restart the mySQL service. sudo service mysql restart should do the job.

If your mySQL service is named something else like mysqld you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart

How to convert NSNumber to NSString

In Swift you can do like this

let number : NSNumber = 95
let str : String = number.stringValue

Swing JLabel text change on the running application

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
public class Test extends JFrame implements ActionListener
{
    private JLabel label;
    private JTextField field;
    public Test()
    {
        super("The title");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(400, 90));
        ((JPanel) getContentPane()).setBorder(new EmptyBorder(13, 13, 13, 13) );
        setLayout(new FlowLayout());
        JButton btn = new JButton("Change");
        btn.setActionCommand("myButton");
        btn.addActionListener(this);
        label = new JLabel("flag");
        field = new JTextField(5);
        add(field);
        add(btn);
        add(label);
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
        setResizable(false);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getActionCommand().equals("myButton"))
        {
            label.setText(field.getText());
        }
    }
    public static void main(String[] args)
    {
        new Test();
    }
}

Using HTML5 file uploads with AJAX and jQuery

It's not too hard. Firstly, take a look at FileReader Interface.

So, when the form is submitted, catch the submission process and

var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file
var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = shipOff;
//reader.onloadstart = ...
//reader.onprogress = ... <-- Allows you to update a progress bar.
//reader.onabort = ...
//reader.onerror = ...
//reader.onloadend = ...


function shipOff(event) {
    var result = event.target.result;
    var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg'
    $.post('/myscript.php', { data: result, name: fileName }, continueSubmission);
}

Then, on the server side (i.e. myscript.php):

$data = $_POST['data'];
$fileName = $_POST['name'];
$serverFile = time().$fileName;
$fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting
fwrite($fp, $data);
fclose($fp);
$returnData = array( "serverFile" => $serverFile );
echo json_encode($returnData);

Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg in /uploads/ on your server, and respond with a JSON variable (to a continueSubmission() function) containing the fileName on the server.

Check out fwrite() and jQuery.post().

On the above page it details how to use readAsBinaryString(), readAsDataUrl(), and readAsArrayBuffer() for your other needs (e.g. images, videos, etc).

Each GROUP BY expression must contain at least one column that is not an outer reference

To start with you can't do this:

having rid!=MAX(rid)

The HAVING clause can only contain things which are attributes of the aggregate groups.

In addition, 1, 2, 3 is not valid in GROUP BY in SQL Server - I think that's only valid in ORDER BY.

Can you explain why this isn't what you are looking for:

select 
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound,
MAX(qvalues.rid)
 from batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
where LEN(datapath)>4
group by LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

Implement runtime permission for running your app on Android 6.0 Marshmallow (API 23) or later.

or you can manually enable the storage permission-

goto settings>apps> "your_app_name" >click on it >then click permissions> then enable the storage. Thats it.

But i suggest go the for first one which is, Implement runtime permissions in your code.

Two-way SSL clarification

Both certificates should exist prior to the connection. They're usually created by Certification Authorities (not necessarily the same). (There are alternative cases where verification can be done differently, but some verification will need to be made.)

The server certificate should be created by a CA that the client trusts (and following the naming conventions defined in RFC 6125).

The client certificate should be created by a CA that the server trusts.

It's up to each party to choose what it trusts.

There are online CA tools that will allow you to apply for a certificate within your browser and get it installed there once the CA has issued it. They need not be on the server that requests client-certificate authentication.

The certificate distribution and trust management is the role of the Public Key Infrastructure (PKI), implemented via the CAs. The SSL/TLS client and servers and then merely users of that PKI.

When the client connects to a server that requests client-certificate authentication, the server sends a list of CAs it's willing to accept as part of the client-certificate request. The client is then able to send its client certificate, if it wishes to and a suitable one is available.

The main advantages of client-certificate authentication are:

  • The private information (the private key) is never sent to the server. The client doesn't let its secret out at all during the authentication.
  • A server that doesn't know a user with that certificate can still authenticate that user, provided it trusts the CA that issued the certificate (and that the certificate is valid). This is very similar to the way passports are used: you may have never met a person showing you a passport, but because you trust the issuing authority, you're able to link the identity to the person.

You may be interested in Advantages of client certificates for client authentication? (on Security.SE).

Python 3.2 Unable to import urllib2 (ImportError: No module named urllib2)

In python 3 urllib2 was merged into urllib. See also another Stack Overflow question and the urllib PEP 3108.

To make Python 2 code work in Python 3:

try:
    import urllib.request as urllib2
except ImportError:
    import urllib2

Excel VBA Run-time Error '32809' - Trying to Understand it

I have removed all ActiveX controls from sheet and now it works smoothly without any error messages. That's my solution.

Get Current date & time with [NSDate date]

NSLocale* currentLocale = [NSLocale currentLocale];
[[NSDate date] descriptionWithLocale:currentLocale];  

or use

NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
// or @"yyyy-MM-dd hh:mm:ss a" if you prefer the time with AM/PM 
NSLog(@"%@",[dateFormatter stringFromDate:[NSDate date]]);

Hibernate Annotations - Which is better, field or property access?

To make your classes cleaner, put the annotation in the field then use @Access(AccessType.PROPERTY)

How do I get the Git commit count?

If you’re looking for a unique and still quite readable identifier for commits, git describe might be just the thing for you.

Vim multiline editing like in sublimetext?

Ctrl-v ................ start visual block selection
6j .................... go down 6 lines
I" .................... inserts " at the beginning
<Esc><Esc> ............ finishes start
2fdl. ................. second 'd' l (goes right) . (repeats insertion)

creating Hashmap from a JSON String

Don't do this yourself, I suggest.
Use a library, e.g. the Gson library from Google.

https://code.google.com/p/google-gson/

Verify object attribute value with mockito

This is answer based on answer from iraSenthil but with annotation (Captor). In my opinion it has some advantages:

  • it's shorter
  • it's easier to read
  • it can handle generics without warnings

Example:

@RunWith(MockitoJUnitRunner.class)
public class SomeTest{

    @Captor
    private ArgumentCaptor<List<SomeType>> captor;

    //...

    @Test 
    public void shouldTestArgsVals() {
        //...
        verify(mockedObject).someMethodOnMockedObject(captor.capture());

        assertThat(captor.getValue().getXXX(), is("expected"));
    }
}

DBNull if statement

The closest equivalent to your VB would be (see this):

Convert.IsDBNull()

But there are a number of ways to do this, and most are linked from here

How to make primary key as autoincrement for Room Persistence lib

For example, if you have a users entity you want to store, with fields (firstname, lastname , email) and you want autogenerated id, you do this.

@Entity(tableName = "users")
data class Users(
   @PrimaryKey(autoGenerate = true)
   val id: Long,
   val firstname: String,
   val lastname: String,
   val email: String
)

Room will then autogenerate and auto-increment the id field.

Case statement in MySQL

Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

Run cron job only if it isn't already running

As a follow up to Earlz answer, you need a wrapper script that creates a $PID.running file when it starts, and delete when it ends. The wrapper script calls the script you wish to run. The wrapper is necessary in case the target script fails or errors out, the pid file gets deleted..

Create PDF with Java

Another alternative would be JasperReports: JasperReports Library. It uses iText itself and is more than a PDF library you asked for, but if it fits your needs I'd go for it.

Simply put, it allows you to design reports that can be filled during runtime. If you use a custom datasource, you might be able to integrate JasperReports easily into the existing system. It would save you the whole layouting troubles, e.g. when invoices span over more sites where each side should have a footer and so on.

How to add a constant column in a Spark DataFrame?

As the other answers have described, lit and typedLit are how to add constant columns to DataFrames. lit is an important Spark function that you will use frequently, but not for adding constant columns to DataFrames.

You'll commonly be using lit to create org.apache.spark.sql.Column objects because that's the column type required by most of the org.apache.spark.sql.functions.

Suppose you have a DataFrame with a some_date DateType column and would like to add a column with the days between December 31, 2020 and some_date.

Here's your DataFrame:

+----------+
| some_date|
+----------+
|2020-09-23|
|2020-01-05|
|2020-04-12|
+----------+

Here's how to calculate the days till the year end:

val diff = datediff(lit(Date.valueOf("2020-12-31")), col("some_date"))
df
  .withColumn("days_till_yearend", diff)
  .show()
+----------+-----------------+
| some_date|days_till_yearend|
+----------+-----------------+
|2020-09-23|               99|
|2020-01-05|              361|
|2020-04-12|              263|
+----------+-----------------+

You could also use lit to create a year_end column and compute the days_till_yearend like so:

import java.sql.Date

df
  .withColumn("yearend", lit(Date.valueOf("2020-12-31")))
  .withColumn("days_till_yearend", datediff(col("yearend"), col("some_date")))
  .show()
+----------+----------+-----------------+
| some_date|   yearend|days_till_yearend|
+----------+----------+-----------------+
|2020-09-23|2020-12-31|               99|
|2020-01-05|2020-12-31|              361|
|2020-04-12|2020-12-31|              263|
+----------+----------+-----------------+

Most of the time, you don't need to use lit to append a constant column to a DataFrame. You just need to use lit to convert a Scala type to a org.apache.spark.sql.Column object because that's what's required by the function.

See the datediff function signature:

enter image description here

As you can see, datediff requires two Column arguments.

Difference between the Apache HTTP Server and Apache Tomcat?

Tomcat is primarily an application server, which serves requests to custom-built Java servlets or JSP files on your server. It is usually used in conjunction with the Apache HTTP server (at least in my experience). Use it to manually process incoming requests.

The HTTP server, by itself, is best for serving up static content... html files, images, etc.

Move to another EditText when Soft Keyboard Next is clicked on Android

Focus Handling

Focus movement is based on an algorithm which finds the nearest neighbor in a given direction. In rare cases, the default algorithm may not match the intended behavior of the developer.

Change default behaviour of directional navigation by using following XML attributes:

android:nextFocusDown="@+id/.."  
android:nextFocusLeft="@+id/.."    
android:nextFocusRight="@+id/.."    
android:nextFocusUp="@+id/.."  

Besides directional navigation you can use tab navigation. For this you need to use

android:nextFocusForward="@+id/.."

To get a particular view to take focus, call

view.requestFocus()

To listen to certain changing focus events use a View.OnFocusChangeListener


Keyboard button

You can use android:imeOptions for handling that extra button on your keyboard.

Additional features you can enable in an IME associated with an editor to improve the integration with your application. The constants here correspond to those defined by imeOptions.

The constants of imeOptions includes a variety of actions and flags, see the link above for their values.

Value example

ActionNext :

the action key performs a "next" operation, taking the user to the next field that will accept text.

ActionDone :

the action key performs a "done" operation, typically meaning there is nothing more to input and the IME will be closed.

Code example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="16dp"
        android:imeOptions="actionNext"
        android:maxLines="1"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="24dp"
        android:imeOptions="actionDone"
        android:maxLines="1"
        android:ems="10" />

</RelativeLayout>

If you want to listen to imeoptions events use a TextView.OnEditorActionListener.

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            performSearch();
            return true;
        }
        return false;
    }
});

How can I wrap text in a label using WPF?

try use this

lblresult.Content = lblresult.Content + "prime are :" + j + "\n";

What is the difference between a mutable and immutable string in C#?

None, actually. The String class is mutable.

unsafe
{
    string foo = string.Copy("I am immutable.");
    fixed (char* pChar = foo)
    {
        char* pFoo = pChar;

        pFoo[5] = ' ';
        pFoo[6] = ' ';
    }

    Console.WriteLine(foo); // "I am   mutable."
}

This kind of logic is done all the time in the String and StringBuilder classes, actually. They just allocate a new string each time you call Concat, Substring, etc. and use pointer arithmetic to copy over to the new string. Strings just don't mutate themselves, hence why they are considered "immutable".


By the way, do not attempt this with string literals or you will badly mess up your program:

string bar = "I am a string.";

fixed (char* pChar = bar)
{
    char* pBar = pChar;

    pBar[2] = ' ';
}

string baz = "I am a string.";

Console.WriteLine(baz); // "I  m a string."

This is because string literals are interned in the desktop .NET Framework; in other words, bar and baz point to the exact same string, so mutating one will mutate the other. This is all fine and dandy though if you're using an unmanaged platform like WinRT, which lacks string interning.

Select single item from a list

SingleOrDefault() is what you need

cheers

Install pip in docker

While T. Arboreus's answer might fix the issues with resolving 'archive.ubuntu.com', I think the last error you're getting says that it doesn't know about the packages php5-mcrypt and python-pip. Nevertheless, the reduced Dockerfile of you with just these two packages worked for me (using Debian 8.4 and Docker 1.11.0), but I'm not quite sure if that could be the case because my host system is different than yours.

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    php5-mcrypt \
    python-pip

However, according to this answer you should think about installing the python3-pip package instead of the python-pip package when using Python 3.x.

Furthermore, to make the php5-mcrypt package installation working, you might want to add the universe repository like it's shown right here. I had trouble with the add-apt-repository command missing in the Ubuntu Docker image so I installed the package software-properties-common at first to make the command available.

Splitting up the statements and putting apt-get update and apt-get install into one RUN command is also recommended here.

Oh and by the way, you actually don't need the -y flag at apt-get update because there is nothing that has to be confirmed automatically.

Finally:

FROM ubuntu:14.04

# Install dependencies
RUN apt-get update && apt-get install -y \
    software-properties-common
RUN add-apt-repository universe
RUN apt-get update && apt-get install -y \
    apache2 \
    curl \
    git \
    libapache2-mod-php5 \
    php5 \
    php5-mcrypt \
    php5-mysql \
    python3.4 \
    python3-pip

Remark: The used versions (e.g. of Ubuntu) might be outdated in the future.

Is it possible to make an HTML anchor tag not clickable/linkable using CSS?

The answer is:

<a href="page.html" onclick="return false">page link</a>

How to go up a level in the src path of a URL in HTML?

Here is all you need to know about relative file paths:

  • Starting with / returns to the root directory and starts there

  • Starting with ../ moves one directory backward and starts there

  • Starting with ../../ moves two directories backward and starts there (and so on...)

  • To move forward, just start with the first sub directory and keep moving forward.

Click here for more details!

$(document).ready(function() is not working

You only get this error if jQuery is not correctly loaded, you can check with firebug what url its trying to load so you can see if your relative path is wrong.

Also, on a separate note, you can use $(function(){ as a shorthand to $(document).ready(function(){

Make an image width 100% of parent div, but not bigger than its own width

I found an answer which worked for me and can be found in the following link:

Full Width Containers in Limited Width Parents

Which is better, return value or out parameter?

Return values are almost always the right choice when the method doesn't have anything else to return. (In fact, I can't think of any cases where I'd ever want a void method with an out parameter, if I had the choice. C# 7's Deconstruct methods for language-supported deconstruction acts as a very, very rare exception to this rule.)

Aside from anything else, it stops the caller from having to declare the variable separately:

int foo;
GetValue(out foo);

vs

int foo = GetValue();

Out values also prevent method chaining like this:

Console.WriteLine(GetValue().ToString("g"));

(Indeed, that's one of the problems with property setters as well, and it's why the builder pattern uses methods which return the builder, e.g. myStringBuilder.Append(xxx).Append(yyy).)

Additionally, out parameters are slightly harder to use with reflection and usually make testing harder too. (More effort is usually put into making it easy to mock return values than out parameters). Basically there's nothing I can think of that they make easier...

Return values FTW.

EDIT: In terms of what's going on...

Basically when you pass in an argument for an "out" parameter, you have to pass in a variable. (Array elements are classified as variables too.) The method you call doesn't have a "new" variable on its stack for the parameter - it uses your variable for storage. Any changes in the variable are immediately visible. Here's an example showing the difference:

using System;

class Test
{
    static int value;

    static void ShowValue(string description)
    {
        Console.WriteLine(description + value);
    }

    static void Main()
    {
        Console.WriteLine("Return value test...");
        value = 5;
        value = ReturnValue();
        ShowValue("Value after ReturnValue(): ");

        value = 5;
        Console.WriteLine("Out parameter test...");
        OutParameter(out value);
        ShowValue("Value after OutParameter(): ");
    }

    static int ReturnValue()
    {
        ShowValue("ReturnValue (pre): ");
        int tmp = 10;
        ShowValue("ReturnValue (post): ");
        return tmp;
    }

    static void OutParameter(out int tmp)
    {
        ShowValue("OutParameter (pre): ");
        tmp = 10;
        ShowValue("OutParameter (post): ");
    }
}

Results:

Return value test...
ReturnValue (pre): 5
ReturnValue (post): 5
Value after ReturnValue(): 10
Out parameter test...
OutParameter (pre): 5
OutParameter (post): 10
Value after OutParameter(): 10

The difference is at the "post" step - i.e. after the local variable or parameter has been changed. In the ReturnValue test, this makes no difference to the static value variable. In the OutParameter test, the value variable is changed by the line tmp = 10;

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

I had the same problem with something like

@foreach (var item in Model)
{
    @Html.DisplayFor(m => !item.IsIdle, "BoolIcon")
}

I solved this just by doing

@foreach (var item in Model)
{
    var active = !item.IsIdle;
    @Html.DisplayFor(m => active , "BoolIcon")
}

When you know the trick, it's simple.

The difference is that, in the first case, I passed a method as a parameter whereas in the second case, it's an expression.

Bootstrap 3 breakpoints and media queries

for bootstrap 3 I have the following code in my navbar component

/**
 * Navbar styling.
 */
@mobile:          ~"screen and (max-width: @{screen-xs-max})";
@tablet:          ~"screen and (min-width: @{screen-sm-min})";
@normal:          ~"screen and (min-width: @{screen-md-min})";
@wide:            ~"screen and (min-width: @{screen-lg-min})";
@grid-breakpoint: ~"screen and (min-width: @{grid-float-breakpoint})";

then you can use something like

@media wide { selector: style }

This uses whatever value you have the variables set to.

Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

http://lesscss.org

Good tutorial for using HTML5 History API (Pushstate?)

I've written a very simple router abstraction on top of History.js, called StateRouter.js. It's in very early stages of development, but I am using it as the routing solution in a single-page application I'm writing. Like you, I found History.js very hard to grasp, especially as I'm quite new to JavaScript, until I understood that you really need (or should have) a routing abstraction on top of it, as it solves a low-level problem.

This simple example code should demonstrate how it's used:

var router = new staterouter.Router();
// Configure routes
router
  .route('/', getHome)
  .route('/persons', getPersons)
  .route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();

Here's a little fiddle I've concocted in order to demonstrate its usage.

How do I show a message in the foreach loop?

You are looking to see if a single value is in an array. Use in_array.

However note that case is important, as are any leading or trailing spaces. Use var_dump to find out the length of the strings too, and see if they fit.

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

What is the use of the @Temporal annotation in Hibernate?

This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (i.e., the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date/time or both (TIMESTAMP) in database table.

The temporal precision is not specified in core Java APIs. @Temporal is a JPA annotation that converts back and forth between timestamp and java.util.Date. It also converts time-stamp into time. For example, in the snippet below, @Temporal(TemporalType.DATE) drops the time value and only preserves the date.

@Temporal(TemporalType.DATE)
private java.util.Date creationDate;

As per javadocs,

Annotation to declare an appropriate {@code TemporalType} on query method parameters. Note that this annotation can only be used on parameters of type {@link Date} with default TemporalType.DATE

[Information above collected from various sources]

How to check if a registry value exists using C#?

        internal static Func<string, string, bool> regKey = delegate (string KeyLocation, string Value)
        {
            // get registry key with Microsoft.Win32.Registrys
            RegistryKey rk = (RegistryKey)Registry.GetValue(KeyLocation, Value, null); // KeyLocation and Value variables from method, null object because no default value is present. Must be casted to RegistryKey because method returns object.
            if ((rk) == null) // if the RegistryKey is null which means it does not exist
            {
                // the key does not exist
                return false; // return false because it does not exist
            }
            // the registry key does exist
            return true; // return true because it does exist
        };

usage:

        // usage:
        /* Create Key - while (loading)
        {
            RegistryKey k;
            k = Registry.CurrentUser.CreateSubKey("stuff");
            k.SetValue("value", "value");
            Thread.Sleep(int.MaxValue);
        }; // no need to k.close because exiting control */


        if (regKey(@"HKEY_CURRENT_USER\stuff  ...  ", "value"))
        {
             // key exists
             return;
        }
        // key does not exist

What is the best way to trigger onchange event in react js

At least on text inputs, it appears that onChange is listening for input events:

var event = new Event('input', { bubbles: true });
element.dispatchEvent(event);

Log all queries in mysql

Quick way to enable MySQL General Query Log without restarting.

mysql> SET GLOBAL general_log = 'ON';
mysql> SET GLOBAL general_log_file = '/var/www/nanhe/log/all.log';

I have installed mysql through homebrew, mysql version : mysql Ver 14.14 Distrib 5.7.15, for osx10.11 (x86_64) using EditLine wrapper

What's the best way to set a single pixel in an HTML5 canvas?

putImageData is probably faster than fillRect natively. I think this because the fifth parameter can have different ways to be assigned (the rectangle color), using a string that must be interpreted.

Suppose you're doing that:

context.fillRect(x, y, 1, 1, "#fff")
context.fillRect(x, y, 1, 1, "rgba(255, 255, 255, 0.5)")`
context.fillRect(x, y, 1, 1, "rgb(255,255,255)")`
context.fillRect(x, y, 1, 1, "blue")`

So, the line

context.fillRect(x, y, 1, 1, "rgba(255, 255, 255, 0.5)")`

is the most heavy between all. The fifth argument in the fillRect call is a bit longer string.

What is the scope of variables in JavaScript?

Variables declared globally have a global scope. Variables declared within a function are scoped to that function, and shadow global variables of the same name.

(I'm sure there are many subtleties that real JavaScript programmers will be able to point out in other answers. In particular I came across this page about what exactly this means at any time. Hopefully this more introductory link is enough to get you started though.)

ArrayList: how does the size increase?

ArrayList in Java grows by 50% of its original capacity once it is full.

Byte[] to InputStream or OutputStream

There is no conversion between InputStream/OutputStream and the bytes they are working with. They are made for binary data, and just read (or write) the bytes one by one as is.

A conversion needs to happen when you want to go from byte to char. Then you need to convert using a character set. This happens when you make String or Reader from bytes, which are made for character data.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

Try this :

    driver.findElement(By.id("email")).clear(); 
driver.findElement(By.id("email")).sendKeys("[email protected]");

Git blame -- prior commits?

Building on the previous answer, this bash one-liner should give you what you're looking for. It displays the git blame history for a particular line of a particular file, through the last 5 revisions:

LINE=10 FILE=src/options.cpp REVS=5; for commit in $(git rev-list -n $REVS HEAD $FILE); do git blame -n -L$LINE,+1 $commit -- $FILE; done

In the output of this command, you might see the content of the line change, or the line number displayed might even change, for a particular commit.

This often indicates that the line was added for the first time, after that particular commit. It could also indicate the line was moved from another part of the file.

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.

But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.

What's the difference between Docker Compose vs. Dockerfile

In my workflow, I add a Dockerfile for each part of my system and configure it that each part could run individually. Then I add a docker-compose.yml to bring them together and link them.

Biggest advantage (in my opinion): when linking the containers, you can define a name and ping your containers with this name. Therefore your database might be accessible with the name db and no longer by its IP.

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

Goto processes in mysql.

So can see there is task still working.

Kill the particular process or wait until process complete.

Flutter.io Android License Status Unknown

The right solution would be if you have android studio installed then

  1. open SDK manager
  2. under SDK tools uncheck hide obsolete packages at the bottom
  3. then you should see an option called Android SDK Tools (Obsolete)

enter image description here

  1. check it and apply and let the studio download the package
  2. once done run the command flutter doctor and it should now prompt you to run flutter doctor --android-licenses once you run the license command accept all licenses by hitting y and it should solve the problem

enter image description here

How do I count unique visitors to my site?

$user_ip=$_SERVER['REMOTE_ADDR'];

$check_ip = mysql_query("select userip from pageview where page='yourpage'  and userip='$user_ip'");
if(mysql_num_rows($check_ip)>=1)
{

}
else
{
  $insertview = mysql_query("insert into pageview values('','yourpage','$user_ip')");

  $updateview = mysql_query("update totalview set totalvisit = totalvisit+1 where page='yourpage' ");
}

code from talkerscode official tutorial if you have any problem http://talkerscode.com/webtricks/create-a-simple-pageviews-counter-using-php-and-mysql.php

How to use Google fonts in React.js?

Here are two different ways you can adds fonts to your react app.

Adding local fonts

  1. Create a new folder called fonts in your src folder.

  2. Download the google fonts locally and place them inside the fonts folder.

  3. Open your index.css file and include the font by referencing the path.

@font-face {
  font-family: 'Rajdhani';
  src: local('Rajdhani'), url(./fonts/Rajdhani/Rajdhani-Regular.ttf) format('truetype');
}

Here I added a Rajdhani font.

Now, we can use our font in css classes like this.

.title{
    font-family: Rajdhani, serif;
    color: #0004;
}

Adding Google fonts

If you like to use google fonts (api) instead of local fonts, you can add it like this.

@import url('https://fonts.googleapis.com/css2?family=Rajdhani:wght@300;500&display=swap');

Similarly, you can also add it inside the index.html file using link tag.

<link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@300;500&display=swap" rel="stylesheet">

(originally posted at https://reactgo.com/add-fonts-to-react-app/)

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

In case anyone gets the same error I did: “Requirements installation failed with status: 1.” here's what to do:

Install Homebrew (for some reason might not work automatically) with this command:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Then proceed to install rvm again using

curl -sSL https://get.rvm.io | bash -s stable --ruby

Quit and reopen Terminal and then:

rvm install 2.2
rvm use 2.2 --default

Adding gif image in an ImageView in android

Based on Ahmad Dwaik 'Warlock's comment, I have tried the following code and it worked.

  1. Use a webview in your xml file, and adjust its position to the place where exactly you were trying to show you .gif image.
  2. In your activity initialise this small piece of webview like other views.
  3. place the .gif image in assets folder
  4. now load the image as if you are loading a url into webview like "diyaWebView1.loadUrl("file:///android_asset/www/diya.gif");"
  5. you can see your .gif image when you launch the application.

P.S : this things works if you .gif image fits your webview or viceversa else if the image is bigger than the webview the scrollbar gets enabled and user can scroll the image AKA webview. So we need to be careful when we use this, to give proper size to the webview as per image or edit the image that fits your webview.

How to create a MySQL hierarchical recursive query?

I have made a query for you. This will give you Recursive Category with a Single Query:

SELECT id,NAME,'' AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 WHERE prent is NULL
UNION 
SELECT b.id,a.name,b.name AS subName,'' AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id WHERE a.prent is NULL AND b.name IS NOT NULL 
UNION 
SELECT c.id,a.name,b.name AS subName,c.name AS subsubName,'' AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id WHERE a.prent is NULL AND c.name IS NOT NULL 
UNION 
SELECT d.id,a.name,b.name AS subName,c.name AS subsubName,d.name AS subsubsubName FROM Table1 AS a LEFT JOIN Table1 AS b ON b.prent=a.id LEFT JOIN Table1 AS c ON c.prent=b.id LEFT JOIN Table1 AS d ON d.prent=c.id WHERE a.prent is NULL AND d.name IS NOT NULL 
ORDER BY NAME,subName,subsubName,subsubsubName

Here is a fiddle.

Choose folders to be ignored during search in VS Code

This answer is outdated

If these are folders you want to ignore in a certain workspace, you can go to:

AppMenu > Preferences > Workspace Settings

Otherwise, if you want these folders to be ignored in all your workspaces, go to:

AppMenu > Preferences > User Settings

and add the following to your configuration:

//-------- Search configuration --------

// The folders to exclude when doing a full text search in the workspace.
"search.excludeFolders": [
    ".git",
    "node_modules",
    "bower_components",
    "path/to/other/folder/to/exclude"
],

The difference between workspace and user settings is explained in the customization docs

Alter table to modify default value of column

ALTER TABLE <table_name> MODIFY <column_name> DEFAULT <defult_value>

EX: ALTER TABLE AAA MODIFY ID DEFAULT AAA_SEQUENCE.nextval

Tested on Oracle Database 12c Enterprise Edition Release 12.2.0.1.0

Android Image View Pinch Zooming

Add bellow line in build.gradle:

compile 'com.commit451:PhotoView:1.2.4'

or

compile 'com.github.chrisbanes:PhotoView:1.3.0'

In Java file:

PhotoViewAttacher photoAttacher;
photoAttacher= new PhotoViewAttacher(Your_Image_View);
photoAttacher.update();

Update Jenkins from a war file

Mine is installed under /usr/share/jenkins I thought it was installed via apt-get so might want to check there as well.

Ubuntu 12.04.1

Get GPS location via a service in Android

Just complementing, I implemented this way and usually worked in my Service class

In my Service

@Override
public void onCreate()
{
    mHandler = new Handler(Looper.getMainLooper());
    mHandler.post(this);
    super.onCreate();
}

@Override
public void onDestroy() 
{
    mHandler.removeCallbacks(this);     
    super.onDestroy();
}

@Override
public void run()
{
    InciarGPSTracker();
}

Android canvas draw rectangle

Create a new class MyView, Which extends View. Override the onDraw(Canvas canvas) method to draw rectangle on Canvas.

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class MyView extends View {

 Paint paint;
 Path path;

 public MyView(Context context) {
  super(context);
  init();
 }

 public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
  init();
 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  init();
 }

 private void init(){
  paint = new Paint();
  paint.setColor(Color.BLUE);
  paint.setStrokeWidth(10);
  paint.setStyle(Paint.Style.STROKE);

 }

 @Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);

  canvas.drawRect(30, 50, 200, 350, paint);
  canvas.drawRect(100, 100, 300, 400, paint);
  //drawRect(left, top, right, bottom, paint)

 }

}

Then Move your Java activity to setContentView() using our custom View, MyView.Call this way.

    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(new MyView(this));
  }

For more details you can visit here

http://developer.android.com/reference/android/graphics/Canvas.html

regex string replace

Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:

str = str.replace(/[^-a-z0-9]+/g, "");

Also, if you need to match upper-case letters along with lower case, you should use:

str = str.replace(/[^-a-zA-Z0-9]+/g, "");

How to implement a ConfigurationSection with a ConfigurationElementCollection

An easier alternative for those who would prefer not to write all that configuration boilerplate manually...

1) Install Nerdle.AutoConfig from NuGet

2) Define your ServiceConfig type (either a concrete class or just an interface, either will do)

public interface IServiceConfiguration
{
    int Port { get; }
    ReportType ReportType { get; }
}

3) You'll need a type to hold the collection, e.g.

public interface IServiceCollectionConfiguration
{
    IEnumerable<IServiceConfiguration> Services { get; } 
}

4) Add the config section like so (note camelCase naming)

<configSections>
  <section name="serviceCollection" type="Nerdle.AutoConfig.Section, Nerdle.AutoConfig"/>
</configSections>

<serviceCollection>
  <services>
    <service port="6996" reportType="File" />
    <service port="7001" reportType="Other" />
  </services>
</serviceCollection>

5) Map with AutoConfig

var services = AutoConfig.Map<IServiceCollectionConfiguration>();

How to do error logging in CodeIgniter (PHP)

Also make sure that you have allowed codeigniter to log the type of messages you want in a config file.

i.e $config['log_threshold'] = [log_level ranges 0-4];

Where is the Java SDK folder in my computer? Ubuntu 12.04

On Ubuntu 14.04, it is in /usr/lib/jvm/default-java.

Why can't I use a list as a dict key in python?

The issue is that tuples are immutable, and lists are not. Consider the following

d = {}
li = [1,2,3]
d[li] = 5
li.append(4)

What should d[li] return? Is it the same list? How about d[[1,2,3]]? It has the same values, but is a different list?

Ultimately, there is no satisfactory answer. For example, if the only key that works is the original key, then if you have no reference to that key, you can never again access the value. With every other allowed key, you can construct a key without a reference to the original.

If both of my suggestions work, then you have very different keys that return the same value, which is more than a little surprising. If only the original contents work, then your key will quickly go bad, since lists are made to be modified.

SQL Developer is returning only the date, not the time. How do I fix this?

This will get you the hours, minutes and second. hey presto.

select
  to_char(CREATION_TIME,'RRRR') year, 
  to_char(CREATION_TIME,'MM') MONTH, 
  to_char(CREATION_TIME,'DD') DAY, 
  to_char(CREATION_TIME,'HH:MM:SS') TIME,
  sum(bytes) Bytes 
from 
  v$datafile 
group by 
  to_char(CREATION_TIME,'RRRR'), 
  to_char(CREATION_TIME,'MM'), 
  to_char(CREATION_TIME,'DD'), 
  to_char(CREATION_TIME,'HH:MM:SS') 
 ORDER BY 1, 2; 

Get first word of string

I'm surprised this method hasn't been mentioned: "Some string".split(' ').shift()


To answer the question directly:

let firstWords = []
let str = "Hello m|sss sss|mmm ss";
const codeLines = str.split("|");

for (var i = 0; i < codeLines.length; i++) {
  const first = codeLines[i].split(' ').shift()
  firstWords.push(first)
}

How to add a downloaded .box file to Vagrant?

Alternatively to add downloaded box, a json file with metadata can be created. This way some additional details can be applied. For example to import box and specifying its version create file:

{
  "name": "laravel/homestead",
  "versions": [
    {
      "version": "7.0.0",
      "providers": [
        {
          "name": "virtualbox",
          "url": "file:///path/to/box/virtualbox.box"
        }
      ]
    }
  ]
}

Then run vagrant box add command with parameter:

vagrant box add laravel/homestead /path/to/metadata.json

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

How does OAuth 2 protect against things like replay attacks using the Security Token?

Here is perhaps the simplest explanation of how OAuth2 works for all 4 grant types, i.e., 4 different flows where the app can acquire the access token.

Similarity

All grant type flows have 2 parts:

  • Get access token
  • Use access token

The 2nd part 'use access token' is the same for all flows

Difference

The 1st part of the flow 'get access token' for each grant type varies.

However, in general the 'get access token' part can be summarized as consisting 5 steps:

  1. Pre-register your app (client) with OAuth provider, e.g., Twitter, etc. to get client id/secret
  2. Create a social login button with client id & required scopes/permissions on your page so when clicked user gets redirected to OAuth provider to be authenticated
  3. OAuth provider request user to grant permission to your app (client)
  4. OAuth provider issues code
  5. App (client) acquires access token

Here is a side-by-side diagram comparing how each grant type flow is different based on the 5 steps.

This diagram is from https://blog.oauth.io/introduction-oauth2-flow-diagrams/

enter image description here

Each have different levels of implementation difficulty, security, and uses cases. Depending on your needs and situation, you will have to use one of them. Which to use?

Client Credential: If your app is only serving a single user

Resource Owner Password Crendential: This should be used only as last resort as the user has to hand over his credentials to the app, which means the app can do everything the user can

Authorization Code: The best way to get user authorization

Implicit: If you app is mobile or single-page app

There is more explanation of the choice here: https://blog.oauth.io/choose-oauth2-flow-grant-types-for-app/

Do the parentheses after the type name make a difference with new?

new Thing(); is explicit that you want a constructor called whereas new Thing; is taken to imply you don't mind if the constructor isn't called.

If used on a struct/class with a user-defined constructor, there is no difference. If called on a trivial struct/class (e.g. struct Thing { int i; };) then new Thing; is like malloc(sizeof(Thing)); whereas new Thing(); is like calloc(sizeof(Thing)); - it gets zero initialized.

The gotcha lies in-between:

struct Thingy {
  ~Thingy(); // No-longer a trivial class
  virtual WaxOn();
  int i;
};

The behavior of new Thingy; vs new Thingy(); in this case changed between C++98 and C++2003. See Michael Burr's explanation for how and why.

405 method not allowed Web API

Old question but none of the answers worked for me.

This article solved my problem by adding the following lines to web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>

Writing a VLOOKUP function in vba

Have you tried:

Dim result As String 
Dim sheet As Worksheet 
Set sheet = ActiveWorkbook.Sheets("Data") 
result = Application.WorksheetFunction.VLookup(sheet.Range("AN2"), sheet.Range("AA9:AF20"), 5, False)

jQuery event to trigger action when a div is made visible

There is no native event you can hook into for this however you can trigger an event from your script after you have made the div visible using the .trigger function

e.g

//declare event to run when div is visible
function isVisible(){
   //do something

}

//hookup the event
$('#someDivId').bind('isVisible', isVisible);

//show div and trigger custom event in callback when div is visible
$('#someDivId').show('slow', function(){
    $(this).trigger('isVisible');
});

Getting error "No such module" using Xcode, but the framework is there

I win the award for dumbest cause of the "No such module" error. In my case I build the included framework by hand, and copy it into my project directory. My framework search paths were set correctly, and the framework was added to the project correctly.

When I archived the framework I was building, I used "Show in Finder" to take me to the release folder in derived data. But I didn't noticed that the folder contains only an alias to the framework, not the framework itself. The original framework remained in my derived data directory, so later when I cleared derived data the framework was deleted, but my project didn't know that.

Re-archiving the framework, following the alias to the actual framework, and copying that to my project directory worked.

Get variable from PHP to JavaScript

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>

'this' is undefined in JavaScript class methods

In ES2015 a.k.a ES6, class is a syntactic sugar for functions.

If you want to force to set a context for this you can use bind() method. As @chetan pointed, on invocation you can set the context as well! Check the example below:

class Form extends React.Component {
constructor() {
    super();
  }
  handleChange(e) {
    switch (e.target.id) {
      case 'owner':
        this.setState({owner: e.target.value});
        break;
      default:
    }
  }
  render() {
    return (
      <form onSubmit={this.handleNewCodeBlock}>
        <p>Owner:</p> <input onChange={this.handleChange.bind(this)} />
      </form>
    );
  }
}

Here we forced the context inside handleChange() to Form.

How do I find Waldo with Mathematica?

I don't know Mathematica . . . too bad. But I like the answer above, for the most part.

Still there is a major flaw in relying on the stripes alone to glean the answer (I personally don't have a problem with one manual adjustment). There is an example (listed by Brett Champion, here) presented which shows that they, at times, break up the shirt pattern. So then it becomes a more complex pattern.

I would try an approach of shape id and colors, along with spacial relations. Much like face recognition, you could look for geometric patterns at certain ratios from each other. The caveat is that usually one or more of those shapes is occluded.

Get a white balance on the image, and red a red balance from the image. I believe Waldo is always the same value/hue, but the image may be from a scan, or a bad copy. Then always refer to an array of the colors that Waldo actually is: red, white, dark brown, blue, peach, {shoe color}.

There is a shirt pattern, and also the pants, glasses, hair, face, shoes and hat that define Waldo. Also, relative to other people in the image, Waldo is on the skinny side.

So, find random people to obtain an the height of people in this pic. Measure the average height of a bunch of things at random points in the image (a simple outline will produce quite a few individual people). If each thing is not within some standard deviation from each other, they are ignored for now. Compare the average of heights to the image's height. If the ratio is too great (e.g., 1:2, 1:4, or similarly close), then try again. Run it 10(?) of times to make sure that the samples are all pretty close together, excluding any average that is outside some standard deviation. Possible in Mathematica?

This is your Waldo size. Walso is skinny, so you are looking for something 5:1 or 6:1 (or whatever) ht:wd. However, this is not sufficient. If Waldo is partially hidden, the height could change. So, you are looking for a block of red-white that ~2:1. But there has to be more indicators.

  1. Waldo has glasses. Search for two circles 0.5:1 above the red-white.
  2. Blue pants. Any amount of blue at the same width within any distance between the end of the red-white and the distance to his feet. Note that he wears his shirt short, so the feet are not too close.
  3. The hat. Red-white any distance up to twice the top of his head. Note that it must have dark hair below, and probably glasses.
  4. Long sleeves. red-white at some angle from the main red-white.
  5. Dark hair.
  6. Shoe color. I don't know the color.

Any of those could apply. These are also negative checks against similar people in the pic -- e.g., #2 negates wearing a red-white apron (too close to shoes), #5 eliminates light colored hair. Also, shape is only one indicator for each of these tests . . . color alone within the specified distance can give good results.

This will narrow down the areas to process.

Storing these results will produce a set of areas that should have Waldo in it. Exclude all other areas (e.g., for each area, select a circle twice as big as the average person size), and then run the process that @Heike laid out with removing all but red, and so on.

Any thoughts on how to code this?


Edit:

Thoughts on how to code this . . . exclude all areas but Waldo red, skeletonize the red areas, and prune them down to a single point. Do the same for Waldo hair brown, Waldo pants blue, Waldo shoe color. For Waldo skin color, exclude, then find the outline.

Next, exclude non-red, dilate (a lot) all the red areas, then skeletonize and prune. This part will give a list of possible Waldo center points. This will be the marker to compare all other Waldo color sections to.

From here, using the skeletonized red areas (not the dilated ones), count the lines in each area. If there is the correct number (four, right?), this is certainly a possible area. If not, I guess just exclude it (as being a Waldo center . . . it may still be his hat).

Then check if there is a face shape above, a hair point above, pants point below, shoe points below, and so on.

No code yet -- still reading the docs.

Why do python lists have pop() but not push()

Because it appends; it doesn't push. "Appending" adds to the end of a list, "pushing" adds to the front.

Think of a queue vs. a stack.

http://docs.python.org/tutorial/datastructures.html

Edit: To reword my second sentence more exactly, "Appending" very clearly implies adding something to the end of a list, regardless of the underlying implementation. Where a new element gets added when it's "pushed" is less clear. Pushing onto a stack is putting something on "top," but where it actually goes in the underlying data structure completely depends on implementation. On the other hand, pushing onto a queue implies adding it to the end.

Remove Fragment Page from ViewPager in Android

add or remove fragment in viewpager dynamically.
Call setupViewPager(viewPager) on activity start. To load different fragment call setupViewPagerCustom(viewPager). e.g. on button click call: setupViewPagerCustom(viewPager);

    private void setupViewPager(ViewPager viewPager)
{
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new fragmnet1(), "HOME");
    adapter.addFrag(new fragmnet2(), "SERVICES");

    viewPager.setAdapter(adapter);
}

private void setupViewPagerCustom(ViewPager viewPager)
{

    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());

    adapter.addFrag(new fragmnet3(), "Contact us");
    adapter.addFrag(new fragmnet4(), "ABOUT US");


    viewPager.setAdapter(adapter);
}

//Viewpageradapter, handles the views

static class ViewPagerAdapter extends FragmentStatePagerAdapter
{
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager){
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    @Override
    public int getItemPosition(Object object){
        return PagerAdapter.POSITION_NONE;
    }

    public void addFrag(Fragment fragment, String title){
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position){
        return mFragmentTitleList.get(position);
    }
}

How to allow only one radio button to be checked?

Give them the same name, and it will work. By definition Radio buttons will only have one choice, while check boxes can have many.

<input type="radio" name="Radio1" />

Jquery find nearest matching element

You could try:

$(this).closest(".column").prev().find(".inputQty").val();