text:
Q: How to get udev to identify a USB device regardless of the USB port it is plugged in? I'd like to write a script that backups data on a USB device every time the latter is getting plugged in a random USB slot. Now I know about the KERNEL=sdX identifier but the problem is that depending on the slot and on whether other devices are already plugged in the sdX will change. What would be the best way to identify my USB device in udev ? I've been thinking about using partuuid but I don't know how and I don't know where the partuuid is stored in the first place or how it is worked out.

A: If you partition your device using gdisk as opposed to fdisk you will create a GPT-style partition table which, for each partition, can hold a PARTUUID and a PARTLABEL. The c command in gdisk allows you to set the partition name, ie the PARTLABEL.
These partition ids do not change when you reformat the partition by creating a new filesystem on it.
Most filesystems allow you to get or set a UUID and LABEL on the filesystem. The means to do so depends on the filesystem type, eg for ext3/4 it is tune2fs with -U and -L. These appear as UUID and LABEL in Linux.
Do not confuse these 2 sets of ids. blkid will show all of them:
/dev/sdb1: LABEL="MYLABEL" UUID="A369-D716" TYPE="vfat" PARTLABEL="My new partition" \
  PARTUUID="f0817245-d3ce-408b-9457-e33dfc04aebe"

You can see the udev attributes with
$ udevadm info -p $(udevadm info -q path -n /dev/sdb1)
...
E: ID_FS_LABEL=MYLABEL
E: ID_FS_LABEL_ENC=MYLABEL
E: ID_FS_UUID=A369-D716
E: ID_FS_UUID_ENC=A369-D716
E: ID_PART_ENTRY_UUID=f0817245-d3ce-408b-9457-e33dfc04aebe
E: ID_PART_TABLE_UUID=7301d696-b66d-4f85-8272-7dd5e29175ae
E: ID_PART_ENTRY_NAME=My\x20new\x20partition

A: I've done something similar, using the UUID (Universally Unique Identifier library) of the USB device.
You can see UUIDs with blkid command:
# blkid

You can find more information about blkid, looking into it's man page
# man blkid


