text:
Q: How to limit characters per message and make anti-spam? i have this shouwbox script.
I would like to know how to limit the characters for each message like 70 characters.
And i would also like to know how to do so you have to wait 3 seconds between each message you post.
Here is my script.
Index.html

  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>jQuery</title>

<form id="daddy-shoutbox-form" action="demos/jquery-shoutbox/daddy-shoutbox.php?action=add" method="post">

    Name:
    <input type="text" name="nickname" />

  Message:
  <input type="text" name="message" />

    <input type="submit" value="Submit" />

  </form>

daddy-shoutbox.php
<?php
  function replace(&$item, $key) {
    $item = str_replace('|', '-', $item);
  }

  if (!function_exists('file_put_contents')) {
        function file_put_contents($fileName, $data) {
            if (is_array($data)) {
                $data = join('', $data);
            }
            $res = @fopen($fileName, 'w+b');
            if ($res) {
                $write = @fwrite($res, $data);
                if($write === false) {
                    return false;
                } else {
                    return $write;
                }
            }
        }
    }

  //file_put_contents('debug.txt', print_r($_GET, true));
  switch($_GET['action']) {
    case 'add':
      array_walk($_POST, 'replace');
      $arr = file('messages.txt');

      if(count($arr) > 10)
        array_shift($arr);

      $_POST['nickname'] = htmlentities($_POST['nickname']);
      $_POST['message'] = htmlentities($_POST['message']);
      $time = time();
      $arr[] = $time.'|'.$_POST['nickname'].'|'.$_POST['message'].'|'.$_SERVER['REMOTE_ADDR']."\n";
      file_put_contents('messages.txt', implode('', $arr));

      $data['response'] = 'Good work';
      $data['nickname'] = $_POST['nickname'];
      $data['message'] = $_POST['message'];
      $data['time'] = $time;
    break;

    case 'view':
      $data = array();
      $arr = file('messages.txt');
      if(!$_GET['time'])
        $_GET['time'] = 0;
      foreach($arr as $row) {
        $aTemp = null;
        list($aTemp['time'], $aTemp['nickname'], $aTemp['message']) = explode('|', $row);
        if($aTemp['message'] AND $aTemp['time'] > $_GET['time'])
          $data[] = $aTemp;
      }
      //file_put_contents('debug.txt', print_r($data, true));
    break;
  }

  require_once('JSON.php');
  $json = new Services_JSON();
  $out = $json->encode($data);
  print $out;
?>

JSON.php
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * Converts to and from JSON format.
 *
 * JSON (JavaScript Object Notation) is a lightweight data-interchange
 * format. It is easy for humans to read and write. It is easy for machines
 * to parse and generate. It is based on a subset of the JavaScript
 * Programming Language, Standard ECMA-262 3rd Edition - December 1999.
 * This feature can also be found in  Python. JSON is a text format that is
 * completely language independent but uses conventions that are familiar
 * to programmers of the C-family of languages, including C, C++, C#, Java,
 * JavaScript, Perl, TCL, and many others. These properties make JSON an
 * ideal data-interchange language.
 *
 * This package provides a simple encoder and decoder for JSON notation. It
 * is intended for use with client-side Javascript applications that make
 * use of HTTPRequest to perform server communication functions - data can
 * be encoded into JSON notation for use in a client-side javascript, or
 * decoded from incoming Javascript requests. JSON format is native to
 * Javascript, and can be directly eval()'ed with no further parsing
 * overhead
 *
 * All strings should be in ASCII or UTF-8 format!
 *
 * LICENSE: Redistribution and use in source and binary forms, with or
 * without modification, are permitted provided that the following
 * conditions are met: Redistributions of source code must retain the
 * above copyright notice, this list of conditions and the following
 * disclaimer. Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following disclaimer
 * in the documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
 * NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
 * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 *
 * @category
 * @package     Services_JSON
 * @author      Michal Migurski <mike-json@teczno.com>
 * @author      Matt Knapp <mdknapp[at]gmail[dot]com>
 * @author      Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
 * @copyright   2005 Michal Migurski
 * @version     CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @link        http://pear.php.net/pepr/pepr-proposal-show.php?id=198
 */

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_SLICE',   1);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_STR',  2);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_ARR',  3);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_OBJ',  4);

/**
 * Marker constant for Services_JSON::decode(), used to flag stack state
 */
define('SERVICES_JSON_IN_CMT', 5);

/**
 * Behavior switch for Services_JSON::decode()
 */
define('SERVICES_JSON_LOOSE_TYPE', 16);

/**
 * Behavior switch for Services_JSON::decode()
 */
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);

/**
 * Converts to and from JSON format.
 *
 * Brief example of use:
 *
 *
 * // create a new instance of Services_JSON
 * $json = new Services_JSON();
 *
 * // convert a complexe value to JSON notation, and send it to the browser
 * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
 * $output = $json->encode($value);
 *
 * print($output);
 * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
 *
 * // accept incoming POST data, assumed to be in JSON notation
 * $input = file_get_contents('php://input', 1000000);
 * $value = $json->decode($input);
 *
 */
class Services_JSON
{
   /**
    * constructs a new JSON instance
    *
    * @param    int     $use    object behavior flags; combine with boolean-OR
    *
    *                           possible values:
    *                           - SERVICES_JSON_LOOSE_TYPE:  loose typing.
    *                                   "{...}" syntax creates associative arrays
    *                                   instead of objects in decode().
    *                           - SERVICES_JSON_SUPPRESS_ERRORS:  error suppression.
    *                                   Values which can't be encoded (e.g. resources)
    *                                   appear as NULL instead of throwing errors.
    *                                   By default, a deeply-nested resource will
    *                                   bubble up with an error, so all return values
    *                                   from encode() should be checked with isError()
    */
    function Services_JSON($use = 0)
    {
        $this->use = $use;
    }

   /**
    * convert a string from one UTF-16 char to one UTF-8 char
    *
    * Normally should be handled by mb_convert_encoding, but
    * provides a slower PHP-only method for installations
    * that lack the multibye string extension.
    *
    * @param    string  $utf16  UTF-16 character
    * @return   string  UTF-8 character
    * @access   private
    */
    function utf162utf8($utf16)
    {
        // oh please oh please oh please oh please oh please
        if(function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
        }

        $bytes = (ord($utf16{0}) << 8) | ord($utf16{1});

        switch(true) {
            case ((0x7F & $bytes) == $bytes):
                // this case should never be reached, because we are in ASCII range
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0x7F & $bytes);

            case (0x07FF & $bytes) == $bytes:
                // return a 2-byte UTF-8 character
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0xC0 | (($bytes >> 6) & 0x1F))
                     . chr(0x80 | ($bytes & 0x3F));