text:
Q: Wolfram|Alpha not able to graph sum_(n=0)^∞ (-(ExpIntegralE[-n, (-1 + n) Log[x]] Log[x]^(1 + n))"? I know for a fact that nothing in my expression is wrong, then why cant Wolfram|Alph graph:
sum_(n=0)^∞ (-(ExpIntegralE[-n, (-1 + n) Log[x]] Log[x]^(1 + n))) ?

Note: The above expression is in Wolfram L  anguage code.

A: Assuming that you mean
Sum[-ExpIntegralE[-n, (n-1) Log[x]] Log[x]^(1 + n), {n, 0, ∞}]

the term $n=1$ is ComplexInfinity, and so the entire formula is infinite.

A: If you can't get WolframAlpha, or anything else for that matter, to plot an infinite sum over the reals then see if it can plot a finite sum over some points that is close enough to what you want to see.
This
plot Table[sum_(n=2)^10 (-(ExpIntegralE[-n, (-1+n) Log[x]] Log[x]^(1+n))),{x,2.,100.,.25}]

plots just fine under WolframAlpha and the upper bound on the summation seems to be enough to show the behavior of the expression. Likewise the range of x.
Notice I skipped 0 and 1 to avoid the infinities.
People need to make it really really REALLY clear that they are asking a question ONLY within the domain of WolframAlpha or they will almost always get people who will answer something about Mathematica instead. And that will often happen even when people do make it REALLY clear. That happens even with WolframAlpha questions posted to https://community.wolfram.com/

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best practices of phpunit in a complex scenario I'm trying to test my php cms and I question many things about why & how:

*

*official policy is NOT to test protected/private methods

but then it's about functional/behavioral testing and not unit testing

*

*development of phpunit stopped support of database testing a whole time ago; sth they called it dbunit if I remember right

as a result we do have to create complex test classes for database management or because these classes already exist in an extensive work like mine we do have to use methods from other classes existed here and there that facilitate database management so the system under test actually helps the testing software in a close interaction one with the other

*

*it is said that testing is actually call your code before even having written it using your awesome command line and move step-by-step to your goal

but if your testing code targets a more functional approach then I can call my in-development method with any other way even from command line and debug it sending output to php log with error_log.
Having said that I save all the trouble of writing 100 lines of code + more than 100 lines of test files, changing 100 lines of code + changing more than 100 lines of test files and on and on....
In the above if we add all the arguments about not to test protected/private members we end in a simple question: why that fuss on unit testing of private/protected methods that might have long chain of internal calls when there are much simpler methods of testing while we code?
All the above introduction seems to me necessary for the reader to understand what I'm asking about:
Given the next specific method can you propose the best approach of (unit?) testing?
1 Method under test
File is /home/test/server/auth/Auth.php
namespace g3\auth;

use g3\Singleton;
use g3\TokenFactory;
use g3\Registry;
use g3\Header;
use g3\Session;
use g3\Lang;
use g3\Utils;
use g3\mail\MailClient;
use Firebase\JWT;

class Auth {
   /** @var AuthToken $token The AuthToken of this class */
   protected $token;
   /** @var PDO $dbh The PDO handler to the database */
   protected $dbh;
...............
...............
   /**
    * Called by user/admin during the registration.
    *
    * We use argument '$params' to handle the additional fields that we added at
    * table 'profiles' (beyond, 'id', 'emai', 'password', 'isactive' and 'dt').
    * An example for '$params': array('first_name' => "John", 'second_name' => "Doe").
    * The available fields:
    * - 'title',
    * - 'fullname',
    * - 'first_name',
    * - 'second_name',
    * - 'username',
    * - 'address1',
    * - 'address2',
    * - 'zip1',
    * - 'zip2',
    * - 'tel',
    * - 'mobile',
    * - 'fax',
    * - 'city',
    * - 'state',
    * - 'country',
    * - 'birth',
    * - 'language',
    * - 'currency',
    * - 'img',
    * - 'capacity_kb'.
    *
    * Two modes of call:
    * -by user: addUser($email, $password, $params, $name),
    * -by admin: addUser($email, $password, $params, $name, true).
    *
    * In admin mode no request is added or email is sent.
    *
    * If useradd succeeds but profile fails to be inserted in table 'profiles'
    * then return array contains key 'message' although key 'error' remains
    * 'false' (registration proceeds).
    *
    * @param string $email
    * @param string $password
    * @param string[] $params Data for table 'profiles'
    * @param boolean $admin True to bypass activation process
    *
    * @return A hash array with keys 'error', 'message' and if successful, 'uid'
    */
   protected function addUser($email, $password, $params = array(), $name = '', $admin = false) {
      $return['error'] = true;
      $query = $this->dbh->prepare("INSERT INTO {$this->token->get('table_users')} (isactive) VALUES (0)");
      if (!$query->execute()) {
         $return['message'] = $this->getLang()["system_error"] . " #03";
         return $return;
      }
      $uid = $this->dbh->lastInsertId();
      $email = \htmlentities(\strtolower($email));
      if (((int)$this->token->get('suppress_activation') != 1) && !$admin) {
         $addRequest = $this->addRequest($uid, $email, "activation", $name);
         if ($addRequest['error'] == 1) {
            $query = $this->dbh->prepare("DELETE FROM {$this->token->get('table_users')} WHERE id = ?");
            $query->execute(array($uid));
            $return['message'] = $addRequest['message'];
            return $return;
         }
         $isactive = 0;
      } else {
         $isactive = 1;
      }
      $password = $this->getHash($password);
      $query = $this->dbh->prepare("UPDATE {$this->token->get('table_users')} SET email = ?, password = ?, isactive = ? WHERE id = ?");
      if (!$query->execute(array($email, $password, $isactive, $uid))) {
         $query = $this->dbh->prepare("DELETE FROM {$this->token->get('table_users')} WHERE id = ?");
         $query->execute(array($uid));
         $return['message'] = $this->getLang()["system_error"] . " #04";
         return $return;
      }
      if (!\is_array($params))
         $params = array();
      if(($r = $this->addProfile($uid, $params)) !== true)
         $return['message'] = $r['message'];
      $return['error'] = false;
      $return['uid'] = $uid;
      return $return;
   }
.............
.............
}

Database is SQLite.
It's obvious that a numerous other methods of class Auth are called:
Auth::addUser
  | | | |
  v | | |
Auth::getLang
    | | |
    v | |
Auth::addRequest
      | |
      v |
Auth::getHash
        |
        v
Auth::addProfile

Also a number of other classes are used:
class Auth
  | | |
  v | |
Auth::token is a AuthToken: contains parameters supporting the
authentication system like table names, database path etc.
    | |
    v |
class Lang: contains parameters that lead to language specific
messages
      |
      v
Auth::dbh is a database connection returned by DbHandler::getHandler
class DbHandler: manages the database

You can skip next parts and read "5. Write some tests"
2 Setup Composer

*

*just download a local composer.phar

*build a composer.json: I don't care about composer's autoloader as I have mine and I load it there from my /home/test/server/g3 sub-folder

*I don't use vendor but only for developing packages all production software including my g3 framework are deployed on /home/test/server sub-folder on seperate sub-folders with a custom autoloader
/home/test/composer.json
{
   "autoload": {
      "psr-4": {
         "": "server"
      }
    },
   "require-dev": {
         "mockery/mockery": "=1.3.1",
         "phpunit/phpunit": "=6.5.14",
         "phpunit/php-invoker": "=1.1.4",
         "gealex/doublit": "=2.1.5",
         "phpspec/prophecy": "=1.10.3"
    }
}

/home/test/vendor/autoloader.php
<?php

// my autoloader
require_once("/home/test/server/g3/ClassLoader.php");

// autoload.php @generated by Composer

require_once __DIR__ . '/composer/autoload_real.php';

return ComposerAutoloaderInit1e0ee11cc0a18a5af0d236383dd8a888::getLoader();

3 Setup phpunit

*

*just download a local /home/test/server/dev/phpunit-6.phar

*customize the /home/test/server/dev/phpunit.xml
<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="/home/test/vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false"
         syntaxCheck="false"
         verbose="true">

    <testsuites>
        <testsuite name="Root">
            <directory suffix="Test.php">../../tests/server/root</directory>
        </testsuite>

        <testsuite name="Core">
            <directory suffix="Test.php">../../tests/server/core</directory>
        </testsuite>

        <testsuite name="Auth">
            <directory suffix="Test.php">../../tests/server/auth</directory>
        </testsuite>

        <testsuite name="mail">
            <directory suffix="Test.php">../../tests/server/mail</directory>
        </testsuite>
    </testsuites>

    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">server</directory>
        </whitelist>
    </filter>

    <php>
        <var name="skip_mail_integration_tests" value="1"/>
        <var name="skip_auth_integration_tests" value="1"/>
        <var name="domain" value="4f4d4ebc35f1.eu.ngrok.io"/>
        <var name="mailTo" value="john.doe@gmail.com"/>
    </php>
</phpunit>

4 Extend PHPUnit\Framework\TestCase
First let's extend PHPUnit\Framework\TestCase with /home/test/tests/server/CustomTestCase.php that

*

*supports Prophecy and Mockery

*contains utility methods callMethod, getProperty and setProperty that can access private/protected members

*initializes \g3\Registry with real \g3\Token values coming from json files
<?php
declare(strict_types=1);

use Mockery\Adapter\Phpunit\MockeryTestCase;
use PHPUnit\Framework\TestCase;

/**
 * runTestsInSeparateProcesses
 */
class CustomTestCase extends MockeryTestCase {
   protected $prophet;

   // returns the call to private/protected methods
   public static function callMethod($obj, $name, array $args) {
      $class = new \ReflectionClass($obj);
      $method = $class->getMethod($name);
      $method->setAccessible(true);
      return $method->invokeArgs($obj, $args);
   }
   // returns private/protected properties
   public static function getProperty($obj, $name){
      $r = new ReflectionObject($obj);
      $p = $r->getProperty($name);
      $p->setAccessible(true);
      return $p->getValue($obj);
      // alternative syntax with closures
      //$cls = \Closure::bind(function() use ($name){return $this->{$name};}, $obj, \get_class($obj));
      //return $cls();
   }
   // sets a value to a private/protected property
   public static function setProperty($object, $property, $value){
       $ref = new \ReflectionClass($object);
       $ref_prop = $ref->getProperty($property);
       $ref_prop->setAccessible(true);
       $ref_prop->setValue($object, $value);
   }

   public static function setUpBeforeClass(){
      Mockery::globalHelpers();
   }
   public static function tearDownAfterClass(){
   }

   protected function setup() {
      $this->prophet = new \Prophecy\Prophet;
   }
   protected function tearDown() {
      $this->prophet->checkPredictions();
      Mockery::close();
   }
}

5 Write some tests
File is /home/test/tests/server/g3/auth/AuthTest.php
<?php
declare(strict_types=1);

require_once(__DIR__ . '/../CustomTestCase.php');

/**
 * runTestsInSeparateProcesses
 */
class AuthTest extends CustomTestCase {
   protected $tokens;

   public static function setUpBeforeClass(){
      parent::setUpBeforeClass();
      // tokens initialize the g3 framework and these contain full data
      // from json files; access them like:
      // \g3\Registry::getInstance()->getToken('g3\auth\AuthToken') etc.
      static::callMethod(\g3\Dispatcher::getInstance(), 'tokenInit', array());
   }
   public static function tearDownAfterClass(){
      parent::tearDownAfterClass();
      \g3\Registry::getInstance()->destroy();
   }

   /**
    * Creates mocked constructor argument objects before each test.
    * These tokens do not contain data read from json files; dummy tokens.
    * Accessible through $this->tokens.
    */
   protected function setup() {
      parent::setup();

      $resolverToken = $this->getMockBuilder('\g3\ResolverToken')
         ->disableOriginalConstructor()
         ->getMock();

      $requestToken = $this->getMockBuilder('\g3\RequestToken')
         ->disableOriginalConstructor()
         ->getMock();

      $authToken = $this->getMockBuilder('\g3\auth\AuthToken')
         ->disableOriginalConstructor()
         ->getMock();

      $accountToken = $this->getMockBuilder('\g3\AccountToken')
         ->disableOriginalConstructor()
         ->getMock();

      $dbh = $this->getMockBuilder('\g3\DbHandler')
         ->disableOriginalConstructor()
         ->getMock();

      $lang = $this->getMockBuilder('\g3\Lang')
         ->disableOriginalConstructor()
         ->getMock();

      $session = $this->getMockBuilder('\g3\Session')
         ->disableOriginalConstructor()
         ->getMock();

      $this->tokens = array('accountToken' => $accountToken, 'resolverToken' => $resolverToken, 'requestToken' => $requestToken, 'authToken' => $authToken, 'dbh' => $dbh, 'lang' => $lang, 'session' => $session);
   }

   /**
    * Deletes mocked objects stored at $this->tokens after each test.
    */
   protected function tearDown() {
      parent::tearDown();
      $this->tokens = null;
   }

   /**
    * Prints a message on CLI
    */
   public function out($msg){
      $msg = \str_replace(array('test_', '_', "\n"), array('', ' ', ":\n"), $msg);
      fwrite(STDOUT, $msg);
   }

   /**
    * Adds an inactive user. It uses real tokens.
    */
   public function helper_addUserInactive($arr) {
      // AuthToken is not stored in Registry & not synchronized
      \g3\TokenFactory::getInstance()->synchronize($arr['authToken'], 'r');
      $test = $this->getMockBuilder('\g3\auth\Auth')
         ->setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         ->setMethods(['addRequest', 'getHash'])
         ->getMock();
      $test->expects($this->exactly(1))
         ->method('addRequest')
         ->will($this->returnValue(array('error' => false)));
      $test->expects($this->exactly(1))
         ->method('getHash')
         ->will($this->returnValue('123'));
      $token = static::getProperty($test, 'token');
      $token->set('suppress_activation', 0);
      $profile = array('first_name' => 'John', 'second_name' => 'Doe', 'username' => 'John', 'address1' => 'White House, Washington D.C.', 'country' => 'USA');
      // call 'addUser'
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', $profile, 'John'));
      $users = $arr['authToken']->get('table_users');
      $profiles = $arr['authToken']->get('table_profiles');

      return array(
         'dbh' => $arr['dbh'],
         'user' => array('id' => $r['uid'], 'email' => $arr['to'], 'password' => '123', 'role' => 'guest', 'isactive' => '0'),
         'profile' => $profile,
         'tables' => array('users' => $arr['authToken']->get('table_users'), 'profiles' => $arr['authToken']->get('table_profiles'), 'requests' => $arr['authToken']->get('table_requests'))
      );
   }

/**
    * Adds an active user. It uses real tokens.
    */
   public function helper_addUserActive($arr) {
      // AuthToken is not stored in Registry & not synchronized
      \g3\TokenFactory::getInstance()->synchronize($arr['authToken'], 'r');
      $test = $this->getMockBuilder('\g3\auth\Auth')
         ->setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         ->setMethods(['addRequest', 'getHash'])
         ->getMock();
      $test->expects($this->never())
         ->method('addRequest');
      $test->expects($this->exactly(1))
         ->method('getHash')
         ->will($this->returnValue('123'));
      $token = static::getProperty($test, 'token');
      $token->set('suppress_activation', 1);
      $profile = array('first_name' => 'John', 'second_name' => 'Doe', 'username' => 'John', 'address1' => 'White House, Washington D.C.', 'country' => 'USA');
      // call 'addUser'
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', $profile, 'John'));
      $users = $arr['authToken']->get('table_users');
      $profiles = $arr['authToken']->get('table_profiles');

      return array(
         'dbh' => $arr['dbh'],
         'user' => array('id' => $r['uid'], 'email' => $arr['to'], 'password' => '123', 'role' => 'guest', 'isactive' => '1'),
         'profile' => $profile,
         'tables' => array('users' => $arr['authToken']->get('table_users'), 'profiles' => $arr['authToken']->get('table_profiles'), 'requests' => $arr['authToken']->get('table_requests'))
      );
   }

   /**
    * Adds an active user as admin. It uses real tokens.
    */
   public function helper_adminAddsUserActive($arr) {
      // AuthToken is not stored in Registry & not synchronized
      \g3\TokenFactory::getInstance()->synchronize($arr['authToken'], 'r');
      $test = $this->getMockBuilder('\g3\auth\Auth')
         ->setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         ->setMethods(['addRequest', 'getHash'])
         ->getMock();
      $test->expects($this->never())
         ->method('addRequest');
      $test->expects($this->exactly(1))
         ->method('getHash')
         ->will($this->returnValue('123'));
      $token = static::getProperty($test, 'token');
      $token->set('suppress_activation', 0);
      $profile = array('first_name' => 'John', 'second_name' => 'Doe', 'username' => 'John', 'address1' => 'White House, Washington D.C.', 'country' => 'USA');
      // call 'addUser'
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', $profile, 'John', true));
      $users = $arr['authToken']->get('table_users');
      $profiles = $arr['authToken']->get('table_profiles');

      return array(
         'dbh' => $arr['dbh'],
         'user' => array('id' => $r['uid'], 'email' => $arr['to'], 'password' => '123', 'role' => 'guest', 'isactive' => '1'),
         'profile' => $profile,
         'tables' => array('users' => $arr['authToken']->get('table_users'), 'profiles' => $arr['authToken']->get('table_profiles'), 'requests' => $arr['authToken']->get('table_requests'))
      );
   }

   /**
    * Inserts a user & profile without the call to any `Auth` method.
    * It uses real tokens.
    */
   public function helper_insertUser($arr, $active = '0') {
      // AuthToken is not stored in Registry & not synchronized
      \g3\TokenFactory::getInstance()->synchronize($arr['authToken'], 'r');
      $users = $arr['authToken']->get('table_users');
      $profiles = $arr['authToken']->get('table_profiles');
      $requests = $arr['authToken']->get('table_requests');
      // table 'users'
      $time = \time();
      $query = $arr['dbh']->getHandler()->prepare("INSERT INTO {$users} (email, password, isactive, dt) VALUES (?, ?, ?, ?)");
      $query->execute(array($arr['to'], '123', $active, $time));
      $uid = $arr['dbh']->getHandler()->lastInsertId();
      return array(
         'dbh' => $arr['dbh'],
         'user' => array('id' => $uid, 'email' => $arr['to'], 'password' => '123', 'role' => 'guest', 'isactive' => $active),
         'tables' => array('users' => $users, 'profiles' => $profiles, 'requests' => $requests)
      );
   }

   /**
    * Deletes user from tables `users`, `profiles` and `requests`.
    * `$arr` is the return of `::test_helper_addUserInactive` or
    * `::test_helper_addUserActive`.
    */
   public function helper_deleteAddedUser($arr) {
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      $requests = $arr['tables']['requests'];
      $query = $arr['dbh']->getHandler()->prepare("DELETE FROM {$users} WHERE id = ?");
      $query->execute(array($arr['user']['id']));
      $query = $arr['dbh']->getHandler()->prepare("DELETE FROM {$profiles} WHERE uid = ?");
      $query->execute(array($arr['user']['id']));
      $query = $arr['dbh']->getHandler()->prepare("DELETE FROM {$requests} WHERE uid = ?");
      $query->execute(array($arr['user']['id']));
   }

   /**
    * Helper that returns real tokens of g3 platform.
    * @group integration_email
    * @group test
    */
   public function test_helper_construct_with_real_tokens() {
      $systemToken = \g3\Registry::getInstance()->getToken('g3\SystemToken');
      $accountToken = \g3\Registry::getInstance()->getToken('g3\AccountToken');
      $lang = new \g3\Lang(ROOT . "/server/g3/auth/language", $accountToken->get('site', 'language'));
      $exceptionToken = \g3\Registry::getInstance()->getToken('g3\ExceptionToken');
      $dbh = new \g3\DbHandler('sqlite', 'db_auth', $accountToken, $exceptionToken);
      // AuthToken is not stored in Registry & not synchronized
      $authToken = \g3\TokenFactory::getInstance()->getToken('g3\auth\AuthToken', null, array('registry' => \g3\Registry::getInstance(), 'dbh' => $dbh));
      \g3\TokenFactory::getInstance()->synchronize($authToken, 'r');
      $requestToken = \g3\Registry::getInstance()->getToken('g3\RequestToken');
      $resolverToken = \g3\Registry::getInstance()->getToken('g3\ResolverToken');
      $session = \g3\Session::getInstance();
      $to = $GLOBALS['mailTo'];

      $this->assertTrue(true);

      return array('systemToken' => $systemToken, 'accountToken' => $accountToken, 'resolverToken' => $resolverToken, 'requestToken' => $requestToken, 'authToken' => $authToken, 'exceptionToken' => $exceptionToken, 'dbh' => $dbh, 'lang' => $lang, 'session' => $session, 'to' => $to);
   }

   // !!!WAIT WHAT THE HELL!!!
   // !!!WE DIDN'T EVEN BEGIN TO TEST!!!

   /*
    * ===============
    * Auth::addUser()
    * ===============
    */
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_for_misspelled_table_users($arr) {
      $this->out(__METHOD__ . "\n");
      // AuthToken is not stored in Registry & not synchronized
      \g3\TokenFactory::getInstance()->synchronize($arr['authToken'], 'r');
      $test = $this->getMockBuilder('\g3\auth\Auth')
         ->setConstructorArgs(array($arr['resolverToken'], $arr['requestToken'], $arr['authToken'], $arr['accountToken'], $arr['dbh']))
         ->setMethods(null)
         ->getMock();
      $token = static::getProperty($test, 'token');
      $token->set('table_users', 'user');
      // call 'addUser'
      $this->expectException(PDOException::class);
      $r = static::callMethod($test, 'addUser', array($arr['to'], '123', array(), 'John'));
      echo "\n";
   }
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_updates_tables_users_profiles($tokens) {
      $this->out(__METHOD__ . "\n");
      $arr = $this->helper_addUserInactive($tokens);
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      // query table 'users'
      $query = $arr['dbh']->getHandler()->prepare("SELECT email, role, password, isactive FROM $users WHERE id = ?");
      $query->execute(array($arr['user']['id']));
      $row = $query->fetch(\PDO::FETCH_ASSOC);
      $this->assertSame($arr['user']['email'], $row['email']);
      $this->assertSame($arr['user']['role'], $row['role']);
      $this->assertSame($arr['user']['password'], $row['password']);
      $this->assertSame($arr['user']['isactive'], $row['isactive']);
      // query table 'profiles'
      $query = $arr['dbh']->getHandler()->prepare("SELECT first_name, second_name, username, address1 FROM $profiles WHERE uid = ?");
      $query->execute(array($arr['user']['id']));
      $row = $query->fetch(\PDO::FETCH_ASSOC);
      $this->assertSame($arr['profile']['first_name'], $row['first_name']);
      $this->assertSame($arr['profile']['second_name'], $row['second_name']);
      $this->assertSame($arr['profile']['username'], $row['username']);
      $this->assertSame($arr['profile']['address1'], $row['address1']);
      // delete entries in tables
      $this->test_helper_deleteAddedUser($arr);
      echo "\n";
   }
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_updates_tables_users_profiles_with_supress_activation($tokens) {
      $this->out(__METHOD__ . "\n");
      $arr = $this->helper_addUserActive($tokens);
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      // query table 'users'
      $query = $arr['dbh']->getHandler()->prepare("SELECT email, role, password, isactive FROM $users WHERE id = ?");
      $query->execute(array($arr['user']['id']));
      $row = $query->fetch(\PDO::FETCH_ASSOC);
      $this->assertSame($arr['user']['email'], $row['email']);
      $this->assertSame($arr['user']['role'], $row['role']);
      $this->assertSame($arr['user']['password'], $row['password']);
      $this->assertSame($arr['user']['isactive'], $row['isactive']);
      // query table 'profiles'
      $query = $arr['dbh']->getHandler()->prepare("SELECT first_name, second_name, username, address1 FROM $profiles WHERE uid = ?");
      $query->execute(array($arr['user']['id']));
      $row = $query->fetch(\PDO::FETCH_ASSOC);
      $this->assertSame($arr['profile']['first_name'], $row['first_name']);
      $this->assertSame($arr['profile']['second_name'], $row['second_name']);
      $this->assertSame($arr['profile']['username'], $row['username']);
      $this->assertSame($arr['profile']['address1'], $row['address1']);
      // delete entries in tables
      $this->test_helper_deleteAddedUser($arr);
      echo "\n";
   }
   /**
    * @depends test_helper_construct_with_real_tokens
    */
   public function test_addUser_updates_tables_users_profiles_for_admin($tokens) {
      $this->out(__METHOD__ . "\n");
      $arr = $this->helper_adminAddsUserActive($tokens);
      $users = $arr['tables']['users'];
      $profiles = $arr['tables']['profiles'];
      // query table 'users'
      $query = $arr['dbh']->getHandler()->prepare("SELECT email, role, password, isactive FROM $users WHERE id = ?");
      $query->execute(array($arr['user']['id']));
      $row = $query->fetch(\PDO::FETCH_ASSOC);
      $this->assertSame($arr['user']['email'], $row['email']);
      $this->assertSame($arr['user']['role'], $row['role']);
      $this->assertSame($arr['user']['password'], $row['password']);
      $this->assertSame($arr['user']['isactive'], $row['isactive']);
      // query table 'profiles'
      $query = $arr['dbh']->getHandler()->prepare("SELECT first_name, second_name, username, address1 FROM $profiles WHERE uid = ?");
      $query->execute(array($arr['user']['id']));
      $row = $query->fetch(\PDO::FETCH_ASSOC);
      $this->assertSame($arr['profile']['first_name'], $row['first_name']);
      $this->assertSame($arr['profile']['second_name'], $row['second_name']);
      $this->assertSame($arr['profile']['username'], $row['username']);
      $this->assertSame($arr['profile']['address1'], $row['address1']);
      // delete entries in tables
      $this->test_helper_deleteAddedUser($arr);
      echo "\n";
   }

I just tested sth I knew from the beginning - several months ago - it was working o'right as I can send GET or POST requests and with injected error_log I have production error-free code bypassing all unit-testing theories.
Also these tests are prone to error if someone starts messing with the testing method they start producing code errors from the test file; in that case you have to debug the tests that try to test your code!
From my point of view I start to believe that unit-testing is an excellent way to waste loose your time. I understand your argument that this is not unit testing so I replace protected with public does that fixes anything?
I wonder can someone prove me wrong? What's your approach then?

A: My approach is the same as the approach I take when solving certain problem/task - break it into as much smaller peaces as possible and solve them one by one.
If I have to test an advanced class and make sure all its methods cover certain criterias, I would make a tests for every method of it even if it is private or protected (with closure functions). So the next time something throws an error/does not pass a test, you know exactly what it is and why it fails.


text:
Q: 2d histogram: Get result of full nbins x nbins I am using matplotlib's hist2d function to make a 2d histogram of data that I have, however I am having trouble interpreting the result.
Here is the plot I have:

This was created using the line:
hist = plt.hist2d(X, Y, (160,160), norm=mpl.colors.LogNorm(vmin=1, vmax=20))

This returns a 2d array of (160, 160), as well as the bin edges etc.
In the plot there are bins which have a high frequency of values (yellow bins). I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins. But I would expect there to be 160*160 values, but I can only find 160 X and 160 Y values.
What I would like to do is essentially filter out the more dense data from the less dense data. If this means representing the data as a single value (a bin), then that is ok.
Am I misinterpreting the function or am I not accessing the data results correctly? I have tried with spicy also but the results seem to be in the same or similar format.

A: You need Seaborn package.
You mentioned

I would like to be able to get the results of this histogram and filter out the bins that have low values, preserving the high bins.

You should definitely be using one of those:

*

*seaborn.joinplot(...,kind='hex') : it shows the counts of observations that fall within hexagonal bins. This plot works best with relatively large dataset.

*seaborn.joinplot(...,kind='kde') : use the kernel density estimation to visualize a bivariate distribution. I recommed it better.

Example 'kde'
Use number of levels n_levels and shade_lowest=False to ignore low values.
import seaborn as sns
import numpy as np
import matplotlib.pylab as plt
x, y = np.random.randn(2, 300)
plt.figure(figsize=(6,5))
sns.kdeplot(x, y, zorder=0, n_levels=6, shade=True, cbar=True,
     shade_lowest=False, cmap='viridis')

A: Not sure if this is what you wanted.
The hist2d docs specify that the function returns a tuple of size 4, where the first item h is a heatmap.
This h will have the same shape as bins.
You can capture the output (it will still plot), and use argwhere to find coordinates where values exceed, say, the 90th percentile:
h, xedges, yedges, img = hist = plt.hist2d(X, Y, bins=(160,160), norm=mpl.colors.LogNorm(vmin=1, vmax=20))

print(list(np.argwhere(h > np.percentile(h, 90))))


text:
Q: Installing .apk file on Emulator in Linux I'm trying to integrate the Zxing Bar code scanner into an application, but I need to install the bar code application on the emulator first. I already downloaded the .apk file. How do I install it on the emulator? I'm running Ububtu.

A: Goto Shell/Terminal/, reach at android-sdk/tools directory then
adb install fileName.apk
or ./adb install fileName.apk

A: *

*Start emulator.

*android-sdk-linux/platform-tools > ./adb -e install Test-debug.apk


text:
Q: Find regular expression match in string after a given index in Scala I want to find a match (if any) for a regular expression on a string, but only testing after a given index. For example:
val p = "[a-zA-Z_][a-zA-Z0-9_]*".r
val t = "const pi = 3.141592"
val m = p.findFirstMatchIn(t, start=5) // not real syntax

That is, I want to ignore the first n = 5 characters of the string. Is there any way to do that?

A: Scala's .r syntax is a thin wrapper around the original java.util.regex.{Pattern, Matcher} API. The original API provides more control. Use Matcher.region:
scala> val m = Pattern.compile("[a-zA-Z_][a-zA-Z0-9_]*").matcher(t)
scala> m.region(5, t.size)
scala> m.find()
scala> m.group(0)
res6: String = pi


text:
Q: How can I increase ID column manually in Sharepoint Online I need to change default ID column to different number on Microsoft Lists(Sharepoint Lists) so, its now 633 but i need to increase to 1198. I just want the change the last entry to 1198, so it stars increasing from 1198.
is it possible?
Thanks.

A: Unfortunately you cannot Change this, Its by Product design, But as a workaround you can add some dummy items and delete the same, you may get the desired ID.
If still you want to keep the logic , I suggest to create a new column and update the ID, while retrieve the data , please query the created column and fetch the data.
Thanks

A: It's not possible to update the default ID column of a list in SharePoint online. ID field is an auto-increase column and it's read-only.
You could always recreate the list and add the items again in the proper order, or create a custom 'id' column to replace it.

A: I exported the list to excel. I added dummy items to excel until i match the number i needed then i imported the excel back and created a new list.
Thanks.


text:
Q: Sort listview for 2 conditions Can I sort my listview for 2 conditions at once?I have 4 lines:title,description,url of image and pinned.I must show records where pinned==true at the top,then I must sort for alphabeticaly title line,at show after pinned==true lines.How can I do that?MainActivity and Adapter put below.
MainActivity:
public class MainActivity extends ListActivity {
private Context context;
SqlHelper dbHelper;
    Intent intent;
    private static String url = "https://fierce-citadel-4259.herokuapp.com/hamsters";
    private static final String TITLE = "title";
    private static final String DESCRIPTION = "description";
    private static final String IMAGE = "image";
    private static final String PINNED = "pinned";

    ArrayList<HashMap<String,String>> jsonlist = new ArrayList<HashMap<String, String>>();
    ArrayList<HashMap<String,String>> bdList = new ArrayList<HashMap<String, String>>();
   ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActionBar actbar = getActionBar();
        actbar.setDisplayShowHomeEnabled(false);
        actbar.setDisplayShowTitleEnabled(false);
        actbar.setDisplayUseLogoEnabled(false);
        lv=(ListView) findViewById(android.R.id.list);
        LayoutInflater mInflater =LayoutInflater.from(MainActivity.this);
        View mcustomview = mInflater.inflate(R.layout.customactionbar, null);
        ImageButton imgbutt =(ImageButton)mcustomview.findViewById(R.id.actbarimagebutton);
        imgbutt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ProgressTask(MainActivity.this).execute();
            }

        });
        actbar.setCustomView(mcustomview);
        actbar.setDisplayShowCustomEnabled(true);
        if(isNetworkConnected()==true) {
            new ProgressTask(MainActivity.this).execute();
            ForItemClick();
        }
        else {
            try {
                dbHelper = new SqlHelper(MainActivity.this);
               WithoutInternetItemClick();
                imgbutt.setClickable(false);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            displaysavedlv();

        }

    }

    private class ProgressTask extends AsyncTask<String,Void,Boolean> {
        private ProgressDialog dialog;
        private ListActivity activity;
        private Context context;

        public ProgressTask(MainActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
            try {
                dbHelper = new SqlHelper(MainActivity.this);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        protected void onPreExecute(){
           this.dialog.setMessage("Progress start");
           this.dialog.show();
        }
        protected void onPostExecute(final Boolean success){
            try{
       if((this.dialog != null)&& this.dialog.isShowing()){
this.dialog.dismiss();
            }
if(isNetworkConnected()==true) {
    CustomListAdapter adapter = new CustomListAdapter(MainActivity.this, jsonlist, R.layout.list_item, new String[]{TITLE, DESCRIPTION}, new int[]{R.id.title, R.id.description});
    lv.setAdapter(adapter);
}else{
    displaysavedlv();
}

        }catch (final IllegalArgumentException e){e.printStackTrace();}
        }
        protected Boolean doInBackground(String... args) {

           JSONParser jParser = new JSONParser();
            JSONArray json = jParser.getJSONFromUrl(url);
            for(int i =0;i<json.length();i++) {
                try {
                    JSONObject c = json.getJSONObject(i);
                    String vtitle = c.getString(TITLE);
                    String vdescription = c.getString(DESCRIPTION);
                    String vimage = c.getString(IMAGE);
                    Boolean vpinned = c.getBoolean(PINNED);
                    dbHelper.open();
dbHelper.createEntry(vtitle, vimage, vdescription);

                    dbHelper.close();
                    HashMap<String, String> map = new HashMap<>();
                    map.put(TITLE, vtitle);
                    map.put(DESCRIPTION, vdescription);
map.put(IMAGE, vimage);
                    map.put(PINNED, String.valueOf(vpinned));
                    jsonlist.add(map);

                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            return null;
        }
    }

    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni == null) {
            // There are no active networks.
            return false;
        } else
            return true;
    }
    public void ForItemClick(){

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title1 = jsonlist.get(position).get("title");
                String description1 = jsonlist.get(position).get("description");
                String url1 = jsonlist.get(position).get("image");

                intent = new Intent(MainActivity.this, DetailInfo.class);

                intent.putExtra("title", title1);
                intent.putExtra("description", description1);
                intent.putExtra("url", url1);
                startActivity(intent);

    }
});
    };
    private void displaysavedlv(){
        bdList = dbHelper.getAllData();
lv=(ListView) findViewById(android.R.id.list);
        CustomListAdapter adapter1 = new CustomListAdapter(MainActivity.this,bdList,R.id.list_item,new String[]{TITLE,DESCRIPTION},new int[]{R.id.title,R.id.description});
        lv.setAdapter(adapter1);

    }
    public void WithoutInternetItemClick(){
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String title1 = bdList.get(position).get("title");
                String description1 = bdList.get(position).get("description");
                String url1 = bdList.get(position).get("image");
                intent = new Intent(MainActivity.this, DetailInfo.class);

                intent.putExtra("title", title1);
                intent.putExtra("description", description1);
                intent.putExtra("url", url1);
                startActivity(intent);
            }
        });

    }
}