            case (0xFFFF & $bytes) == $bytes:
                // return a 3-byte UTF-8 character
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0xE0 | (($bytes >> 12) & 0x0F))
                     . chr(0x80 | (($bytes >> 6) & 0x3F))
                     . chr(0x80 | ($bytes & 0x3F));
        }

        // ignoring UTF-32 for now, sorry
        return '';
    }

   /**
    * convert a string from one UTF-8 char to one UTF-16 char
    *
    * Normally should be handled by mb_convert_encoding, but
    * provides a slower PHP-only method for installations
    * that lack the multibye string extension.
    *
    * @param    string  $utf8   UTF-8 character
    * @return   string  UTF-16 character
    * @access   private
    */
    function utf82utf16($utf8)
    {
        // oh please oh please oh please oh please oh please
        if(function_exists('mb_convert_encoding')) {
            return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
        }

        switch(strlen($utf8)) {
            case 1:
                // this case should never be reached, because we are in ASCII range
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return $utf8;

            case 2:
                // return a UTF-16 character from a 2-byte UTF-8 char
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr(0x07 & (ord($utf8{0}) >> 2))
                     . chr((0xC0 & (ord($utf8{0}) << 6))
                         | (0x3F & ord($utf8{1})));

            case 3:
                // return a UTF-16 character from a 3-byte UTF-8 char
                // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                return chr((0xF0 & (ord($utf8{0}) << 4))
                         | (0x0F & (ord($utf8{1}) >> 2)))
                     . chr((0xC0 & (ord($utf8{1}) << 6))
                         | (0x7F & ord($utf8{2})));
        }

        // ignoring UTF-32 for now, sorry
        return '';
    }

   /**
    * encodes an arbitrary variable into JSON format
    *
    * @param    mixed   $var    any number, boolean, string, array, or object to be encoded.
    *                           see argument 1 to Services_JSON() above for array-parsing behavior.
    *                           if var is a strng, note that encode() always expects it
    *                           to be in ASCII or UTF-8 format!
    *
    * @return   mixed   JSON string representation of input var or an error if a problem occurs
    * @access   public
    */
    function encode($var)
    {
        switch (gettype($var)) {
            case 'boolean':
                return $var ? 'true' : 'false';

            case 'NULL':
                return 'null';

            case 'integer':
                return (int) $var;

            case 'double':
            case 'float':
                return (float) $var;

            case 'string':
                // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
                $ascii = '';
                $strlen_var = strlen($var);

               /*
                * Iterate over every character in the string,
                * escaping with a slash or encoding to UTF-8 where necessary
                */
                for ($c = 0; $c < $strlen_var; ++$c) {

                    $ord_var_c = ord($var{$c});

                    switch (true) {
                        case $ord_var_c == 0x08:
                            $ascii .= '\b';
                            break;
                        case $ord_var_c == 0x09:
                            $ascii .= '\t';
                            break;
                        case $ord_var_c == 0x0A:
                            $ascii .= '\n';
                            break;
                        case $ord_var_c == 0x0C:
                            $ascii .= '\f';
                            break;
                        case $ord_var_c == 0x0D:
                            $ascii .= '\r';
                            break;

                        case $ord_var_c == 0x22:
                        case $ord_var_c == 0x2F:
                        case $ord_var_c == 0x5C:
                            // double quote, slash, slosh
                            $ascii .= '\\'.$var{$c};
                            break;

                        case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
                            // characters U-00000000 - U-0000007F (same as ASCII)
                            $ascii .= $var{$c};
                            break;

                        case (($ord_var_c & 0xE0) == 0xC0):
                            // characters U-00000080 - U-000007FF, mask 110XXXXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c, ord($var{$c + 1}));
                            $c += 1;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xF0) == 0xE0):
                            // characters U-00000800 - U-0000FFFF, mask 1110XXXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}));
                            $c += 2;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xF8) == 0xF0):
                            // characters U-00010000 - U-001FFFFF, mask 11110XXX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}),
                                         ord($var{$c + 3}));
                            $c += 3;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xFC) == 0xF8):
                            // characters U-00200000 - U-03FFFFFF, mask 111110XX
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}),
                                         ord($var{$c + 3}),
                                         ord($var{$c + 4}));
                            $c += 4;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;

                        case (($ord_var_c & 0xFE) == 0xFC):
                            // characters U-04000000 - U-7FFFFFFF, mask 1111110X
                            // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
                            $char = pack('C*', $ord_var_c,
                                         ord($var{$c + 1}),
                                         ord($var{$c + 2}),
                                         ord($var{$c + 3}),
                                         ord($var{$c + 4}),
                                         ord($var{$c + 5}));
                            $c += 5;
                            $utf16 = $this->utf82utf16($char);
                            $ascii .= sprintf('\u%04s', bin2hex($utf16));
                            break;
                    }
                }

                return '"'.$ascii.'"';

            case 'array':
               /*
                * As per JSON spec if any array key is not an integer
                * we must treat the the whole array as an object. We
                * also try to catch a sparsely populated associative
                * array with numeric keys here because some JS engines
                * will create an array with empty indexes up to
                * max_index which can cause memory issues and because
                * the keys, which may be relevant, will be remapped
                * otherwise.
                *
                * As per the ECMA and JSON specification an object may
                * have any string as a property. Unfortunately due to
                * a hole in the ECMA specification if the key is a
                * ECMA reserved word or starts with a digit the
                * parameter is only accessible using ECMAScript's
                * bracket notation.
                */

                // treat as a JSON object
                if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
                    $properties = array_map(array($this, 'name_value'),
                                            array_keys($var),
                                            array_values($var));

                    foreach($properties as $property) {
                        if(Services_JSON::isError($property)) {
                            return $property;
                        }
                    }

                    return '{' . join(',', $properties) . '}';
                }

                // treat it like a regular array
                $elements = array_map(array($this, 'encode'), $var);

                foreach($elements as $element) {
                    if(Services_JSON::isError($element)) {
                        return $element;
                    }
                }

                return '[' . join(',', $elements) . ']';

            case 'object':
                $vars = get_object_vars($var);

                $properties = array_map(array($this, 'name_value'),
                                        array_keys($vars),
                                        array_values($vars));

                foreach($properties as $property) {
                    if(Services_JSON::isError($property)) {
                        return $property;
                    }
                }

                return '{' . join(',', $properties) . '}';

            default:
                return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
                    ? 'null'
                    : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
        }
    }

   /**
    * array-walking function for use in generating JSON-formatted name-value pairs
    *
    * @param    string  $name   name of key to use
    * @param    mixed   $value  reference to an array element to be encoded
    *
    * @return   string  JSON-formatted name-value pair, like '"name":value'
    * @access   private
    */
    function name_value($name, $value)
    {
        $encoded_value = $this->encode($value);

        if(Services_JSON::isError($encoded_value)) {
            return $encoded_value;
        }

        return $this->encode(strval($name)) . ':' . $encoded_value;
    }

   /**
    * reduce a string by removing leading and trailing comments and whitespace
    *
    * @param    $str    string      string value to strip of comments and whitespace
    *
    * @return   string  string value stripped of comments and whitespace
    * @access   private
    */
    function reduce_string($str)
    {
        $str = preg_replace(array(

                // eliminate single line comments in '// ...' form
                '#^\s*//(.+)$#m',

                // eliminate multi-line comments in '/* ... */' form, at start of string
                '#^\s*/\*(.+)\*/#Us',

                // eliminate multi-line comments in '/* ... */' form, at end of string
                '#/\*(.+)\*/\s*$#Us'

            ), '', $str);

        // eliminate extraneous space
        return trim($str);
    }

   /**
    * decodes a JSON string into appropriate variable
    *
    * @param    string  $str    JSON-formatted string
    *
    * @return   mixed   number, boolean, string, array, or object
    *                   corresponding to given JSON input string.
    *                   See argument 1 to Services_JSON() above for object-output behavior.
    *                   Note that decode() always returns strings
    *                   in ASCII or UTF-8 format!
    * @access   public
    */
    function decode($str)
    {
        $str = $this->reduce_string($str);

        switch (strtolower($str)) {
            case 'true':
                return true;

            case 'false':
                return false;

            case 'null':
                return null;

            default:
                $m = array();

                if (is_numeric($str)) {
                    // Lookie-loo, it's a number

                    // This would work on its own, but I'm trying to be
                    // good about returning integers where appropriate:
                    // return (float)$str;

                    // Return float or int, as appropriate
                    return ((float)$str == (integer)$str)
                        ? (integer)$str
                        : (float)$str;

                } elseif (pre

A: You can enforce these limitations on the client-side for speed purposes, but they need to be applied on the server side.  Otherwise, someone could download your form, remove the limitations, and use it without limitations.  You've given us the client-side code, so there's not much we can do to help you with what you've given us.
If your site doesn't impliment some sort of login system, it probably should.  This is the best way to identify who is doing what (so if they are doing something like spamming, you can make them stop).

A: To limit the number of characters on the client side I believe <input type="text" maxlength="70"> should work.
You will need to enforce the limit server side using substr(). Otherwise it would be terribly easy to circumvent.
eg.
$message = substr($_REQUEST['message'], 0, 70);
Seeing as 3 seconds isn't a terribly long time, you could make it so the page takes 3 seconds to load. Not an elegant solution and easily bypassed by ANY hacker but it's a start. put this at the beginning of your document:
<?php
  sleep(3);
?>


text:
Q: Finding regression equation from support vector regression I'm currently using Python's scikit-learn to create a support vector regression model, and I was wondering how one would go about finding the explicit regression equation of our target variable in terms of our predictors. It doesn't have to be simple or pretty, but is there a method Python has to output this (for a polynomial kernel, specifically)? I am fairly new to using SVR, and I am not certain of what to expect a regression equation to look like used in the prediction from a test observation after the regression is fit.
I've already fit an SVR model that predicts with a performance I'm happy with, and I've used GridSearchCV to tune hyper-parameters. However, I need an explicit form of my target variable in terms of the predictors for an independent optimization, and don't know how to find this equation.
from sklearn.svm import SVR
svr = SVR(kernel = 'poly', C = best_params['C'], epsilon = best_params['epsilon'], gamma = best_params['gamma'], coef0 = 0.1, shrinking = True, tol = 0.001, cache_size = 200, verbose = False, max_iter = -1)
svr.fit(x,y)

Where x is my matrix of observations, y is my vector of target values from the observations, and best_params is the output (optimal hyperparameters) found by GridSearchCV.
Does Python have any method for outputting the resulting equation of the SVR model used in predicting future target values from a set of predictors? Or is there a straightforward way of using values found by SVR to create an equation myself if I specify the kernel to be of polynomial type?
Thank you!

A: If you use a linear kernel, then you can output your coefficient.
For example
from sklearn.svm import SVR
import numpy as np
n_samples, n_features = 1000, 5
rng = np.random.RandomState(0)
coef = [1,2,3,4,5]
X = rng.randn(n_samples, n_features)
y = coef * X
y = y.sum(axis = 1) + rng.randn(n_samples)
clf = SVR(kernel = 'linear', gamma='scale', C=1.0, epsilon=0.2)
clf.fit(X, y)
clf.coef_
array([[0.97626634, 2.00013793, 2.96205576, 4.00651352, 4.95923782]])

redpajama_set_name: RedPajamaStackExchange


text:
Q: NodeJS: Array automatically gets converted into object? I am running into strange problem where a simple array of JavaScript somehow automatically gets converted into object. Here is the code I am using:
function readData(callback) {
  fs.readFile(__dirname + '/data/data.xml', function (err, data) {
      parser.parseString(data, function (err, result) {
          let chapterList = [];

          console.log(typeof chapterList); // strangley this outputs "object"

          for (let i = 0; i <= 113; i++) {
              chapterList.push(result[i].name);
          }

          callback();
      });
  });
}

module.exports = { chapters };

As can be seen, on first line I define chapterList and on second line it tells me it is type of object.
FYI, this is nodejs script which I run like node index.js


text:
Q: Recursive function to get numbered tree of categories in php I have a big problem with a nested array, that contains category tree:
Array(
[1] => Array
    (
        [parent_id] => 0
        [category_id] => 1
        [name] => Auto-moto
        [path] => Auto-moto
        [children] => Array
            (

                [4] => Array
                    (
                        [parent_id] => 1
                        [category_id] => 4
                        [name] => Autodiely
                        [path] => Auto-moto/Autodiely
                        [children] => Array
                            (
                                [5] => Array
                                    (
                                        [parent_id] => 4
                                        [category_id] => 5
                                        [name] => Kabínové filtre pre automobily
                                        [path] => Auto-moto/Autodiely/Kabínové filtre pre automobily
                                        [children] =>
                                    )

I have a recursive function to show it in html ul > li list but I want to make list looks like this:
1.Auto-moto
1.1.Autodiely
1.1.1.Kabínové filtre pre automobily
1.1.2. xxxx
1.2.YYY
1.3.AAA
2.New
2.1.Sub....

Is that possible? Many thanks for help.

A: Use recursion. My approach, go by whole array all levels recursively, and for for each level add corresponding code into 'level' key.
This is an example for you:
$arr = array(
    'a' => array(

        'name' => 'a',
        'children' => array(

            'aa' => array(
                'name' => 'aa',
                'children' => array(

                    'aaa' => array(
                        'name' => 'aaa',
                    ),
                ),
            ),

            'ab' => array(
                'name' => 'ab',
                'children' => array(

                    'aba' => array(
                        'name' => 'aba',
                        'children' => array(

                            'abaa' => array(
                                'name' => 'abaa',
                            ),

                        ),
                    ),
                    'abb' => array(
                        'name' => 'abb',
                    ),
                ),
            ),
        )
     ),
    'b' => array(
        'name' => 'b',
        'children' => array(
            'ba' => array(
                'name' => 'ba',
            ),
            'bb' => array(
                'name' => 'bb',
            ),
        )
    ),
);

/**
 * To target array, for each level adds new field named 'level', with level deep number
 * @param type $array target array
 * @param type $level nested level number
 */
function add_levels( &$array, $level ){
    $i = 0;
    foreach ( $array as $key => &$value ) {
        $level_name = $level.++$i;
        $value[ 'level' ] = $level_name;

        if( array_key_exists( 'children', $value ) and is_array( $value[ 'children' ] )){
            add_levels( $value[ 'children' ], $level_name.'.' );
        }

    }
}

/**
 * Prints out array in required form
 * @param type $array
 */
function draw_ordered( $array ){
    foreach ( $array as $key => &$value ) {
        echo( $value[ 'level' ].'.'. $value[ 'name' ].'<br />' );
        if( array_key_exists( 'children', $value ) and is_array( $value[ 'children' ] )){
            draw_ordered( $value[ 'children' ] );
        }
    }
}

add_levels( $arr );
//print_r($arr);

draw_ordered( $arr );
die();


text:
Q: Is full width carousel possible? I would like to make the Jssor Carousel full width, without resizing height at all when the window resizes. So on a wide screen, it would show more slides and on a narrow screen it will show less, without ever changing height. I don't want the slider to resize, I just want it to cut off, if that makes sense.
So far I've got it working as I'd like in Firefox, Chrome, Safari and Opera. If I'm not explaining it very well, I apologize, you can see an example of how I'd like it to work here: http://jessetessman.com/110/slider.php in Firefox, Chrome, Safari or Opera. Note, when you resize the window you have to refresh to resize the slider.
My problem is, it doesn't work in IE. It just has a width of 100px in IE and I have no idea how to get it working.
I appreciate any help you can give. I realize the way I have it now is probably not the best way to go about accomplishing this, but I am not very good with javascript so I just messed with it until I got to this point. Any suggestions about better ways to do this are certainly welcome.
Thank you in advance for the help.

A: Please add one line $("#news-slider").width("100%");
        var jssor_slider1 = new $JssorSlider$("news-slider", options);
        $("#news-slider").width("100%");

Forgot to change following css, make the width to greater than screen width then.
#news-slider {
    left: 0px; top: 0px; width: 2400px; height: 350px; overflow: hidden; position: relative;
}
#news-slider .slides {
    left: 0px; top: 0px; width: 2400px; height: 350px; overflow: hidden; z-index: 0;
}


text:
Q: Getting Negative Topographic Wetness Index (TWI) values in SAGA GIS? I am getting negative topographic index wetness values in SAGA GIS - anyone else every get this?
Not all negative values, but the minimum of the TWI range is negative for some steep watersheds we are examining.  Ranges get as negative as (approx.) -1.5.
For this to happen, the value resulting from (specific catchment area / tan slope ) must be less than 1, since the ln of values between 0 than 1 = a negative value.
It is a very steep watershed, so we have slopes that approach 1.57 radians (almost 90 degrees).  In fact, the maximum slope for the watershed in question is 1.509 radians (or 86.459 degrees).  And the minimum Specific catchment Area value is 2.2175m.  So we can see that if we calculate ln(2.2175/tan 1.509), which further simplified is ln(2.2175/16.16159) and then ln(0.137208), we get a negative value (-1.8 or something) that shows the theoretical absolute minimum TI value for our watershed.  Its theoretical cause the steepest slope and smallest SCA don't combine, but some set of close values do, to get a real minimum of approx. -1.5.
To get more specific, in our steep watershed, the DEM has a resolution of 8.86 m and the Total Catchment Area minimum calculated by SAGA is this cell size squared (78.4996 sq m).  Which makes sense, as there are cells in the catchment that don't accept flow from any other cells and therefore have a Total Catchment Area equal to the cell area.  Now, for these cells, at localized peaks in the watershed (or even maximum peaks at the edges), the Specific Catchment Area should be equal to the Total Catchment Area for these cells divided by the contour width of downslope flow paths.  These peaks flow to all neighboring cells, this 78.4996 is divided by (as currently coded in SAGA) 35.4 (which is 8 * 0.5 * 8.86).  This gives the Specific Catchment Area minimum of 2.2175m.
My main problem with this negative TI result, is that I don't think it is possible, or at least have never really seen negative TI values talked about/graphed in a paper.
Any thoughts form anyone?

A: This is a good question, and one that I tend to get asked from time to time. First, as you've pointed out, the equation for TWI = ln(a / tan(B)), where a is the 'specific' catchment area (i.e. the upslope inflowing area normalized for a measure of contour length) and B is the slope gradient, in radians, at the grid cell. As you correctly pointed out TWI will only take on negative values where a < tan(B) since the natural log of any value less than 1 will be negative. So, negative TWI values should be surprising. Remember, TWI is just an index. All it is telling you is that two grid cells that have similar TWI values will likely become saturated at the surface under similar basin moisture conditions given their combined contributing areas and local slope gradients. It's also giving you a relative ranking of when grid cells will become saturated, such that cells with higher values are likely to become saturated before cells with lower values. So, those negative TWI values are really among the driest locations in the basin. The real genius of Beven and Kirkby's TWI is that if you hook this up to a simple hydrological model (e.g. TOPMODEL), which then keeps track of the basin's current moisture conditions, you can relate the current extent of the surface saturated area to a threshold TWI value. All grid cells with a TWI greater than this threshold value define the current surface saturated area which will be predicted to experience overland flow and possibly return flow.
For a particular DEM, you can actually figure out what conditions you'll likely find these negative TWI values. For a DEM of resolution g, the lowest possible a value will be equal to (or approximately equal to depending on how the TWI implementation determines contour length) g (i.e. g^2 / g). We can call this minimum value amin. Grid cells with this a value occur where there are no inflowing cells, which will only really happen along topographic ridge lines. Interestingly, these are the exact places that are likely to experience high local slope gradients as well. So, now, you can calculate the slope threshold at which point TWI starts to take on negative values as: Bthresh = atan(amin). Since you have a DEM resolution of 8.86 m, then any grid cells with this a value that have a slope greater than 83.56 degrees will take on negative TWI values. You can see why many people believe that TWI can't be negative; that is a fairly high slope and the conditions under which you would get a negative TWI are somewhat rare. You're lucky then to be working in such an interesting environment. (NOTE: TWI was never intended to be used across the very wide range of landscapes that it is commonly applied to today.)

In the TWI raster above, I've highlighted each of the grid cells with negative TWI. As you can see, it isn't all that common in the grid. In fact, in this case, it is completely confined to grid cells associated with off-terrain objects (buildings in this LiDAR DEM) because of their very steep sides and small a values. This particular case isn't very realistic from a process point of view (what does the wetness index of a building mean?), but nonetheless, it highlights my point well.
In his comment, Jeffery Evans raises the possibility that the reason for negative values is because of the way that zero slope values are handled. In fact, these flat areas will have very large TWI values rather than negative values. Flat areas, which also tend to be very low-lying valley bottom positions, are among the wettest and first to saturate locations in a basin. Now obviously if B is zero, tan(B) is also zero and you get a division by zero, which of course is infinity. This is like saying, if you have a perfectly flat location, it's always going to be saturated since it cannot shed water to a downslope position. Again, remember that TWI is meant to be a relative index of wetness based on topography, we're not saying that a cell with a TWI value of 2 is twice as saturated as a cell with a TWI of 1. However, obviously we can't have a grid with infinity values, and depending on the quality and source data of your DEM, zero gradients are quite likely. So it's true that developers of TWI tools need to have special rules in place to handle grid cells with zero local gradient. Generally you'll simply substitute in a 'really high value' to let the user know this site is quite wet. The problem with this approach is that, just as you've asked why you get negative TWI values, users will commonly say, 'why am I getting TWI values as high as 9999?'. So an alternative is simply to stick a NoData value in these cells.
I hope that helps to answer you questions.


text:
Q: Android Studio Install vs. Google Play Install (App Size on Device) I seem to be having a problem with limiting the size of my installed Android Application. During development I used Android Studio to deploy my application to my testing device. The app took a total of 2.32 MB in storage when freshly installed.
The problem in size came up when I published my application to the Google Play Store for alpha testing. I uninstalled the same app I had loaded with Android Studio, then downloaded the one I listed on the Google Play Store. The funny thing is that the same app now takes up 4.11 MB in storage.
How did this occur? The testing environment is the same, therefore what additional libraries or information would need to be added to the app causing it to take up the extra 1.79 MB?
TL;DR

*

*App installed on testing device via Android Studio: 2.32 MB in storage

*Same app installed on the same testing device through the Google Play Store: 4.11 MB in storage

Why is there such a significant increase in the size of my application? No other variables aside from installation source have changed.

A: That's because compiling & installing app into one target device and all devices is different.
When you click the run button, you are targeting only single device.
When deploying a signed release apk, you are targeting all screen densities, intel and arm processors. It includes extra files. It makes your apk file bigger.

A: Check out this existing answer on SO. Android release apk bigger than debug
The answers point out how a debug version only includes resources for the connected devices screen density.  For production all images/res are included.  Also, you should be able to further reduce size of your apk by using pro guard if you aren't already.


text:
Q: Spring data for neo4j 2.3 embedded mode I am planning to use Neo4j 2.3 with Spring Data 3.x version with Neo4j in embedded mode. Is Spring data 3.x compatible with Neo4j 2.3?
Ref: http://neo4j.com/blog/spring-data-neo4j-summer-update/
But this page was updated last on august 2015.
If it is compatible, will support continue for Spring Data 3.x?

A: You should use Spring Data Neo4j 4.x - 3.x will not be supported/maintained going forward.


text:
Q: Angular onSameUrlNavigation for a lazy loaded module I have a problem with lazy loaded module data re-fetch.
onSameUrlNavigation  simply doesn't work
I have a separate routing module for a lazy loaded feature and maybe I couldn't integrate onSameUrlNavigation  properly
project structure:
app/
    app.component.ts
    app.module.ts
    app-routing.module.ts
        someFeature/
            someFeature.module.ts
            someFeature-routes.module.ts
            someFeature.component.ts

app-routing module code:
    export const routes: Routes = [{
      {
      path: 'myfeature',
      loadChildren: () => import('./someFeature/someFeature.module').then(m => m.someFeatureModule),
      canActivate: [AuthGuard],
      runGuardsAndResolvers: 'always',
    }}]

@NgModule({
  imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})],
  exports: [RouterModule],
})
export class AppRoutingModule {
}

lazy loaded routing module:
    const routes: Routes = [
      {
        path: '',
        component: someFeatureComponent,
      },
    ];
    @NgModule({
      imports: [RouterModule.forChild(routes)],
      exports: [RouterModule],
    })

component code:
    ngOnInit(): void {
    this.unsubscribe$ = new Subject<void>();
    this.route
      .queryParams.pipe(
      takeUntil(this.unsubscribe$),
      map(p => {
        this.loading = true;
        if (p.page && p.limit) {
          this.page = p.page;
          this.limit = p.limit;
        }
        return {
          page: this.page,
          limit: this.limit,
        };
      }),
      flatMap((f) => this.myService.getData(f)),
      tap(() => this.loading = false),
    )
      .subscribe((payload) => {
        this.data = payload.data;
      })
    ;
  }

this is the problematic section (in the component code)
 reload(): void {
    this.router.navigate(['someFeature'], {queryParams: {page: this.page, limit: this.limit}});
  }
refetchDataOnClick(){
 this.reload();
}

data is fetched on the first request (So I decided that there's no problem with module import or anything like that), but re-fetch isn't happening as I can see there are no additional requests on the API.
I tried adding and removing "runGuardsAndResolvers" ,someFeature-routes module, but with no success.
I also tried adding onSameUrlNavigation to someFeature-routes module, but forChild can accept only one parameter

A: Thanks to the user frido's comment I found a solution
instead of reloading the component I just call the service which loads the data again
this.loading = true;
    this.myService.getData({page: this.page, limit: this.limit})
      .pipe(
        takeUntil(this.unsubscribe$),
        finalize(() => this.loading = false))
      .subscribe((payload) => {
        this.data = payload.data;
      });


text:
Q: Menu fading out of a navigationbar I want to have a menu in views and tableviews where I have a navigationbar in my iphone-app. The menu should fade in from above, when clicking on the menu-button on the navigationbar.
Currently I have a view with buttons as a menu and animate them in an out using menus y-position. I added the menu inside my current viewvontrollers view, but I get into trouble, when my menu is above a table-section.
My idea is to cutomize the navigationbar and set a view into it as the parentview for my menu. Is this a good idea? The navigationbar should alway be visible, even while the menu fades in.
Are there any example on the web, I could use?

A: The quick and dirty way would probably be to grow the bounds (height) of the UINavigationBar and then use [Navbar addSubview:] to add your custom view.
However, this probably won't look good and might fly in the face of Apple's Human Interface Guidelines. If you want to use a menu, I would use something close to the UIPopover class on the iPad. A couple GitHub projects exist already to recreate the class on the iPhone - https://github.com/werner77/WEPopover
Edit: Thought of something else: You might want to look into UIActionSheet. It sounds like exactly what you want to do, except comes out of the bottom instead of from the Navigation Bar.


text:
Q: Python selenium - set value using data-qa attribute I have the following object,

      Username
      <input id="ember4124" class="ember-view ember-text-field form-control" data-qa="username-input" type="text" value="">

Here the input id "ember4124" changes every time. My requirement is find by data-qa "username-input" and pass the value, where value is the username.
Using below I can find the element,
driver.find_elements_by_css_selector("input[data-qa='username-input']")

Output: [<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="90144b65-8a86-4d54-90ae-4ccccab0cc9e", element="18e84265-46a7-41d8-a487-299e95ef7ae8")>]

But not sure how to send the value. Can anyone assist me?

A: Probably there is only one element so use element (without s at the end) instead of elements to get only first element and you will have
x = driver.find_element_by_css_selector("input[data-qa='username-input']")
x.send_keys("James Bond")

If you will use elements (with s at the end) then you get list and you will have to use [0] to get first element on list
x = driver.find_elements_by_css_selector("input[data-qa='username-input']")
x[0].send_keys("James Bond")


text:
Q: JSON.parse with special chracters I'm sorry for posting this but I after so many hours of pulling my hair I can't seem to make any more progress.
I have a JSON string that is being returned to me as part of a JSON object like:
{ "name": "value", "artifact": "THE_JSON_STRING" }

I'm pulling the artifact out and using JSON.parse works fine most of the time but I came across an issue when the artifact string contains a /" and JSON.parse breaks. I've gone over many solutions and tried what seems like everything but there has to be something I'm doing wrong.  For simplicity this is my code:
var str = '{ "name" : "This is some value \"escaped\""}';
str = str.replace(/\\"/g, 'x')
var obj = JSON.parse(str);

Any help would be much appreciated
https://fiddle.jshell.net/u428x1k7/2/
Edit
I'm very new to Javascript but I'm using React with Redux to make a service call to get my data.  Then I try to use the data via props:
Raw Data Coming from Service Call:
{
    "id": "8b6df083-8f4f-440a-bc67-4c57bf0969bf",
    "name": "My API ",
    "description": "All APIs are added to this category if one is not specified",
    "icon": "fa-university",
    "services": [
        {
            "id": "16e32cfd-b6e7-4c49-b5ef-ebb5456e6639",
            "artifact": "{ \"swagger\": \"2.0\", \"info\": { \"version\": \"1.0.0\", \"title\": \"Swagger Petstore\", \"license\": { \"name\": \"MIT\" } }, \"host\": \"petstore.swagger.io\", \"basePath\": \"/v1\", \"schemes\": [ \"http\" ], \"consumes\": [ \"application/json\" ], \"produces\": [ \"application/json\" ], \"paths\": { \"/pets\": { \"get\": { \"summary\": \"List all pets\", \"operationId\": \"listPets\", \"tags\": [ \"pets\" ], \"parameters\": [ { \"name\": \"limit\", \"in\": \"query\", \"description\": \"How many items to return at one time (max 100)\", \"required\": false, \"type\": \"integer\", \"format\": \"int32\" } ], \"responses\": { \"200\": { \"description\": \"An paged array of pets\", \"headers\": { \"x-next\": { \"type\": \"string\", \"description\": \"A link to the next page of responses\" } }, \"schema\": { \"$ref\": \"#/definitions/Pets\" } }, \"default\": { \"description\": \"unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } }, \"post\": { \"summary\": \"Create a pet\", \"operationId\": \"createPets\", \"tags\": [ \"pets\" ], \"responses\": { \"201\": { \"description\": \"Null response\" }, \"default\": { \"description\": \"unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } } }, \"/pets/{petId}\": { \"get\": { \"summary\": \"Info for a specific pet\", \"operationId\": \"showPetById\", \"tags\": [ \"pets\" ], \"parameters\": [ { \"name\": \"petId\", \"in\": \"path\", \"required\": true, \"description\": \"The id of the pet to retrieve\", \"type\": \"string\" } ], \"responses\": { \"200\": { \"description\": \"Expected response to a valid request\", \"schema\": { \"$ref\": \"#/definitions/Pets\" } }, \"default\": { \"description\": \"unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } } } }, \"definitions\": { \"Pet\": { \"required\": [ \"id\", \"name\" ], \"properties\": { \"id\": { \"type\": \"integer\", \"format\": \"int64\" }, \"name\": { \"type\": \"string\" }, \"tag\": { \"type\": \"string\" } } }, \"Pets\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/definitions/Pet\" } }, \"Error\": { \"required\": [ \"code\", \"message\" ], \"properties\": { \"code\": { \"type\": \"integer\", \"format\": \"int32\" }, \"message\": { \"type\": \"string\" } } } } }"
    },
    {
        "id": "b4328bbc-bcb0-4313-b80c-a4394e553dd9",
        "artifact": "{ \"swagger\": \"2.0\", \"info\": { \"title\": \"Uber API\", \"description\": \"Move your app forward with the Uber API\", \"version\": \"1.0.0\" }, \"host\": \"api.uber.com\", \"schemes\": [ \"https\" ], \"basePath\": \"/v1\", \"produces\": [ \"application/json\" ], \"paths\": { \"/products\": { \"get\": { \"summary\": \"Product Types\", \"description\": \"The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order.\", \"parameters\": [ { \"name\": \"latitude\", \"in\": \"query\", \"description\": \"Latitude component of location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" }, { \"name\": \"longitude\", \"in\": \"query\", \"description\": \"Longitude component of location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" } ], \"tags\": [ \"Products\" ], \"responses\": { \"200\": { \"description\": \"An array of products\", \"schema\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/definitions/Product\" } } }, \"default\": { \"description\": \"Unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } } }, \"/estimates/price\": { \"get\": { \"summary\": \"Price Estimates\", \"description\": \"The Price Estimates endpoint returns an estimated price range for each product offered at a given location. The price estimate is provided as a formatted string with the full price range and the localized currency symbol.

The response also includes low and high estimates, and the [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code for situations requiring currency conversion. When surge is active for a particular product, its surge_multiplier will be greater than 1, but the price estimate already factors in this multiplier.\", \"parameters\": [ { \"name\": \"start_latitude\", \"in\": \"query\", \"description\": \"Latitude component of start location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" }, { \"name\": \"start_longitude\", \"in\": \"query\", \"description\": \"Longitude component of start location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" }, { \"name\": \"end_latitude\", \"in\": \"query\", \"description\": \"Latitude component of end location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" }, { \"name\": \"end_longitude\", \"in\": \"query\", \"description\": \"Longitude component of end location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" } ], \"tags\": [ \"Estimates\" ], \"responses\": { \"200\": { \"description\": \"An array of price estimates by product\", \"schema\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/definitions/PriceEstimate\" } } }, \"default\": { \"description\": \"Unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } } }, \"/estimates/time\": { \"get\": { \"summary\": \"Time Estimates\", \"description\": \"The Time Estimates endpoint returns ETAs for all products offered at a given location, with the responses expressed as integers in seconds. We recommend that this endpoint be called every minute to provide the most accurate, up-to-date ETAs.\", \"parameters\": [ { \"name\": \"start_latitude\", \"in\": \"query\", \"description\": \"Latitude component of start location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" }, { \"name\": \"start_longitude\", \"in\": \"query\", \"description\": \"Longitude component of start location.\", \"required\": true, \"type\": \"number\", \"format\": \"double\" }, { \"name\": \"customer_uuid\", \"in\": \"query\", \"type\": \"string\", \"format\": \"uuid\", \"description\": \"Unique customer identifier to be used for experience customization.\" }, { \"name\": \"product_id\", \"in\": \"query\", \"type\": \"string\", \"description\": \"Unique identifier representing a specific product for a given latitude & longitude.\" } ], \"tags\": [ \"Estimates\" ], \"responses\": { \"200\": { \"description\": \"An array of products\", \"schema\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/definitions/Product\" } } }, \"default\": { \"description\": \"Unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } } }, \"/me\": { \"get\": { \"summary\": \"User Profile\", \"description\": \"The User Profile endpoint returns information about the Uber user that has authorized with the application.\", \"tags\": [ \"User\" ], \"responses\": { \"200\": { \"description\": \"Profile information for a user\", \"schema\": { \"$ref\": \"#/definitions/Profile\" } }, \"default\": { \"description\": \"Unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } } }, \"/history\": { \"get\": { \"summary\": \"User Activity\", \"description\": \"The User Activity endpoint returns data about a user's lifetime activity with Uber. The response will include pickup locations and times, dropoff locations and times, the distance of past requests, and information about which products were requested.

The history array in the response will have a maximum length based on the limit parameter. The response value count may exceed limit, therefore subsequent API requests may be necessary.\", \"parameters\": [ { \"name\": \"offset\", \"in\": \"query\", \"type\": \"integer\", \"format\": \"int32\", \"description\": \"Offset the list of returned results by this amount. Default is zero.\" }, { \"name\": \"limit\", \"in\": \"query\", \"type\": \"integer\", \"format\": \"int32\", \"description\": \"Number of items to retrieve. Default is 5, maximum is 100.\" } ], \"tags\": [ \"User\" ], \"responses\": { \"200\": { \"description\": \"History information for the given user\", \"schema\": { \"$ref\": \"#/definitions/Activities\" } }, \"default\": { \"description\": \"Unexpected error\", \"schema\": { \"$ref\": \"#/definitions/Error\" } } } } } }, \"definitions\": { \"Product\": { \"properties\": { \"product_id\": { \"type\": \"string\", \"description\": \"Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles.\" }, \"description\": { \"type\": \"string\", \"description\": \"Description of product.\" }, \"display_name\": { \"type\": \"string\", \"description\": \"Display name of product.\" }, \"capacity\": { \"type\": \"string\", \"description\": \"Capacity of product. For example, 4 people.\" }, \"image\": { \"type\": \"string\", \"description\": \"Image URL representing the product.\" } } }, \"PriceEstimate\": { \"properties\": { \"product_id\": { \"type\": \"string\", \"description\": \"Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles\" }, \"currency_code\": { \"type\": \"string\", \"description\": \"[ISO 4217](http://en.wikipedia.org/wiki/ISO_4217) currency code.\" }, \"display_name\": { \"type\": \"string\", \"description\": \"Display name of product.\" }, \"estimate\": { \"type\": \"string\", \"description\": \"Formatted string of estimate in local currency of the start location. Estimate could be a range, a single number (flat rate) or \"Metered\" for TAXI.\" }, \"low_estimate\": { \"type\": \"number\", \"description\": \"Lower bound of the estimated price.\" }, \"high_estimate\": { \"type\": \"number\", \"description\": \"Upper bound of the estimated price.\" }, \"surge_multiplier\": { \"type\": \"number\", \"description\": \"Expected surge multiplier. Surge is active if surge_multiplier is greater than 1. Price estimate already factors in the surge multiplier.\" } } }, \"Profile\": { \"properties\": { \"first_name\": { \"type\": \"string\", \"description\": \"First name of the Uber user.\" }, \"last_name\": { \"type\": \"string\", \"description\": \"Last name of the Uber user.\" }, \"email\": { \"type\": \"string\", \"description\": \"Email address of the Uber user\" }, \"picture\": { \"type\": \"string\", \"description\": \"Image URL of the Uber user.\" }, \"promo_code\": { \"type\": \"string\", \"description\": \"Promo code of the Uber user.\" } } }, \"Activity\": { \"properties\": { \"uuid\": { \"type\": \"string\", \"description\": \"Unique identifier for the activity\" } } }, \"Activities\": { \"properties\": { \"offset\": { \"type\": \"integer\", \"format\": \"int32\", \"description\": \"Position in pagination.\" }, \"limit\": { \"type\": \"integer\", \"format\": \"int32\", \"description\": \"Number of items to retrieve (100 max).\" }, \"count\": { \"type\": \"integer\", \"format\": \"int32\", \"description\": \"Total number of items available.\" }, \"history\": { \"type\": \"array\", \"items\": { \"$ref\": \"#/definitions/Activity\" } } } }, \"Error\": { \"properties\": { \"code\": { \"type\": \"integer\", \"format\": \"int32\" }, \"message\": { \"type\": \"string\" }, \"fields\": { \"type\": \"string\" } } } } }"
    }
]
}

Action:
export const RECEIVE_CATEGORY = 'RECEIVE_CATEGORY';
function receiveCategory(category) {
    return {
        type: RECEIVE_CATEGORY,
        category
    }
}

export function fetchCategory(categoryID) {
    return function(dispatch) {
        dispatch(requestCategory(categoryID))

        return fetch(`${baseURL}/categories/${categoryID}`, {
            method: 'GET',
            headers: {
                'Accept' : 'application/json'
            }
        })
            .then(response => response.json())
            .then(json => dispatch(receiveCategory(json)))
            .catch(function(error) {
                console.log(error);
            });
    }
}

Reducer:
    function categories(state = [], action) {
    switch(action.type) {
            case RECEIVE_CATEGORIES :
            return action.categories;
        case RECEIVE_CATEGORY :

            /* TODO : there has to be an easier way ...*/
            var index = 0;
            for(index; index < state.length; index++) {
                if(action.category.id === state[index].id) {
                    break;
                }
            }

            var array= [...state.slice(0, index),
                action.category,
                ...state.slice(index+1)
            ];
            return array;
        default:
            return state;
    }
}

A: You have to double escape the backslash when representing the JSON as a string. When you actually fetch that data from a service or API, you can just parse it and it should work fine. Check out the example below.

var obj = {
  "name": "This is some value \"escaped\"",
  "artifact": "THE_JSON_STRING"
};

var test = JSON.stringify(obj);
console.log(test);

var str = '{"name":"This is some value \\"escaped\\"","artifact":"THE_JSON_STRING"}';
console.log(test);
console.log(test === str);

try {
  console.log(JSON.parse(str).name);
} catch (error) {
  console.log(error);
}


text:
Q: SQL Server Free Text search: search words from a phrase in two tables I have a table with companies and one with categories. I'm using SQL Server Free Text search, and searching companies (by name and description) works fine. But now I also want to include the category table.
I want to search for something like: ABC 24 Supermarket.
Now, ABC 24 should make a match with the Name column in the company table, and Supermarket is the name of the category this company is connected to.
Right now I have something like this:
DECLARE @SearchString VARCHAR(100) = '"ABC 24 Supermarket"'
SELECT * FROM Company CO
INNER JOIN Category CA
ON CA.CategoryId = CO.CategoryId
WHERE CONTAINS((CO.[Description], CO.[Name]), @SearchString)
AND CONTAINS(CA.[Description], @SearchString)

But this of course, gives me nothing, because my search string cannot be found in either the company or the category table. Does anyone have an idea on how to do a combined search on my company and category table?
The idea of splitting strings, as suggested in Lobo's answer below, is not really an option. Because i don't know which part will be the one that should match a category and which part should be used for matching company names/descriptions. Users might just as well type in "Supermarket ABC 24".

A: Imho the right way to do this is to create an indexed view containing the primary key of the main table ('company' in your example) and a second column containing all the stuff you're actually want to search, i.e.
create View View_FreeTextHelper with schemabinding as
select CO.PrimaryKey,                            -- or whatever your PK is named
       CO.description +' '+CA.description +' '+CO.whatever as Searchtext
  from dbo.company CO join
       dbo.category CA on CA.CategoryId = CO.CategoryId

Note the two-part form of your tables. A few restrictions arise from this, e.g. all involved tables must be in the same table space and as far as I remember, no TEXT columns are allowed in this kind of concatenation (you may cast them though).
Now create a unique index on the PrimaryKey column
create unique clustered index [View_Index]
    on View_FreeTextHelper (PrimaryKey ASC)

Finally create the fulltext index on the view using the 'Searchtext' column as the only column to index. Of course, you may add more columns, if you e.g. wish to distinguish in searching for company name and location and, the names of the managers (you would just concatenate them in a second column).
Retrieving your data is now easy:
select tbl.RANK,
       co.*
  from freetextTable(View_FreeTextHelper,Search,'Your searchtext here') tbl
  join company co on tbl.key=co.PrimaryKey
 order by tbl.RANK desc

You may also limit the output using select top 50 as the freetexttable clause will eventually return quite a lot of close and not so close results.
And finally, don't get confused if you cannot find thing like 'off the shelf inc.' Beware of the stop lists. These are list of words which are very common, have no semantic use (like the) and are therefore removed from the text to be indexed. In order to include them, you have to switch of the stoplist feature.
A last tipp: full text is very powerful but has a lot of features, tricks and caveats. It takes quite a bit to fully understand the techniques and get the best results you want.
Have fun.

A: If we assume that the name of columns are unique per row, then you can use below query. The following example returns all rows that contain either the phrase "ABC", "24" or "Supermarket" in each of the columns
DECLARE @SearchString nvarchar(100) = N'ABC 24 Supermarket'
SET @SearchString = REPLACE(LTRIM(RTRIM(@SearchString)), ' ', '|')
SELECT *
FROM Company CO JOIN Category CA ON CA.CategoryId = CO.CategoryId
WHERE CONTAINS(CO.[Name], @SearchString)
 AND CONTAINS(CO.[Description], @SearchString)
 AND CONTAINS(CA.[Description], @SearchString)

First of all you need to prepare a search value for the CONTAINS predicate used in the WHERE clause. In this case I replaced spaces between the words on the "|" logic operator(the bar symbol (|) may be used instead of the OR keyword to represent the OR operator.)

A: ( I don't have sql-server installation to try CONTAINS. You can replace the column LIKE '%string%' with CONTAINS(column, 'string') and try.)
See all queries here.

Another update - After reading the other answers and the manual, it seems that you don't need parenthesized values in the contains string unlike I expected. So this should work too - (you may even try ' | ' instead of ' OR '
SELECT CO.name, CA.description FROM company CO
         INNER JOIN category CA
             ON CA.CategoryId = CO.CategoryId
WHERE CONTAINS((CO.name,CO.description), REPLACE('ABC 25 SuperMarket', ' ', ' OR '))
      AND
      CONTAINS(CA.description, REPLACE('ABC 25 SuperMarket', ' ', ' OR '))

If it complains about syntax error near replace, you can create a search string DECLARE @SearchString varchar(MAX) = REPLACE('ABC 25 SuperMarket',' ', ' OR ') and then use it in place of replace(......) as second argument.

Update as per your modified question -
Firstly, you should be moving the logic to application level if possible. I think, it is too much to handle it here. I have come up with this query, but note that this will  split each word and search for it in both name and description so you will end up getting a few more results than what you might think. For e.g. this will return all Supermarket which have either ABC or 24 in their name compared to returning only one Supermarket with name ABC 24 in my previous query. This should actually help you out because, as per you, user might just type "ABC Supermarket 24" or "24 ABC Supermarket" or ...
DECLARE @SearchString varchar(MAX) = 'ABC 24 SuperMarket'
DECLARE @separator varchar(MAX) = ' '
DECLARE @Like1 varchar(MAX) = 'CO.name LIKE'
DECLARE @Like2 varchar(MAX) = 'CA.description LIKE'

DECLARE @WHERE1 varchar(MAX) = '( ' + @Like1 + ' ''%' +
           REPLACE(@SearchString,@separator,'%'' OR ' + @Like1 + ' ''%')+'%'')'

DECLARE @WHERE2 varchar(MAX) = '( ' + @Like2 + ' ''%' +
           REPLACE(@SearchString,@separator,'%'' OR ' + @Like2 + ' ''%')+'%'')'

DECLARE @QueryString varchar(MAX) =
           CONCAT('SELECT CO.name, CA.description FROM company CO
                       INNER JOIN category CA
                             ON CA.CategoryId = CO.CategoryId
                    WHERE ', @WHERE1, ' AND ', @WHERE2)
exec(@QueryString);

If you output @WHERE1 you should see
( CO.name LIKE '%ABC%' OR CO.name LIKE '%25%' OR CO.name LIKE '%SuperMarket%')

As I said before you might want to try using CONTAINS with parenthesized values like
DECLARE @SearchString varchar(MAX) = 'ABC 25 SuperMarket'
DECLARE @separator varchar(MAX) = ' '

DECLARE @WHEREString varchar(MAX) = '''"' +
        REPLACE(@SearchString, @separator, '" OR "')+'"'''

SELECT CO.name, CA.description FROM company CO
        INNER JOIN category CA
           ON CA.CategoryId = CO.CategoryId
WHERE CONTAINS((CO.name,CO.description), @WHEREString)
      AND
      CONTAINS(CA.description, @WHEREString)

If you output @WHEREString you should see
'"ABC" OR "25" OR "SuperMarket"'

Previous answer:
This will assumes that the word after the last space is the description and rest is the `name.
You can split the search string and use them as shown below. This query is using like as I don't have a sql-server installation.
DECLARE @SearchString VARCHAR(100) = 'ABC 24 Supermarket'
DECLARE @searchLength int = len(@SearchString)
DECLARE @searchReverse VARCHAR(100) = reverse(@SearchString)

SELECT CO.name, CA.description FROM company CO
        INNER JOIN category CA
            ON CA.CategoryId = CO.CategoryId
WHERE CO.name LIKE concat( '%', SUBSTRING(@SearchString,0,@searchLength-charindex(' ',@searchReverse)+1), '%')
     AND
     CA.description LIKE concat( '%', SUBSTRING(@SearchString,@searchLength-charindex(' ',@searchReverse)+2,@searchLength), '%')

This should work. Please note that the where clause is using AND instead of OR.
DECLARE @SearchString VARCHAR(100) = 'ABC 24 Supermarket'
DECLARE @searchLength int = len(@SearchString)
DECLARE @searchReverse VARCHAR(100) = reverse(@SearchString)
DECLARE @company VARCHAR(100) = SUBSTRING(@SearchString,0,@searchLength-charindex(' ',@searchReverse)+1)
DECLARE @category VARCHAR(100) = SUBSTRING(@SearchString,@searchLength-charindex(' ',@searchReverse)+2,@searchLength)

SELECT CO.name, CA.description FROM company CO
        INNER JOIN category CA
           ON CA.CategoryId = CO.CategoryId
WHERE CONTAINS((CO.name, CO.description), @company)
      AND
      CONTAINS(CA.description , @category)

A: I dont know whether this will constitute a GREAT answer (I tend to doubt it) but I wanted a problem to work on and I happed to pick yours, so here's my solution:
DECLARE @SearchString VARCHAR(100) = '"ABC 24 Supermarket"'

DECLARE @AllItems table (
  SearchItem varchar(100)
  ),
        @x int;

-- break up @SearchString into component search items:
select @x = charindex(' ', @SearchString);
while @x > 0 begin
  insert @AllItems (SearchItem) values (substring(@SearchString, 1, @x - 1));
  select @SearchString = substring(@searchstring, @x + 1);
  select @x = charindex(' ', @Searchstring);
end;
-- add the last item
insert @AllItems (SearchItem) values (@SearchString)

DECLARE @this varchar(100),  -- = current search item
        @found table (       -- table to contain rows matching the current search item
          ID int
          ),
        @usable table (      -- table to contain rows matching all search items
          ID int             --   already tested
          );

--now process search items one-at-a-time
while (select count(*) from @AllItems) > 0 begin
  select @this = min(SearchItem) from @AllItems;
  delete @AllItems where SearchItem = @this;

  if (select count(*) from @usable) = 0 begin  --first search item
    --for the first item, just find the companies matching this item, in either the
    --company name or description or category description columns:
    insert @found (ID)
    select CO.CompanyID
    from Company CO inner join Category CA on CO.CategoryID = CA.CategoryID
    where contains ((CO.[Description], [CO.[Name]) @this)
      or contains (CA.[Description], @this)
  end
  else begin                                   --other search items
    -- for subsequent items, its got to match with the company name or description
    -- or category description as above - BUT it's also got to be a company we
    -- already identified when processing the previous term
    insert @found (ID)
    select CO.CompanyID
    from Company CO inner join Category CA on CO.CategoryID = CA.CategoryID inner join @usable U on CO.CompanyID = U.ID
    where contains ((CO.[Description], [CO.[Name]) @this)
      or contains (CA.[Description], @this)
  end

  --now clear out and re-populate the usable companies table ready for processing the
  --next search item
  delete @usable;
  insert @usable (ID)
  select ID
  from @found;

  --and clear out the current matches table, ready for the next search item
  delete @found;
end;

--whatever is in @usable now, is a match with all the component search items, so:
select CO.*
from Company CO inner join Category CA on CO.CategoryId = CA.CategoryId inner join @usable U on CO.CompanyID = U.ID;

A: It occurs to me that while the answer I wrote previously should work fine and be reasonably efficient, processing the search items one-at-a-time and only searching within the existing search result for items after the first, that it would be faster to do it all at once, using dynamic sql.
So here is another potential solution to your problem, which I enter as a separate answer as it is unrelated to the solution I've already posted:
DECLARE @SearchString VARCHAR(100) = '"ABC 24 Supermarket"'

DECLARE @AllItems table (
  SearchItem varchar(100)
  ),
        @x    int,
        @cmd  varchar(1000),
        @wc   varchar(8000),
        @this varchar(100);

-- break up @SearchString into component search items:
select @x = charindex(' ', @SearchString);
while @x > 0 begin
  insert @AllItems (SearchItem) values (substring(@SearchString, 1, @x - 1));
  select @SearchString = substring(@searchstring, @x + 1);
  select @x = charindex(' ', @Searchstring);
end;
-- add the last item
insert @AllItems (SearchItem) values (@SearchString)

select @cmd = 'select CO.* from Company CO inner join Category CA on CO.CategoryId = CA.CategoryId WHERE';

--now process search items one-at-a-time building up a where clause to plug into @cmd:
while (select count(*) from @AllItems) > 0 begin
  select @this = min(SearchItem) from @AllItems;
  delete @AllItems where SearchItem = @this;

  select @wc = @wc +
    'AND (contains ((CO.[Description], [CO.[Name]) ''' + @this + ''') or contains (CA.[Description], ''' + @this + ''') '
end;

--ready to go:
exec (@cmd + substring(@wc, 4));  --substring removes first AND

A: The idea here is that we are going to parse the string into different variables then search  the other variables for a match.
DECLARE @SearchString VARCHAR(100) = '"ABC 24 Supermarket"', @A varchar(100), @B varchar(100), @C varchar(100),@index int

set @A = Substring(@searchString, 1, PATINDEX('% %', @searchString) -1)
set @index = PATINDEX('% %', @searchString) + 1
set @B = Substring(@searchString, @index, PATINDEX('% %', @substring(@searchstring, @index, 100)) -1)
Set @index = PATINDEX('% %', @substring(@searchstring, @index, 100)) + 1
set @C = Substring(@searchString, @index, PATINDEX('% %', @substring(@searchstring, @index, 100)) -1)

SELECT * FROM Company CO
INNER JOIN Category CA
  ON CA.CategoryId = CO.CategoryId
WHERE CO.[Description] like @A
  or CO.[Description] like @B
  or CO.[Description] like @c
  or CO.[Name] like @A
  or CO.[Name] like @B
  or CO.[Name] like @C
  or CA.[Description] like @A
  or CA.[Description] like @B
  or CA.[Description] like @C

This code looks ugly to me but it should accomplish the requirements for the user entering up to 3 items to search on. Anyone have suggestions on cleaning it up?

A: this should work.
DECLARE @SearchString VARCHAR(100) = '"ABC 24 Supermarket"'
set @SearchString = replace(@SearchString,' ','" or "')

SELECT * FROM Company CO
INNER JOIN Category CA
ON CA.CategoryId = CO.CategoryId
WHERE CONTAINS((CO.[Description], CO.[Name]), @SearchString)
AND CONTAINS(CA.[Description], @SearchString)

hope helps a bit

A: Why don't you just reverse your logic?  Your example was trying to find the search string within your field values, but what you really want to do is find your field values within your search string, no?
    DECLARE @SearchString VARCHAR(100) = '"ABC 24 Supermarket"'
SELECT * FROM Company CO
INNER JOIN Category CA
ON CA.CategoryId = CO.CategoryId
WHERE (CONTAINS(@SearchString, CO.[Description]) OR CONTAINS(@SearchString, CO.[Name]))
AND CONTAINS(@SearchString, CA.[Description])

A: you can use FREETEXT instead of CONTAIN.
DECLARE @SearchString VARCHAR(100) = '"ABC 24 Supermarket"'
SELECT * FROM Company CO
INNER JOIN Category CA
ON CA.CategoryId = CO.CategoryId
WHERE FREETEXT((CO.[Description], CO.[Name]), @SearchString)
OR FREETEXT(CA.[Description], @SearchString)


text:
Q: How to Get the title of a custom field? I know how to get the value of a custom field, using code like get_post_meta($post->ID, 'company', true);. Is there a way to get the name of the custom field?

A: to get a post custom fields name you can use get_post_custom
eg:
$post_meta = get_post_custom($post->ID);
foreach ( $post_meta as $key => $value )
    echo $key . " => " . $value . "
";

this will print a list of custom_field_name => custom_field_value

A: if you only want to get the name, you can use get_post_custom_keys
<?php

  $custom_field_keys = get_post_custom_keys();
  foreach ( $custom_field_keys as $key => $value ) {
    $valuet = trim($value);
      if ( '_' == $valuet{0} )
      continue;
    echo $key . " => " . $value . "
";
  }
?>

prints something like this:
0 => mykey
1 => yourkey


text:
Q: groff for Windows: man pages bad formatted when output in windows command prompt From Windows command prompt I am using groff for Windows to display some man pages.
I can see that some characters are not being correctly outputted and in some case depending on the device being passed in as parameter I get some warnings.
For example:

*

*groff -man -Tascii < mymanpage.1 | more
The man page is displayed but with below warning and some characters not correctly displayed.
Warning:
:48: warning: can't find character with input code 226
Also I get characters not correctly displayed:

*groff -man -Tutf8 < mymanpage.1 | more
Even worse:

*groff -man -Tlatin1 < mymanpage.1 | more

A: Apparently, the Windows terminal does not understand the escape codes. If col is available on your system, you might:
groff -man -Tascii  mymanpage.1 | col -b |more


text:
Q: Sinatra app has session issues in production I've been working on a web application in Ruby using Sinatra. While in development, I really never had a lot of issues with sessions. However, now i'm ussing passenger to actually deploy the application I have quite a lot of issues regarding that session data keeps getting 'reset'.
I've seen other stack overflow questions related to this problem but no answer has yet fixed it for me. I've tried a couple of things:

*

*Putting 'use Rack::Session::Pool' inside config.ru as suggested here

*Used Rack::Session::Pool like explained here

*Tried Memcache as explained here

*Tried Redis-Rack (gives me an error: Exception NoMethodError in Rack application object (undefined method `foreign_key' for nil:NilClass))

Nothing seems to be helping really... I either end up having an error or my session gets reset each request. I know that passenger probably uses multiple threads and that that is the cause for the sessions to not be working, but I cannot seem to find a solution to the problem.
Am I missing something obvious here? Any suggestions?
Gemfile
source "https://rubygems.org"

gem 'mongo', '1.8.6'
gem 'sinatra', '1.4.8'
gem 'mongo_mapper'
gem 'bson_ext'
gem 'active_model_serializers'
gem 'activemodel-serializers-xml'
gem 'sinatra-flash'
gem 'sinatra-param', require: 'sinatra/param'
gem 'rack-recaptcha2', git: 'https://github.com/nicolas-simplex/rack-    recaptcha'
gem 'mail'
gem 'slugify'
gem 'biz'
gem 'bcrypt'
gem 'redis-rack'

group :development do
  gem 'mailcatcher', '~> 0.6.4'
end

config.ru
It had different forms depending on if I used just Rack::Session::Pool, Memcache or Redis. This one was the one I used for redis:
require 'rubygems'
require 'sinatra'
require File.expand_path '../app.rb', __FILE__

require 'rack'
require 'rack/session/redis'

require_relative './app'

app = App.new

sessioned = use Rack::Session::Redis.new(app)

run sessioned

App.rb
require 'rubygems'
require 'bundler/setup'
require 'sinatra'

require 'slugify'

class App < Sinatra::Base
  use Rack::Protection

  set :bind, '0.0.0.0'
end

require_relative './config/init'  # Initialize configuration files
require_relative './helpers/init' # Initialize helpers
require_relative './routes/init'  # Initialize routes
require_relative './models/init'  # Initialize models

require_relative './util/tokens'  # Token utility

... # Some database seeding, basic setup for some data I use

TL;DR
Sinatra and Passenger together resets sessions in production, while this doesn't happen in development.

A: After some more researching I found the configuration option passenger_sticky_sessions. Because in my web application session storage is quite important, this works fine for me. However, the use of this is not recommended in all use cases because all the clients sends will be routed to the same originating application process.
Documentation: https://www.phusionpassenger.com/library/config/nginx/reference/#passenger_sticky_sessions
With this configuration parameter 'on' in my conf file in nginx/sites-enabled, I was able to just use the simple rack session pool:
use Rack::Session::Pool, path: '/', expire_after: 2592000


text:
Q: Java - Conflicting interface type parameters I'm working on a project that involves reading in structures from a string/stream.
As part of my design I attempted to create something along these lines:

*

*public class Thing;

*public class SpecialThing extends Thing;

*public class ShinyThing extends Thing;

*public abstract class ThingDeserialiser implements Iterable<Thing>;

*public abstract class GenericThingDeserialiser<T extends Thing> extends ThingDeserialiser implements Iterable<T>;

*public class SpecialThingDeserialiser extends GenericThingDeserialiser<SpecialThing>;

*public class ShinyThingDeserialiser extends GenericThingDeserialiser<ShinyThing>;
However I get an error with GenericThingDeserialiser because there is a conflict between

*

*ThingDeserialiser implementing Iterable<Thing> and

*GenericThingDeserialiser trying to implement Iterable<T>.

I am able to create a set up like this in C#, why am I unable to do this in Java?
Is there a way around this somehow?

I have also considered removing ThingDeserialiser in hope that ShinyThingDeserialiser and SpecialThingDeserialiser might both be castable to GenericThingDeserialiser<Thing>, but as expected that's not going to work.
I have another idea involving interfaces, but I'd like to stop and ask for advice before continuing.
If it's not obvious, the general idea is that the Thing objects are retrieved from strings/streams based on reasonably trivial patterns.

A:
I am able to create a set up like this in C#, why am I unable to do this in Java?

Because generics in Java are not covariant.
That is, even if you have types A and B, and B extends A, class Foo<B> will not be a subtype of Foo<A>. Due to type erasure, at runtime, both will be Foo.
As already suggested, you should really get rid of ThingDeserialiser here and just do with the GenericThingDeserializer<T extends Thing> implements Iterable<T>. You can then create, say, MyThingDeserialiser implements GenericThingDeserialiser<MyThing>.

A: I would definitely suggest removing ThingDeserialiser. You say you want to cast ShinyThingDeserialiser and SpecialThingDeserializer to GenericThingDeserialiser<Thing>, but that won't work. You should be able to cast them to GenericThingDeserialiser<? extends Thing>. Does that help?


text:
Q: Drupal Module help required function nat_customForms_block($op = 'list', $delta = 0, $edit = array()){
// set up an empty array which will contain the block contents
$block = array();

switch ($op) {
  case "list":
    drupal_set_message('
>Medjool List
');
    // Generate listing of blocks from this module, for the admin/block page
    $block[0]["info"] = t('Medjool Dates are scrummy don\'t you know');
    //$block[0]["content"] = "list # list # list # list # list # list # list # list";
    $block[0]["content"] = _nct_customForms_CONTENT();
  break;

  case "view":
    drupal_set_message('
>Medjool View
');
    // Generate listing of blocks from this module, for the admin/block page
    $block[0]["info"] = t('Medjool Dates are scrummy don\'t you know');
    $block[0]['status'] = 1;
    $block[0]["subject"] = 'SUBJECT Medjool SUBJECT';
    $block[0]["content"] = '####Medjool Dates are scrummy don\'t you know####';

case "save":
  break;

case "configure":
  break;
}
return $block;
//print render($block['content']);
}

Using Drupal 6 I am trying to get this block to output some content. I can see it when I assign it to a region in a panel but no content is being rendered. How do I make the content part of the block be rendered in the panel?
thank you!

A: The above code started working for me after I removed the delta portion from the $block
eg.
$block[0]["info"] = t('Medjool Dates are scrummy don\'t you know');

turns into
$block["info"] = t('Medjool Dates are scrummy don\'t you know');

Weird since I specified $delta as being 0.


text:
Q: IndexOutOfBoundsException in LinkedList I'm getting IndexOutOfBoundsException, which looks like kind of impossible to me.
Code:
public class SomethingCalculator {

    @Nullable
    private Config mConfig;
    @Nullable
    private Long mTime;
    final private List<Long> mLinkedList = new LinkedList<>();

    public synchronized void setupWithConfiguration(Config config, Long time) {
        //config and time are non null always
        mTime = time;
        mConfig = config;
        generatLookUp();
    }

    public synchronized void reset() {
        mConfig = null;
        mTime = null;
        mLinkedList.clear();
    }

    @Nullable
    public synchronized Long getTheValue(long ms) {
        if (mConfig == null)
            return null;

        // getting exception here
        if (ms > mLinkedList.get(mLinkedList.size() - 1)) {
            return 0l; // something
        }
        return 0l; // something
    }

    private synchronized void generatLookUp() {
        mLinkedList.clear();
        if (mConfig == null || mTime==null)
            return;
        // mLinkedList will always have size > 0 after executing this
        // based upon config this method add elements to mLinkedList

        // adding dummy values
        mLinkedList.add(1L);
        mLinkedList.add(2L);
    }
}

getting an exception while calling SomethingCalculator.getTheValue()
Exception:
Fatal Exception: java.lang.IndexOutOfBoundsException: Index: 4, Size: 0
 at java.util.LinkedList.checkElementIndex(LinkedList.java:565)

Not sure if mMylinkedList.size() returns 4 then how mMylinkedList.get(4) throws IndexOutOfBoundsException.

A: After looking into generated AAR it was found that the synchronized keyword was stripped thus this exception can occur. The synchronized keyword was stripped due to a proguard optimization.
Removed this:
-optimizations !method/marking/synchronized

Now i can see synchronized keyword in the generated AAR.


text:
Q: Is a valuation of a logic formula always a trivial task? I.e. is it practically executable?
For a given structure for a quantified theory, is the valuation of any formula always practically executable?

In the case of propositional calculus, where every formula has a certain degree, this is the case as there you can simply climb down to atomic propositions (for which the truth values are determined by the structure/assignment) to validate the whole expression. I don't know if this is also as easy for predicate logic though. It's known that there isn't always a proof, but does this relate to the valuation?

Argument against it: If it's true that for a given structure you can automatically evaluate any given formula (or at least sentence with no free variable), then I don't see why finding a proof (e.g. writing down the sequence constructed in say a Hilbert style system) - or rather the possibility not to be able to find one - would be such a big of a deal. To do the valuation means confirm the truth or falsity, which just seems like a proof in a way. Is executing a validation equivalent to finding a proof? On the other hand.
On the other hand, I don't know where the problem with the evaluation would kick in (maybe related to there being more possible variables for a formula).

A: No, in general there is no effective way to determine whether a formula is true or false in an effective first-order structure. A key example is $\mathbb{N}$; in that context Post's theorem shows exactly what Turing degrees are needed to evaluate the truth or falsity of arithmetical formulas with quantifiers.  It turns out that the nesting of the quantifiers is the key factor in making the decision problem difficult. The canonical oracle that can compute the valuation function for an effective structure is the $\omega$th Turing jump of the empty set, $\emptyset^{(\omega)}$.
The question whether a formula is provable in an effective logical system is also undecidable in general, but it is just a $\Sigma^0_1$ question regardless of the complexity of the formula, and so this problem can always be solved by using a $\emptyset'$ oracle, unlike the problem of computing a valuation which requires stronger oracles.

A: *

*Trying out a valuation is much easier than finding a proof. In the propositional case, for example, you can check the validity of a given evaluation in time linear to the formula size. On the other hand, checking whether a formula has a satisfying valuation is NP-complete, and hence, finding a proof in any proof system will be NP-hard.

*In predicate calculus, you can have, e.g., structures with uncomputable predicates, so checking whether a structure satisfies a formula is undecidable in general. In fact, finding decision procedures for given first-order theories and sub-logics of first-order logic is an active field of research.


text:
Q: Decorate step implementation in Cucumber-js Introduction
Im using https://github.com/cucumber/cucumber-js in typescript. Sample of code implementation looks like average cucumber implementation:
import {
    Given,
    Then,
    When
} from 'cucumber'

Given(`Page is up and running`, function(this: World) {
    someFunction()
})

Goal
What I would like to achieve is to be able to somehow decorate Given, so that:

*

*some action can be invoked before code inside Given. Lets say, for simple example, I would like to print first Given argument (so Page is up and running).

*there would be no need to modify existing step implementation.

Each step got two alias function definitions in index.d.ts, e.g.:
export function Given(pattern: RegExp | string, code: StepDefinitionCode): void;
export function Given(pattern: RegExp | string, options: StepDefinitionOptions, code: StepDefinitionCode): void;

A: In the original version of CucumberJS, there were more hooks available including beforeStep. However, there is a way to achieve this functionality in versions of the framework such as 6.0.5 using setDefinitionFunctionWrapper. Example:
setDefinitionFunctionWrapper(fn => async function step(...args) {
    //
    // do something before the step definition runs.
    //
    const result = await fn.apply(this, args);
    //
    // do something after the step definition runs.
    //
    return result;
});

Online Example: https://testjam.io/?p=O2wodDVOveAMdA9HKMKy
Known limitations and caveats:

*

*This function will wrap every step definition AND hook.

*This particular implementation assumes that the step definition or hook is not using a callback.

*I'm not sure how to make callbacks and promises work here at the same time, it may be possible but you'll have to manage that yourself by possibly inspecting the type of the last parameter and then handling it from there.

Update: The beforeStep and afterStep hooks are available in CucumberJS 7.x and later


text:
Q: How to change O365 Tenant Display Name or Organization Name using Powershell I've been finding Powershell commands to change Office 365 Tenant Display name or Organization Name but unable to find any. The reason why I need it through Powershell is because I have 500 advisors and each advisor has it's own Office 365 tenant account. Login to each tenant one by one and changing names will take much of my time, so I need help if Powershell can do this for me as quickly as possible.
Any help is much appreciated.
Organization Name
Tenant Name under Properites

A: You should read the official Azure Active Directory V2 PowerShell documentation. There are

*

*Get-AzureADTenantDetail for listing the details and

*Set-AzureADTenantDetail for setting contact information.

Because Get-AzureADTenantDetail can list the
DisplayName but Set-AzureADTenantDetail can only change the contact information (-MarketingNotificationEmails, -SecurityComplianceNotificationMails, -SecurityComplianceNotificationPhones & -TechnicalNotificationMails) this strongly suggests there's no PowerShell command for changing the display name.


text:
Q: Restrict access to vertex classes in OrientDB I'm looking at OrientDB as a possible data base. I'm quite intrigued by the ability to create vertex classes from which to instantiate vertices. My question is related to the access to these classes:
Is it possible to restrict access to classes (i.e. being able to create a vertex based on a class) per user/role?
Example:
User A creates a vertex class
CREATE CLASS ClassA EXTENDS V

User A should obviously be able to create vertices of class ClassA. But they should be the only one to do so, possibly even be the only ones who can see that class ClassA exists. So User B should not be able to do
CREATE VERTEX ClassA

From what I've read I have the feeling that this might be possible using clusters, but from the documentation I could not find out how that would be done.