Adapter:
public class CustomListAdapter extends SimpleAdapter {
    private static final String IMAGE = null;
private final Activity context;
private ArrayList<HashMap<String, String>> result;
    public CustomListAdapter(Activity context, ArrayList<HashMap<String, String>> data, int resource, String[] from, int[] to) {
        super(context,data,resource,from,to);
        // TODO Auto-generated constructor stub

this.result = data;
        this.context = context;
    }

    public View getView(int position,View view,ViewGroup parent) {
        LayoutInflater inflater=context.getLayoutInflater();
        View rowView=inflater.inflate(R.layout.list_item, null, true);

        ImageView imageView = (ImageView) rowView.findViewById(R.id.image);
TextView title = (TextView) rowView.findViewById(R.id.title);
        title.setText(result.get(position).get("title"));
TextView description = (TextView) rowView.findViewById(R.id.description);
        description.setText(result.get(position).get("description"));
String url = result.get(position).get("image");
          Picasso.with(context)
                .load(url).into(imageView);

        return rowView;

    }

}

A: extend Comparable to your object
over ride equals and compareto
@Override
public boolean equals(Object2 obj) {
    if (obj == null)
        return false;
    if (!(obj instanceof Messages))
        return false;
    Object1 u = (Object1) obj;

    return this.gettitle() == u.gettitle()
}

@Override
public int compareTo(Object2 obj) {
    return String.valueOf(this.title).compareTo(obj.title);
}

A: If i follow your question than you can do something like this.
You can even define the Comparators in the bean itself so that you can reuse them instead of recreating them everytime:
public class Contact {

    private String name;
    private String phone;
    private Address address;

    // ...

    public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.phone.compareTo(other.phone);
        }
    };

    public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.address.compareTo(other.address);
        }
    };

}

which can be used as follows:
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Sort by address.
Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);

// Sort later by phone.
Collections.sort(contacts, Contact.COMPARE_BY_PHONE);

more details you can see here.


text:
Q: Chromecast Receiver App error - Application was not found I subscribed to Receiver App and Published successfully. But when I call it, it returns the error "Application was not found". I use iOS Sender.
Below is my host URL: https://chromecast-test.000webhostapp.com/


text:
Q: .Net and SQL - Transactions with long running processes I have a method in .Net (v4.6 using Dapper), named BulkUpdate, that will modify several tables and can include around 10,000 rows or more. This operation can take a few seconds to a couple of minutes depending on the number of data being inserted. Since I will be updating multiple related tables I have to enclose all operations in a TransactionScope.
My question is what is the best way to avoid other read requests (outside the Transaction) from being "locked" or "wait" while my BulkUpdate method is in progress. Please, I do not want to add SET ISOLATION LEVEL READ_UNCOMMITTED to the beginning of every read, nor add NO LOCK hint...are there any other solutions?

A: Please use TASK concept in front end side C#, split 100 or 1000 rows to each task and run simultaneously. It may be use full for you. already i will improved my application performance using like this.
https://www.codeproject.com/Questions/1226752/Csharp-how-to-run-tasks-in-parallel


text:
Q: mysql average temperature of every day in a period I have a table with date and max temperature.
I'm trying to find the average max temperature of each day of the year given a period of years.
Ex. The average of tmax for 01-01 in the period of 1980 and 2013.
With the following query I found Tmax ordered as I want, but I can't find a way to group by each day.
$resultat = mysql_query ("SELECT data, Tmax FROM $estacio WHERE data between '1980-01-01' and '2013-12-31' group by day(data),year(data);");

    while($row = mysql_fetch_array($resultat)) {
      echo '
';
      echo '',$row[0],'	',$row[1],'	';
      echo '
';
    }

A: This should give you the average max temperatures per day over multiple years. Each row shows the day and month and the average temperature in the given period for that day.
SELECT
  DAY(data),
  MONTH(data),
  AVG(Tmax)
FROM $estacio
WHERE data BETWEEN '1980-01-01' AND '2013-12-31'
GROUP BY DAY(data), MONTH(data);

A: For finding the average surely you would need to use the function AVG().
Use it like
SELECT
DAY(data)
MONTH(data),
  AVG(Tmax)
FROM $estacio
WHERE data BETWEEN '1980-01-01' AND '2013-12-31'
GROUP BY DAY(data), MONTH(data);


text:
Q: EJB Transaction misunderstanding I am calling SLSB method which transaction controlled by container.
In method I am trying to remove entity and create new one
List<FactPlan> factPlans = factPlanFacadeLocal.findAll();

for (FactPlan factPlan : factPlans) {
    factPlanFacadeLocal.remove(factPlan);
}

FactPlan factPlan = new FactPlan(12264L, 12088L);
factPlanFacadeLocal.create(factPlan);

And I have following exception
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "pkfact_plan"
Detail: Key (fact_id, plan_id)=(12264, 12088) already exists.

What am I doing wrong?
UPD: JPA implementation is EclipseLink

A: Edit:
I was wrong in saying you need to commit, a flush is enough after your remove operations for ensuring the DB constraints are not violated.
What is happening (it is exactly the same for EclipseLink as well):
Hibernate is only seeing what is happening in memory inside the Persistence Context of your transaction, without flushing it is unable to validate DB constraints preemptively (primary key in this case).
While Hibernate is perfectly aware of you already removing the item with the same ID (since it all happened in the same Persistence Context), the DB isn't seeing any of your changes until the flush.
Now you would think that why isn't it enough to let the flush happen automatically when the transaction ends, before the commit? Surely the order of DB operations will be consistent with the JPA operations and the DB will see the row removal before the insert. Well it won't, Hibernate is changing the order of your operations and it puts all insertion before deletion breaking the DB constraint: http://docs.jboss.org/hibernate/orm/3.5/javadocs/org/hibernate/event/def/AbstractFlushingEventListener.html#performExecutions%28org.hibernate.event.EventSource%29


text:
Q: $_Get not working in this particular case I am trying to use
http://www.example.com/news/id/21/title/top-10-things/?page=1 for sending the page parameter and it is not working in php
below is my setting in the .htaccess file
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^news/(.*)/(.*)/(.*)/(.*)/$ /news.php?$1=$2&$3=$4
RewriteRule ^news/(.*)/(.*)/$ /news.php?$1=$2
RewriteRule ^news/$ /news.php

A: Try appending the %{QUERY_STRING} to the URLs in your htaccess.
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^news/(.*)/(.*)/(.*)/(.*)/$ /news.php?$1=$2&$3=$4&%{QUERY_STRING}
RewriteRule ^news/(.*)/(.*)/$ /news.php?$1=$2&%{QUERY_STRING}
RewriteRule ^news/$ /news.php&%{QUERY_STRING}

As Daniel noted, you can also use the mod_rewrite qsappend or QSA flag for this purpose. REF: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^news/(.*)/(.*)/(.*)/(.*)/$ /news.php?$1=$2&$3=$4 [QSA]
RewriteRule ^news/(.*)/(.*)/$ /news.php?$1=$2 [QSA]
RewriteRule ^news/$ /news.php [QSA]

A: Set the QSA flag to get the requested query automatically appended to the one in substitution URL:
RewriteRule ^news/(.*)/(.*)/(.*)/(.*)/$ /news.php?$1=$2&$3=$4 [QSA]
RewriteRule ^news/(.*)/(.*)/$ /news.php?$1=$2 [QSA]
RewriteRule ^news/$ /news.php [QSA]

Furthermore, you shouldn't use .* if you can be more specific. In this case using [^/]+ instead avoids unnecessary backtracking:
RewriteRule ^news/([^/]+)/([^/]+)/([^/]+)/([^/]+)/$ /news.php?$1=$2&$3=$4 [QSA]
RewriteRule ^news/([^/]+)/([^/]+)/$ /news.php?$1=$2 [QSA]
RewriteRule ^news/$ /news.php [QSA]

And for a general solution for an arbitrary number or parameters, see Rewriting an arbitrary number of path segments to query parameters.


text:
Q: Update screen on button click Django Say I have a screen that looks like this:
Times clicked: 0
[button]

And every time I click the button, the times clicked would increment by 1. How would I go about doing this?

A: You've tagged this question with django and django forms, so I'll ignore javascript based solutions and assume you want this to be persistent and universal (in that every user sees the same number).
assuming an app called count_things
start with count_things/models.py
from django.db import models

class Counter(models.Model):
    count_num = models.PositiveSmallIntegerField(default=0)
    name= models.CharField(max_length=255)

This is the model which will be instantiated in the database to store the number of clicks
run python manage.py makemigrations then python manage.py migrate to update the database with a table for this model
count_things/views.py
from django.http import HttpResponse
from django.shortcuts import render
def view_counter(request):
    counter = Counter.objects.get_or_create(name="page_counter")

    if request.method == "POST":
        counter.count_num = counter.count_num + 1
        counter.save()
    return render(request, "count_things/count_clicker.html" {"counter":counter})

This is the view that handles adding one to the counter when a form is submitted. We're not overly fussed about form validity because there are no fields in our form.
then in your
count_things/templates/count_things/count_clicker.html

 <form method="POST">
      {% csrf_token %}

times clicked: {{counter.count_num}}

     <input type="submit" value = "Add one to me!">
 </form>

This is the form itself. It's just a submit button in a form wrapper.
count_things/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.view_counter, name='view counter'),
]

urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("count_things.urls"))
]

Add urls to suit.  Here it should just be the first page of our website, with no filename or foldername,eg, http://127.0.0.1:80000
python manage.py runserver to start up your server, then visit your server url


text:
Q: Undefined property: View::$Js Getting this. Site works fine locally, but up on production server I get this error.
cakephp verion 1.3
Production: php 5.3.3-7+squeeze7
Dev: 5.3.3-7+squeeze3
Notice (8): Undefined property: View::$Js [APP/views/layouts/default.ctp, line 31]
Code | Context

include - APP/views/layouts/default.ctp, line 31
View::_render() - CORE/cake/libs/view/view.php, line 736
View::renderLayout() - CORE/cake/libs/view/view.php, line 494
View::render() - CORE/cake/libs/view/view.php, line 440
Controller::render() - CORE/cake/libs/controller/controller.php, line 909
ErrorHandler::_outputMessage() - CORE/cake/libs/error.php, line 458
ErrorHandler::missingComponentFile() - CORE/cake/libs/error.php, line 415
Object::dispatchMethod() - CORE/cake/libs/object.php, line 112
ErrorHandler::__construct() - CORE/cake/libs/error.php, line 125
Object::cakeError() - CORE/cake/libs/object.php, line 201
Component::_loadComponents() - CORE/cake/libs/controller/component.php, line 216
Component::init() - CORE/cake/libs/controller/component.php, line 78
Controller::constructClasses() - CORE/cake/libs/controller/controller.php, line 483
CakeErrorController::__construct() - CORE/cake/libs/error.php, line 52
ErrorHandler::__construct() - CORE/cake/libs/error.php, line 90
Object::cakeError() - CORE/cake/libs/object.php, line 201
Component::_loadComponents() - CORE/cake/libs/controller/component.php, line 216
Component::init() - CORE/cake/libs/controller/component.php, line 78

Fatal error: Call to a member function writeBuffer() on a non-object in /var/www/website.local/views/layouts/default.ctp on line 31

Line 31 is
echo $this->Js->writeBuffer(array('cache'=> true));

I have in app_controller.php
<?php

class AppController extends Controller {

        var $helpers = array('Html','Form','Session','Js','Javascript');
        var $components = array(
                        'Session',
                        'RequestHandler',
                        'DebugKit.Toolbar'
                );
}

?>

A: It looks like you are missing a component file:
ErrorHandler::missingComponentFile() - CORE/cake/libs/error.php, line 415

You may want to explore that error first, and then see if it fixes your other issue.


text:
Q: Can You help me to find a greedy algorithm for covering a line segment? The Question is :Given n segments of line (into the X axis) with coordinates [Li , Ri](coordinates could be negative numbers). You are to choose the minimum number of segments that cover the whole segment [0 , M].
And Here What I did: Actually I've Sorted the segments by their starting coordinates (Li) in increasing order. Then Selected the segments starting with the smallest Li and then selected the Largest one.
but my algorithm does not work for some instances. Do You Guys Have any other idea for this problem ? please give me some hints for solving this problem.

A: First remove the segments havingR < 0. Among the remaining segments, you must select at least one segment such that L <= 0 <= R. There is no loss in selecting the segment with the largest R among the segments having L <= 0.
Rinse and repeat with [R, M] instead of [0, M].

A: *

*Sort the segments by increasing Li.

*Let L= 0, the leftmost abscissa to be covered.

*Scan the list as long as Li <= L, while remembering the segment with the largest Ri.

*Set L= Ri and continue the scan (3) where you left it, unless the list is exhausted.
The invariant of the main loop says "the segments already scanned minimally cover [0, L], and the remaining segments cover [L, M] (though not minimally)".

A: I am posting a python solution to this problem.
def calculateOptimizedPoint(numOfCordinates, cordinates):
     sortedCordinate = sorted((cordinate for cordinate in cordinates), key = lambda itm:itm[0])
     points = []
     currentRange = sortedCordinate[0][1]
     points.append(currentRange)
     for i in range(numOfCordinates-1):
         if (currentRange < sortedCordinate[i][0]) or currentRange > sortedCordinate[i][1]):
              currentRange = sortedCordinate[i][1]
              points.append(currentRange)
     return points

numOfCordinates = int(input("How many coordinate you want to input : "))
cordinates = [(int(input("Enter the a{} cordinate".format(i))),int(input("Enter the b{} cordinate".format(i)))) for i in range(numOfCordinates)]

print(calculateOptimizedPoint(numOfCordinates,cordinates))


text:
Q: Как сделать перенаправление на загружаемый файл? (загрузка файла по любому имени обращения) Имеется директория с файлом files/default.txt.
Файл загружается с сервера (в моем случае localhost) по ссылке readme
Пытаюсь с помощью .htaccess реализовать загрузку файла default.txt при любом обращении к директории, в том числе по несуществующему имени файла, например, readme.txt:
.htaccess
RewriteEngine On
RedirectMatch "files/(.*\.txt)$" "http://localhost/files/$1"

и получаю ошибку загрузки: Ошибка: Ошибка сети.
Прошу подсказать, что нужно исправить и почему ошибка.

A: вместо .htaccess в корне сайта добавить такой .htaccess в папку files:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /files/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . default.txt [L]
</IfModule>


text:
Q: Norwegian keyboard / Writing in english I have my keyboard Language set to Norwegian (3 extra letters of the alphabet). When writing in English the first letter of the words (not all - but lots) change to a capitol letter - why??  Many may say - well just change the keyboard to English when writing English, but then I would have to re-learn where all the keys are (e.g: @ ? ' ( ) =  and so on)

A: The simplest solution would be to buy a USB English keyboard and have both Norwegian and English connected at the same time and just switch keyboards when needed


text:
Q: Using a Normal For Loop with CSV (Import-CSV) I am working on a PowerShell script that will import a CSV file containing server information (including server name, instance, status, and database names) using the Import_Csv cmdlet. After importing the file, the script will loop through the file, connect to each server/instance, and add a user to each database.
What I am trying to figure out is how to be able to use a normal FOR loop within the script instead of a FOREACH loop. I want to limit the number of times I have to connect to each server by looping through the list of servers/databases. What I want to check is if the current server/instance is the same as the next server/instance in the file, keep the connection open. For example, if I have the following data in the file:
server1,instance1,online,database1
server1,instance1,online,database2
server2,instance1,online,database1
server2,instance1,online,database2

When I am looking at the data on the first line, before closing the connection to server1\instance1, I want to check if the same data is on the second line so that I do not have to close the current connection and then reconnect to the same server a moment later.
My question is, is there a way to access the next element of a CSV file in PowerShell within the FOREACH loop, or should I use a FOR loop? If I use a FOR loop instead, what is the best way to access each field?
Here is what I currently have with comments in the foreach loop of what I would like to happen:
Param(
    [Parameter(Mandatory=$true,position=0)]
    [string]$serverListFilePath = $( Read-Host "Server List File Path: " )
)

Write-Host "File path: $serverListFilePath"
$serverListArray = Import-Csv -Path $serverListFilePath # Import the server list CSV file and store it into a CSV object
#$serverListArray

foreach ($item in $serverListArray) # Basically all the substance/work of this script is going to be done in this loop since it needs to go through each server in the file one-by-one
{
    Try
    {
        $serverNameCSV = $item.server_Name
        $serverInstanceCSV = $item.Server_Instance
        $serverStatusCSV = $item.Server_Status
        $databaseNameCSV = $item.Database_Name

        # If no connection to server
             # Create connection to server/instance
        # Run SQL queries
        # If (<current server\instance> -ne <next server\instance>)
             # Close connection to server/instance
             # continue
        # else
             # continue

    } # End Try
# Catch

Any ideas on how to go about this will be much appreciated.

A: Instantiate the server name variable outside of the for/foreach loop. Every time your program loops, compare the new value against the old value and if the values are different, reassign and connect to the new server.
I would also advise sorting the incoming data by server so you can limit the amount of times you need to repeatedly connect to the same data source.

A: Example of how to loop through a CSV using a For loop:
$serverListArray = Import-Csv -Path $serverListFilePath
#will loop until $x is no longer less than 10
for ($x=0;$x -lt 10; $x++)
{
    #call property by index
    $serverListArray[$x].Server_name
    $serverListArray[$x].Server_instance
    #etc...
}

A: You can keep a reference to previous server name and previous connection.
Then check the previous server name with current server name. If its different then close the previous connection (if anything is open).
Also, after the foreach loop check if the previous connection is open, if yes, close it. This will be the connection to the last server.


text:
Q: Issue with Search service account SharePoint 2013 ISSUE:
Using built-in accounts like Network Service or Local System as application pool or as service identities is not supported in a farm configuration.  The following services are currently running as built-in identities on one or more servers: OSearch15(Windows Service)

INFORMATION:
All the search service accounts are set to the domain/sharepointsearch account and all four servers are showing the same account being used for the running windows service.
What would cause this error to continue to pop up with the correct account being used everywhere?
Is there a script I can run that would double check or force SharePoint to recognize that the correct account is in fact being used?

A: This service is not configured to use your domain\sharepointsearch account by default and will run as a local account instead.
You can use the following PowerShell to set this account to the user account you want to use:
$service_user = "domain\sharepointsearch"
$service_password = (ConvertTo-SecureString -String "MyComplexPassword" -AsPlainText -force)
Set-SPEnterpriseSearchService -ServiceAccount $service_user -ServicePassword $service_password


text:
Q: How to get current page in angular datatable I follow this library https://l-lin.github.io/angular-datatables/archives/#!/serverSideProcessing to create a server-side processing datatable. It works very well but may I know how to get current page?
 var vm = this;
        vm.dtOptions = DTOptionsBuilder.newOptions()
            .withOption('ajax', {
                // Either you specify the AjaxDataProp here
                url: 'api/bank_recon/fetch_trx',
                type: 'POST',

            })
            .withDataProp('data')
            .withOption('processing', true)
            .withOption('serverSide', true)
            .withPaginationType('full')

A: You can use drawCallback function to get page information , you can assign that value to scope by using javascript angular element selector methods.
 vm.dtOptions = DTOptionsBuilder.newOptions().
                    .withOption('drawCallback', function(settings) {
                          if(settings.aoData.length > 0) {
                            var api = this.api();
                            var pgNo = api.page.info();
                            var currPg = pgNo.page;
                            var totalPg = pgNo.pages;

                            var scope = angular.element($("#outer")).scope();
                            scope.$apply(function(){
                               scope.currentpage = currPg;
                            })
                          }
                     })
                });


text:
Q: Index/Match returning wrong value Summary tab:

Source tab:

I'm having some trouble using index match combo and getting the data to reference correctly.
what I am trying to achieve is in a tab called "Summary" I have a calendar with range D5:O6. the first cell in the calendar should change everyday to reflect the current date which will change the rest of the row making a rolling calendar. I have a data reference sheet called "PFS" from which the data needs to be referenced.
The thing I'm having trouble with is that with the formula
=INDEX(PFS, MATCH(A8,Snames,0),MATCH(D5,Sdates,0))
is returning the top left intersection (B8 of the source tab) of A8 and D5 values smith, bob & 4-Aug. a cell that i have entered the value "Wrong Corner".
Snames A8:A9, Sdates D5:O5 are the rows and columns containing the dates and names from the Summary tab
what I need help with is why its returning the wrong intersection and what I can do different to get the data I'm looking for.
The correct return would be the number one, which I have conditionally formatted to turn the cell blue and blank the text

A: You don't show what PFS references to. It seems to start in A1.
You can either use a range that starts in the correct cell, or add the required offset to the Match results.
=INDEX(PFS, MATCH(A8,Snames,0)+2,MATCH(D5,Sdates,0)+2)

Also make sure that Sname and Sdates refer to the ranges in the Source tab, not the Summary tab.


text:
Q: How do you run multiple unique instances of debounce at the same time? I'm using debounce (but am willing to use another module) with MongoDB change streams to prevent a function from being called multiple times when there are many updates to the DB at once.  It works great except for when there are multiple users making changes to the DB, then debounce is only called on the last change.
I need a way to pass an id value to debounce so that there can be multiple versions running at the same time.
This is what is currently happening:
debounce(()=>console.log("ID A"), 500); // debounce is called for ID A
debounce(()=>console.log("ID B"), 500); // debounce is called for ID B
debounce(()=>console.log("ID B"), 500); // debounce is called for ID B

// output:
ID B // "ID A" is never returned because it is replaced by "ID B"

This is what I'm wanting to do:
debounce("ID A", ()=>console.log("ID A"), 500); // debounce is called for ID A
debounce("ID B", ()=>console.log("ID B"), 500); // debounce is called for ID B
debounce("ID B", ()=>console.log("ID B"), 500); // debounce is called for ID B

// output:
ID A
ID B

Does that make sense?  How can I implement that?
Example code
function sleep(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

const debouncePool = {};
function debounceById(id) {
    console.log(`debounceById(${id})`);
    if (!debouncePool[id]) {
        debouncePool[id] = debounce(() => {
            console.log(id);
        }, 100);
    }
    debouncePool[id]();
}

debounceById("123");
await sleep(150);
debounceById("123");
debounceById("AAA");
debounceById("123");

// Output:
debounceById(123)
123
debounceById(123)
debounceById(AAA)
debounceById(123)
123 // AAA should return first
AAA // 123 should return second

it should be:
// Output:
debounceById(123)
123
debounceById(123)
debounceById(AAA)
debounceById(123)
AAA
123

A: I switched to using just-debounce-it and it works great now:
import debounce from "just-debounce-it";

function sleep(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

const debouncePool = {};
function debounceById(id) {
    console.log(`debounceById(${id})`);
    if (!debouncePool[id]) {
        debouncePool[id] = debounce(() => {
            console.log(id);
        }, 100);
    }
    debouncePool[id]();
}

debounceById("123");
await sleep(150);
debounceById("123");
debounceById("AAA");
debounceById("123");

//
// Output:
//
debounceById(123)
123
debounceById(123)
debounceById(AAA)
debounceById(123)
AAA
123


text:
Q: Refreshing a ClientDataSet nested in a DataSetField I've nearly finished some code to solve the problem in this unanswered q from last year:
Refresh Nested DataSet with poFetchDetailsOnDemand
Received wisdom is that it's not possible to refresh the nested detail CDS from the server without closing and re-opening the master CDS, but obviously that can generate a disproportionate amount of network traffic, just to refresh a single master row and its detail rows.
I thought of a straightforward way to refresh the detail CDS
from the server and it nearly works.  My code below basically does a detail refresh by temporarily
applying a filter to the master ADO query to filter it down to the current master row and, while that filter is in effect,
refreshing the master CDS by applying a similar filter to it and then calling its Refresh method. This is triggered by the master CDS AfterScroll event.
There is just one teeny problem: On my form,as well as the 4 datasets and accompanying grids, I have a Refresh button on the form that calls my RefreshcdsMasterAndDetails that's
also called in cdsMasterAfterScroll.  If I move around the master CDS using its grid, my code all works fine, and the detail CDS rows correctly update immediately, along with those in the AdoQuery detail <>but if I trigger it by clicking the Refresh button, the CDS detail rows only update every second time I click the Refresh button.
My question is: Why should there be any difference in the effect of my code when it's triggered from a button click rather than from the AfterScroll event, in as much as it reliably does what it's supposed to do called from the AfterScroll event but only every other time when triggered by a button click?
//Obviously MasterPKName below is a const and DoingRefresh is a boolean
// flag on the form

procedure TForm1.cdsMasterRowRefresh(MasterPK : Integer);
begin
  if DoingRefresh then Exit;

  DoingRefresh := True;

  try
    cdsMaster.Prior;
    cdsMaster.Next;
    cdsMaster.Filter := MasterPKName + ' = ' + IntToStr(MasterPK);
    cdsMaster.Filtered := True;
    cdsMaster.Refresh;
    cdsMaster.Filtered := False;

    cdsMaster.Locate(MasterPKName, MasterPK, []);

  finally
    DoingRefresh := False;
  end;
end;

procedure TForm1.qMasterRowRefresh(MasterPK : Integer);
begin
  qMaster.Filter := MasterPKName + ' = ' + IntToStr(MasterPK);
  qMaster.Filtered := True;
  qMaster.Refresh;

  cdsMasterRowRefresh(MasterPK);

  qMaster.Filtered := False;
  qMaster.Locate(MasterPKName, MasterPK, []);
end;

procedure TForm1.RefreshcdsMasterAndDetails;
var
  MasterPK : Integer;
begin
  MasterPK := cdsMaster.FieldByName(MasterPKName).AsInteger;

  cdsDetail.DisableControls;
  cdsMaster.DisableControls;
  qDetail.DisableControls;
  qMaster.DisableControls;

  try
    qMasterRowRefresh(MasterPK);
  finally
    qMaster.EnableControls;
    qDetail.EnableControls;
    cdsMaster.EnableControls;
    cdsDetail.EnableControls;
  end;
end;

procedure TForm1.cdsMasterAfterScroll(DataSet: TDataSet);
begin
  RefreshcdsMasterAndDetails;
end;

A: Despite a lot of careful observation and debugging, I still don't have a satisfying explanation of exactly why my CDS refreshing code
behaves differently if called in the master CDS's AfterScroll event, where the
detail CDS always gets updated correctly, and in a ButtonClick handler where
the detail CDS only gets updated every second click.  I imagine that it's something
to do with the fact that the master CDS's cursor has already moved by the time
the AfterScroll handler is called, unlike the situation where I click the button.
However, I have found a simple work-around and a fix.
The work-around is simply not to call DisableControls on the 4 datasets before
doing the refresh.  Then the detail CDS always gets refreshed correctly.  Any other
permutation of disabling some or all the datasets results in the difference my q is about.  I don't like this work-around though, because the cdsMaster DBGrid has to scroll all the way through the data, just ti refresh one master row + its details.
The fix is to do something that on reflection I should have done in the first place, namely to force
a refresh of the detail ADO query (with my data, simply calling its Refresh, which was my first attempt
at a fix, provokes the familiar Ado error "Insuffient key column information
for updating ..." despite the detail table having a PK on the server).
So, here's the fix:
procedure TForm1.qMasterRowRefresh(MasterPK : Integer);
begin
  try
    qMaster.Filter := MasterPKName + ' = ' + IntToStr(MasterPK);
    qMaster.Filtered := True;

    qMaster.Refresh;

    //  Do NOT omit the next 3 lines, needed to ensure that the detail query
    //  and hence the detail CDS, is refreshed

    qDetail.Parameters.ParamByName(MasterPKName).Value := MasterPK;
    qDetail.Close;
    qDetail.Open;

    cdsMasterRowRefresh(MasterPK);

  finally
    qMaster.Filtered := False;
    qMaster.Locate(MasterPKName, MasterPK, []);
  end;
end;

As I got into this by looking into an earlier unanswered SO question, I'll be
transplanting an updated version of the code to an answer to that one.


text:
Q: Using global properties outside vue components - Vue 3 I have custom service instances created in main.ts
app.config.globalProperties.$service1 = new Service1();
app.config.globalProperties.$service2 = new Service2();

I can use these instances inside vue components but I want to be able to use them in some utility files.
In vue 2 it was like:
import Vue from "vue";
Vue.prototype.$service1.someMethod("foo");

The only option that worked for me is to export the app instance in main.ts and importing it in my utility files but that did not look right.
What is the equivalent of Vue.prototype in Vue 3?
How to keep it singleton and still use the instances outside vue components?

A: There are no good reasons for this code to be written in main.ts, then there won't be a necessity to get service instance frome a place it doesn't belong to.
With the benefits of modular JS, service instance can be defined in a module:
export default new Service1();

Then the service is imported in every module it's used:
import service1 from '.../service';

It's unnecessary to expose it to all component instances like it's done with Vue.prototype, the latter is the remnant of non-modular Vue that used Vue variable as global namespace. Currently the exposure of global dependencies through app.config.globalProperties is only needed for those that are supposed to be used in component templates, e.g. filters.


text:
Q: How to install oct2py on windows? I want to install oct2py in python. I am using windows 8.1
I used the command easy_install oct2py and I installed octave with the standard exe file.
Now according to the  installation guide I should add the octave path.
setx PATH "%PATH%;<path-to-octave-bin-dir>

I did not understand this command. I tried to add the path where is the octave.exe file to the environmental variables.
But when I try to import oct2py I get an error.
>>> import oct2py

Please install GNU Octave and put it in your path

>>>

Can anyone please explain me exactly how to set the path?
An example of the command that I should run on the terminal would be very useful.
Thanks
EDIT:
I tried
setx PATH "%PATH%;C:\Software\Octave-3.6.4\bin"

but I received a strange message:
WARNINGS: The data being saved is truncated to 1024 characters
SUCCESS: Specified value was saved

A: I'm not personally familiar with Octave, but it seems I've helped resolve this question. For others who may stumble upon this issue in the future, here's the process that led to the solution:

Given the error Please install GNU Octave and put it in your path, I searched the source code and found this from _utils.py:
try:
    cmd = 'octave -q --braindead'
    session = subprocess.Popen(cmd, shell=True,
                             stderr=subprocess.STDOUT,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             preexec_fn=os.setsid)
except OSError:
    octave_path = glob('c:/Octave/*/bin/octave.exe')[0]
    if not os.path.exists(octave_path):
        msg = ('Please install Octave at "c:/Octave" '
                 '  or put it in your path:\n'
                 'setx PATH "%PATH%;<path-to-octave-bin-dir>"')
        raise Oct2PyError(msg)
    else:
        cmd = 'octave -q --braindead'
        session = subprocess.Popen(cmd, shell=True,
                             stderr=subprocess.STDOUT,
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             preexec_fn=os.setsid)
except OSError:
    raise Oct2PyError('Please put the Octave executable in your PATH')
return session

So this is raised when the command octave -q --braindead is attempted and fails

Next I asked OP whether the command ran properly on the command line, in order to isolate the problem. Running that, OP learned :MSYS shell available C:\Software\Octave-3.6.4\msys
Including that in the path is the solution
tl;dr
Path should not just be
C:\Software\Octave-[version]\bin
but rather
C:\Software\Octave-[version]\msys


text:
Q: Why does my Node.js gRPC client take 3 seconds to send a request to my Python gRPC server? Let's begin by acknowledging that I am a gRPC noob. If I've asked a stupid question, go ahead and let me know, but only after explaining why it's stupid. Thanks! :)
Overview
I am developing an application that processes images. The variables that affect the result of the processing are to be changeable by the user. I wanted to provide a good-looking GUI while maintaining cross-platform compatibility. Thus, I decided to implement my image processing in Python, and use Node.js and Electron for my GUI.
Needing a way to send and receive data to and from my Python backend, I decided to use gRPC. Thus I have a Node.js gRPC Client paired with a Python gRPC Server.
After reading through many tutorials and learning a bit about protocol buffers, I was able to successfully transfer data between the two programs.
The Setup
The Node.js Electron app takes input from the user, and sends a request to the Python backend. The size of the request is a small object:
// From My Protocol Buffer
message DetectionSettings {
    float lowerThreshold = 1;
    float upperThreshold = 2;
    float smallestObject = 3;
    float largestObject  = 4;
    float blurAmount     = 5;

    int64 frameNumber    = 6;
    string streamSource  = 7;
}

Upon receiving this request, the Python application reads a frame from the specified streamSource and processes it. This processed frame is then converted to JPEG format and returned via gRPC to the Node.js app as an Image:
// From My Protocol Buffer
message Image {
    bytes image_data = 1;
    int32 height = 2;
    int32 width = 3;
    int64 frame = 4;
}

The Problem
I've noticed that there is a variable latency between the time the request is made and the image is received. This time varies from a few ms up to nearly 3 SECONDS! After profiling the Python code, I've determined that the processing time is negligible. In addition, the time that it takes to return the Image via gRPC is also negligible.
Thus there is an intriguing delay between the RPC execution and the Python application receiving the call. Here are some logs with the times to better explain what's happening (The number in brackets is in seconds):
/* Node.js */
[160408.072] "Sending Request..."
[160408.072] "Executing RPC"
[160408.072] "RPC Executed"

/* Python */
[160411.032] [ py-backend ] Getting frame

/* Node.js */
[160411.617] "Got Data"

You can see that in this case the time from Node.js RPC execution to the Python method being called was around 3 seconds, while the time from the execution of the Python method to the Node.js application receiving the Image is less than 1 second 0.o
The Code
Python gRPC Server
# Create the server
server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

# Add our service to the server
processor_pb2_grpc.add_ProcessorServicer_to_server(
    ProcessorServicer(), server
)

server.add_insecure_port('[::1]:50053')
server.start()
server.wait_for_termination()

Node.js Client:
const grpc = require('grpc')
const PROTO_PATH = '../processor.proto'

const serviceConfig = {
    "loadBalancingConfig": [ {"round_robin": {} } ]
}
const options = {
    'grpc.service_config': JSON.stringify(serviceConfig)
}

const ProcessorService = grpc.load(PROTO_PATH).Processor
const client = new ProcessorService ('[::1]:50053',
    grpc.credentials.createInsecure(), options);

module.exports = client

Protocol Buffer:
syntax = "proto3";

message Number {
    float value = 1;
}

message Image {
    bytes image_data = 1;
    int32 height = 2;
    int32 width = 3;
    int64 frame = 4;
}

message DetectionSettings {
    float lowerThreshold = 1;
    float upperThreshold = 2;
    float smallestObject = 3;
    float largestObject  = 4;
    float blurAmount     = 5;

    int64 frameNumber    = 6;
    string streamSource  = 7;
}

service Processor{
    rpc GetFrame(DetectionSettings) returns (Image) {};
}

Node.js gRPC Call:
function GetFrameBytes(detectionSettings, streamSource, frameNumber, callback)
{
    detectionSettings["streamSource"] = streamSource;
    detectionSettings["frameNumber"] = frameNumber;

    client.GetFrame(detectionSettings, (error, response) =>
    {
        if(!error){
            callback(response)
        }
        else
        {
            console.error(error);
        }
    });
}

tl;dr
Why on earth does it take so long for my Node.js client request to trigger my Python code?

A: There are a couple of factors that could be impacting the long time you are seeing.
First, the first request made by a client always takes longer because it has to do some connection setup work. The general expectation is that a single client will make many requests, and that the setup time will be amortized over all of those requests.
Second, you mentioned that you are using Electron. There have been some reports of gRPC for Node performing poorly when used in the Electron rendering process. You may see different results when running your code in the main process, or in a regular Node process.
You may also have different luck if you try the package @grpc/grpc-js, which is a complete reimplementation of the Node gRPC library. The API you are currently using for loading the .proto packages does not exist in that library, but the alternative using @grpc/proto-loader works with both implementations, and the other APIs are the same.


text:
Q: cannot open session with QuickBooks I am trying to open session and add some records to QB, but it does not seem to do anything and does not open session.
Code:
QBFC13Lib.QBSessionManager sessionManager = new QBFC13Lib.QBSessionManager();
//or
QBSessionManager sessionManager = new QBSessionManager();

I tried both.
Installed QBSDK13 and added reference Interop.QBFC13 and namespace QBFC13.
No success so far. Please help me with some examples or advice. Thanks.

A: Just creating a new session manager does not make a connection to QuickBooks or a QuickBooks data file. You need to call OpenConnection2 and BeginSession on the QBSessionManager object.
QBSessionManager sessionMananger = new QBSessionManager();
sessionMananger.OpenConnection2("AppID", "AppName", ENConnectionType.ctLocalQBD);
sessionMananger.BeginSession("QBFile", ENOpenMode.omDontCare);

You'll want to replace AppID and AppName with string values for your app. This is what gets presented to the QB User to grant access. The QBFile string is the file that you want to open. Leave this as a blank string to start a session with the currently opened QB file. If QuickBooks is not currently running or logged into a file, you must supply the file name.
The QBSDK Programmer's Guide that gets installed when you install the SDK has all this information. The connection information starts on page 45.

A: I was also getting errors with the session manager. Make sure your are building against x86. The COM libraries are 32-bit.


text:
Q: Expand ( transform ) some of the hive columns as row (record) Is there a efficient way to transform the below hive table with shown target transformation. The column count in the source table is ~ 1500.
Using spark 2.0, source and target as dataframes.
(id,   dt ,       source1_ColA, source1_ColB, source2_ColA, source2_ColB)
------------------------------------------------------------

(10,"2018-06-01",   10,             9,          5,          8       )

(20,"2018-06-01",   20,             12,         16,         11      )

The columns A,B are transformed as shown below
Target table
(id, dt ,   element_name,  source1,  source2 )
---------------------------------------

(10,"2018-06-01",   ColA    ,     10    ,   5       )

(10,"2018-06-01",   ColB    ,      9    ,   8       )

(20,"2018-06-01",   ColA    ,     20    ,   16      )

(20,"2018-06-01",   ColB    ,     12    ,   11      )


text:
Q: Copy constructor for derived class from base pointer I have looked all around and can't find the answer to my question anywhere. I am trying to use a copy constructor of a derived class from a pointer array of base classes. The only thing I have learned is I should probably use dynamic_cast but cant get that working.
This is the important parts of my code so far (original is way to big since I have 16 different files but this should be enough).
EDIT: The error I receive doing it this way is |26|error: cannot dynamic_cast '& properties[0]' (of type 'class Property**') to type 'class Commercial*' (source is not a pointer to class)|
#include "rentals.h"
#include "commercial.h"
#include "sales.h"
#include "comSales.h"
#include "resSales.h"
#include "resRentals.h"
#include "comRentals.h"

const int MAX_PROPERTIES = 5;

int main(void) {
   int i;

   Property *properties[MAX_PROPERTIES];

   properties[0] = new Commercial("Notting Hill McDonalds", "4 Gardiner Road",
                                  "Notting Hill", 5000, "Li3000");

   properties[1] = new ResRentals("Janet Dalgleish", "30 Firhill Court",
                           "Mary Hill", 4000, 500.00, 300.00, 4);

   properties[2] = new Commercial(dynamic_cast<Commercial*>(properties[0]));  // <-- the copy constructor I can not get to work.

   delete[] properties;

   return 0;
}

commercial.cpp file
#include "property_a.h"
#include "commercial.h"

Commercial::Commercial() : Property() {
   owner = "NULL";
   address = "NULL";
   suburb = "NULL";
   postcode = 0;
   license = "NULL";
}

Commercial::Commercial(string theOwner, string theAddress,
                        string theSuburb, int thepostCode,
                        string theLicense): Property(theOwner, theAddress,
                        theSuburb, thepostCode), license(theLicense) {}

Commercial::~Commercial() {}

Commercial::Commercial(const Commercial& orig) : Property(orig),
                        license(orig.getLicense()) {}

void Commercial::print() {
   cout << getOwner() << endl;
   cout << getAddress() << endl;
   cout << getSuburb() << endl;
   cout << getPostcode() << endl;
   cout << getLicense() << endl;
}

commercial.h file
#ifndef __COMMERCIAL_H__
#define __COMMERCIAL_H__

#include "property_a.h"

class Commercial :  public virtual Property
{
protected:
  string license;

public:
  Commercial();
  Commercial(string theOwner, string theAddress, string theSuburb,
              int thepostCode, string theLicense);

   ~Commercial() ;

   Commercial(const Commercial& orig);

  void input() ;   // Data input for a Shop object
  void print() ;  // Data output for a Shop object

  string getLicense() const {return license;};   //Note the use of const

  void setLicense(string theLicense) {license = theLicense;};

};

property_a.cpp file
#include "property_a.h"

Property::Property(){
   owner = "NULL";
   address = "NULL";
   suburb = "NULL";
   postcode = 0;
}

Property::Property(string theOwner, string theAddress,
                   string theSuburb, int thepostCode):
                     owner(theOwner), address(theAddress),
                     suburb(theSuburb), postcode(thepostCode){}

Property::~Property() {}

Property::Property(const Property& orig) :
                     owner(orig.getOwner()), address(orig.getAddress()),
                     suburb(orig.getSuburb()), postcode(getPostcode()) {}

property_a.h file
#ifndef __PROPERTY_A_H__
#define __PROPERTY_A_H__

/*TODO  REQUIRED HEADER FILES AND NAMESPACES*/
#include <string>
#include "utility1.h"

class Property
{
protected:
  string owner;
  string address;
  string suburb;
  int postcode;

public:
  Property();
  Property(string theOwner, string theAddress, string theSuburb, int thepostCode);
  virtual ~Property();
  Property(const Property& orig);
  virtual void input() ;   // Data input for a Property object
  virtual void print() ;  // Data output for a Property object

  string getOwner() const {return owner;};   //Note the use of const
  string getAddress() const {return address;};
  string getSuburb() const {return suburb;};
  int getPostcode() const {return postcode;};

  void setOwner(string newOwner) {owner = newOwner;};
  void setAddress(string newAddress) {address = newAddress;};
  void setSuburb( string  newSuburb) {suburb = newSuburb;};
  void setPostcode(int  newPostcode) {postcode = newPostcode;};
};
#endif

I hope this is enough details

A:
properties[2] = new Commercial(dynamic_cast(properties[0]));  // <-- the copy constructor I can not get to work.

This is casting properties[0] to Commercial*. But this isn't the signature of your copy constructor. Therefore, you need new Commercial(*dynamic_cast<Commercial*>(properties[0]));.
In this example you could use static_cast<Commercial&>(*properties[0]) since you know properties[0] is a Commercial type.
However, in general if you're using dynamic_cast it probably means you're not sure what the derived type is and you would need to check for NULL (i.e., the cast failed) before dereferencing.
Alternative
You could consider a polymorphic API to take care of this for you.
class Base
{
public:
    virtual ~Base() = default;
    Base* clone() const = 0;
};

class D1 : public Base
{
public:
    virtual ~D1() override = default;
    D1* clone() const { return new D1(*this); }
};

class D2 : public Base
{
public:
    virtual ~D2() override = default;
    D2* clone() const { return new D2(*this); }
};

int main()
{
    std::unique_ptr<Base> b1(new D2());
    std::unique_ptr<Base> b2(b1->clone());

    return 0;
}

A: It would be nice to see the errors but it looks like you aren't calling the copy constructor at all:
new Commercial(dynamic_cast<Commercial*>(properties[0]));

is like calling
Commercial(Commercial * other);

so you need
new Commercial(*dynamic_cast<Commercial*>(properties[0]));


text:
Q: Not able to display value of a element through button click of my extension I have account with www.makemytrip.com and where 'from' field and 'to' field is already saved through cookies
Using extension, I would like to display the value present in 'from' field of that site. (whose id is 'hp-widget__sfrom')
On page load I am able to view the value but the same I can't achieve on click on my button defined in my extension
Below is the code: index.html
<html>
  <head>
      <title>My new extension</title>
  </head>
  <body>
     <input type="button" id="save" value="Save Text">
  </body>
</html>

manifest.json
{
  "manifest_version": 2,

  "name": "Test1",

  "description": "TestDesc",

  "version": "1.0",

  "background": {
  "scripts": ["background.js"]
  },

 "permissions": [
 "activeTab"
  ],

  "browser_action": {
  "default_icon": "icon.png",
  "default_popup": "index.html",
  "default_title": "Test11"
  },

 "content_scripts": [
 {
  "matches": ["http://*/*", "https://*/*"],
  "js": ["myContentScript.js"]
 }
  ]
}

myContentScript.js
window.onload = function(){
  alert("Hi by contentScript");
  //alert(document.getElementById('hp-widget__sfrom').value); //this works!
  //but the below doesn't work; onclick of button
  document.getElementById('save').onclick = function(){
    alert(document.getElementById('hp-widget__sfrom').value);
  }
}

background.js
window.onload = function(){
   alert("Hi by backgroundJS");
}

I appreciate any sort of help!


text:
Q: array_search returns NULL/blank I have such array
<?php
$a = array(
    "apple"=>"uniqid1",
    "apple"=>"uniqid2",
    "apple"=>"uniqid3",
    "bannana"=>"uniqid4"
    );

echo array_search("uniqid1", $a, true);

?>

When I search for "uniqid4" it returns "bannana" (all good)
But when I search for "uniqid1" it returns blank/NULL (I know there are duplicates - but array is as it is)
My question is :
How to search for "uniqid1" or "uniqid2" or "uniqid3" and get "apple" everytime?
based on first to answers:
If i reverse array:
$a=array(

"uniqid1"=>"apple",
"uniqid2"=>"apple",
"uniqid3"=>"apple",
"uniqid4"=>"bannana");

how to search uniqid3or uniqid2 or uniqid1
echo array_search("uniqid3",$a, true);

and get apple everytime?

A: You can not use the same index multiple times. Defining it multiple times will overwrite the value at that index, which leads to only the last value that is assigned (uniqid3 in this case) still remaining.
You can check this like so:
$a=array(

"apple"=>"uniqid1",
"apple"=>"uniqid2",
"apple"=>"uniqid3",
"bannana"=>"uniqid4");

var_dump($a);

And you will see there are actually only two entries:
array(2) {
  ["apple"]=>
  string(7) "uniqid3"
  ["bannana"]=>
  string(7) "uniqid4"
}

If you flip the values (use the values as keys and vice versa) this would work fine and you could search for apple then.

A: this is your array
$a=array(
"apple"=>"uniqid1",
"apple"=>"uniqid2",
"apple"=>"uniqid3",
"bannana"=>"uniqid4");

it is exactly like this array:
$a=array(
"apple"=>"uniqid3",
"bannana"=>"uniqid4");

you are overwriting "apple" 2 more times.
so it's logical if you search for uniqid1 and uniqid2 you will get null, but if you search for uniqid3 and uniqid4 you will get an answer.
after you defined an array, you give "apple" => "uniqid1" but in the next line, you overwrite it an give "apple" another value, "apple" => "uniqid2"
after that you give third value to "apple" again "apple" => "uniqid3"
so "apple" has this value: "uniqid3"
so "uniqid1" and "uniqid2" do not exist in your array any more.

A: As ArSeN said, you cannot use the same apple index multiple times. In doing so, PHP will understand that only the third exists, the first two will be ignored because they use the same key.
Maybe there is a way to make this work, and it would be by changing keys and values, then keys would become values.
The code would look like this:
<?php

$array = array(
    'uniqid1' => 'apple',
    'uniqid2' => 'apple',
    'uniqid3' => 'apple',
    'uniqid4' => 'bannana'
);

echo $array['uniqid1'];
echo '
';
echo $array['uniqid2'];
echo '
';
echo $array['uniqid3'];
echo '
';
echo $array['uniqid4'];

?>

Output

apple apple apple bannana

As you can see, keys have become values, and it is now possible to obtain these values by indicating their index


text:
Q: Limit as $x$ tends to Infinity: Exponential vs $x^n$ $$Y = (1 / x) + ln(x)$$
$y$ tends to infinity as x tends to infinity (by looking at the graph). Is this because ln is related to the exponential function, and the exponential function increases faster than any x^n function?
On the other hand,
$$Y = xe^{-1/x}$$
$y$ tends to plus infinity as x tends to plus infinity, and tends to negative infinity as x tends to negative infinity. How can this be explained?

A: $$y(x)=\frac{1}{x}+\ln(x)$$
When $x\to\infty$ :

*

*$\frac{1}{x}\to 0\quad$. Thus $y(x)$ behaves like $\quad 0+\ln(x)=\ln(x)$.

*$\ln(x) \to\infty\quad$. Thus $y(x)\to\infty$
Conclusion : $y(x)\to\infty$ because $\ln(x)\to\infty.\quad$Nothing more.
$$ $$
$$ $$
$$y(x)=xe^{-1/x}$$
When $x\to\pm\infty$ :

*

*$-1/x \to 0$

*$xe^{-1/x}$ behaves like $xe^0=x$
Conclusion : The same as $x\: ,\quad$  $xe^{-1/x}$  tends to $\begin{cases} +\infty \quad\text{when } x\to +\infty \\ -\infty \quad\text{when } x\to -\infty\end{cases}$

A: In the first equation, note that $\lim_{x\rightarrow \infty}\ln(x) = \infty$. Also $1/x$ is positive for all $x > 0$. Lastly, since $1/x$ and $\ln(x)$ are continuous for $x >0$, $\lim_{x\rightarrow \infty}(1/x + \ln(x)) = \lim_{x\rightarrow \infty}1/x + \lim_{x\rightarrow \infty} \ln(x)$. Therefore, the limit of $Y$ as $x$ goes to infinity is the sum of two positive numbers, one of which tends to infinity.