text:
Q: Static class method properties in Python As the title says, I'm trying to give set/get functionality to my static classes in python. Basically, for a given static class with static attribute _x, I want to define a static property x that gives custom get and set function wrappers for _x.
Strangely it seems like the official Python docs say this functionality should exist. The docs say that as of version 3.9, you can use the @classmethod decorator to wrap property methods. However, it seems that this only works for getters, and not setters. For example, when I try to define a static property using this method, I get the following error:
class Foo:
  _x = 0

  @classmethod
  @property
  def x(self):
    return self._x

  @classmethod
  @x.setter
  def x(self, n):
    self._x = n

AttributeError: 'classmethod' object has no attribute 'setter'
If I flip the order, like:
class Foo:
  _x = 0

  @property
  @classmethod
  def x(self):
    return self._x

  @x.setter
  @classmethod
  def x(self, n):
    self._x = n

Then Foo.x returns a property object instead of calling the property's fget function.
So it seems this approach is not going to work. I then tried to exploit the way that function decorators work, by redefining Foo:
class Foo:
  _x = 0

  def __get_x(self):
    return self._x

  def __set_x(self, n):
    self._x = n

  x = classmethod(property(fget=__get_x, fset=__set_x))

But no luck. Whenever I try to set Foo.x, i.e. with Foo.x = 2, it does not call the property setter but instead directly overwrites x entirely.
One solution I've seen bounced around is using python metaclasses to implement this functionality. While that could fix the issue, it isn't ideal because A. I have many different static classes in my project and B. I use Sphinx to generate documentation for my code and it doesn't always play nice with metaclasses.
I've been looking for a solution to this issue for a while and I'm not sure what the best "pythonic" fix for it is. If metaclasses are the "cleanest" solution, how can I implement them in such a way that I don't have to write a lot of redundant code? Maybe I could write a custom function decorator that enables class property-esque functionality? Any help would be appreciated.

A: An instance's properties must be defined on its class. To define properties on a class, the rule still holds: when considering the class as an instance, its properties must be defined on the class's class (its metaclass).
class Meta(type):

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, n):
        self._x = n

class Foo(metaclass=Meta):
    _x = 0

Despite the drawbacks of using metaclasses, this is the way that works.


text:
Q: OneSignal don't build in Phonegap-build anymore Since yesterday I cannot build a Phonegap-build app that includ OneSignal plugin, it dose not work anymore! I am using the version 2.4.5
here is the error I get:
Any idea ?
FAILURE: Build failed with an exception.

*

*Where:
Build file '/app/build.gradle' line: 94

*What went wrong:
A problem occurred evaluating project ':app'.

Could not resolve all files for configuration 'classpath'.
  Could not resolve gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.10.0, 0.99.99].
   Required by:
       unspecified:unspecified:unspecified
  Could not resolve gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.10.0, 0.99.99].
  Failed to list versions for gradle.plugin.com.onesignal:onesignal-gradle-plugin.
  Unable to load Maven meta-data from https://plugins.gradle.org/m2/gradle/plugin/com/onesignal/onesignal-gradle-plugin/maven-metadata.xml.
  Could not get resource 'https://plugins.gradle.org/m2/gradle/plugin/com/onesignal/onesignal-gradle-plugin/maven-metadata.xml'.
  Could not GET 'https://plugins.gradle.org/m2/gradle/plugin/com/onesignal/onesignal-gradle-plugin/maven-metadata.xml'.
  sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

It worked the day before with the same OneSignal plugin version, and I did not change anything.

A: I solved changing onesignal plugin version:
Before I was using (with problem):

Works only with version 2.4.0:

You need to put exactly spec="2.4.0" not spec="^2.4.0".

A: Looks like there has been an issue with the gradle SSL certificate and they fixed it!  now it should be working fine, try to build with your previously working version 2.4.5 and let me know what you got.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is make_friedman1 used? I have started to learn ML, and am confused with make_friedman1. It highly improved my accuracy, and increased the data size. But the data isn't the same, it's changed after using this function. What does friedman! actually do?

A: If make_friedman1 asked here is the one in sklearn.datasets then it is the function which generates the "Friedman #1" regression problem. Here inputs are 10 independent variables uniformly distributed on the interval [0,1], only 5 out of these 10 are actually used. Outputs are created according to the formula::
y = 10 sin(π x1 x2) + 20 (x3 - 0.5)^2 + 10 x4 + 5 x5 + e

where e is N(0,sd)
Quoting from the Friedman's original paper, Multivariate Adaptive Regression Splines ::

A new method is presented for flexible regression modeling of high
  dimensional data. The model takes the form of an expansion in product
  spline basis functions, where the number of basis functions as well as
  the parameters associated with each one (product degree and knot
  locations) are automatically determined by the data. This procedure is
  motivated by the recursive partitioning approach to regression and
  shares its attractive properties. Unlike recursive partitioning,
  however, this method produces continuous models with continuous
  derivatives. It has more power and flexibility to model relationships
  that are nearly additive or involve interactions in at most a few
  variables

A spline is adding many polynomial curves end-to-end to make a new smooth curve.


text:
Q: How would I code a userscript to receive a desktop notification from a website? I need to write a userscript that detects when an element on a website changes (in this case, it's when somebody receives a popup notification on the screen in the website), and from there sends a desktop notification alerting the person that they have a notification from that website.
I hope this was clear enough, I have very little coding experience so please make this as understandable as possible, I just need to know what to even start out with or do in the first place, thank you

A:
I need to write a userscript that detects when an element on a website changes

You can use MutationObserver.

sends a desktop notification alerting the person that they have a notification from that website

You can use the notification API in script managers.
GreaseMonkey:       GM.notification
ViolentMonkey:      GM.notification/GM_notification
TamperMonkey:       GM_notification
FireMonkey:         GM.notification/GM_notification


text:
Q: Angular 6 - assets not including my app does not include assets directory, when i'm building app or starting a live server
angular.json
       "assets": [
          "src/favicon.ico",
          "src/assets",
          "src/manifest.json"
        ],

Directory structure

A: I think assets folder is empty that's why it is not exists in your dist directory.


text:
Q: Trick dice Probability I was given this exercise:
We have 2 dice, the first is normal $\Omega = \left\{1,2,...,6 \right\}$ and the other is a trick dice, with sample space $\Omega = \left\{2,3,4,5,6,6 \right\}$.
If there is probability $ \frac{1}{3}$ of choosing the first dice and $\frac{2}{3}$ of choosing the second dice what is the probability of:
1)Getting a number $\leq 3$.
2)Getting a number >3.
3) Choosing the trick dice if we got a number < 4.
My answers are $\frac{7}{18}$, $\frac{11}{18}$ and $\frac{7}{18}$.
 I would like to know if I'm correct. Thanks everyone.

A: The first two are correct, the third is not. Denoting with $D$ the result of the dice, with $D_1$ the event to pick the fair dice and with $D_2$ the (complementary) event to pick the tricky dice you have that:

*

*For the 1). By the law of total probability $$P(D\le 3)=P(D\le3|D_1)P(D_1)+P(D\le3|D_2)P(D_2)=\frac{3}{6}\cdot\frac{1}{3}+\frac{2}{6}\cdot\frac{2}{3}=\frac{7}{18}$$

*For the 2). Since $D>3$ and $D\le 3$ are complementary you have that
$$P(D>3)=1-P(D\le 3)=1-\frac{7}{18}=\frac{11}{18}$$

*For the 3). By Bayes rule $$P(D_2|D<4)=P(D_2|D\le 3)=\frac{P(D\le 3|D_2)P(D_2)}{P(D\le 3)}=\frac{\frac{4}{18}}{\frac{7}{18}}=\frac{4}{7}$$

A: As a complement (and compliment) to Stefanos's answer, I'll describe a simpleminded approach I take to problems of this type.
Because of the two-to-one odds of choosing the trick die, I imagine having rolled each side of the normal die once and each side of the trick die twice, for a total of $18$ rolls.  If you do so, you get the numbers $1$, $2$, and $3$ once each from the normal die, and the numbers $2$ and $3$ twice each from the trick die, for a total of $3+4=7$ rolls.  That gives the answer $7/18$ for part 1).
Part 2) is just the complementary probability $1-(7/18)=11/18$.
For part 3), we're focusing on the $7$ rolls described above, which resulted in numbers less than $4$, and asking, in essence, how many of them came from the trick die.  We thus get the conditional probability $4/7$.


text:
Q: Adding a class to a map I am trying to add a class object to a map, this is what I have:
#include<vector>
#include<map>
#include<stdio.h>
#include<string>
#include<iostream>

using namespace std;

class Student{
    int PID;
    string name;
    int academicYear;
public:
    Student(int, string, int);
};

Student::Student (int P, string n, int a) {
    PID = P;
    name = n;
    academicYear = a;
}

void createStudent(map<string, Student>);

int main(int argc, char** argv){

    map <string, Student> studentList;

    createStudent(studentList);
}

void createStudent(map<string, Student> studentList){

    int PID;
    string name;
    int academicYear;

    cout << "Add new student-\nName: ";
    getline(cin, name);
    cout << "PID: ";
    cin >> PID;
    cout << "Academic year: ";
    cin >> academicYear;

    Student newstud (PID, name, academicYear);

    studentList[name] = newstud;  //this line causes the error:
                                  //no matching function for call to
                                  //'Student::Student()'
}

I don't understand why the constructor function is being called there, I thought newstud would already have been constructed from the previous line. Can anyone explain what is happening when I try to add newstud to the map?

A: *

*Problem 1st

std::map::operator[] will insert new element into container if its not present, using default constructor, which in your case is not present and will probably doesn't make sense even if you provide one.
So use std::map::insert for such scenario

*

*Problem 2nd

Even if you successfully insert using studentList.insert(std::make_pair(name, newstud)); its not going to reflect changes in original map studentList in main ( ) unless you use a reference type, in function definition & declaration of createStudent
So use
void createStudent(map<string, Student>& );

A: In order to add entries using the function, you should make your parameter studentList pass by reference.
And instead of
studentList[name] = newstud;

use:
studentList.insert(std::make_pair(name, newstud));

Just a suggestion, though.


text:
Q: Export image with GDAL. Poor quality I use the following command to export a jpg file:
gdaldem color-relief C:\input.tif C:\colors.txt C:\output.jpg

The file colors.txt:
-0.99 255 38 0
-0.5 255 81 0
-0.3 255 119 0
-0.2 255 153 0
-0.1 255 187 0
-0 255 221 0
0.1 255 255 0
0.2 206 224 0
0.3 164 196 0
0.4 122 171 0
0.5 85 145 0
0.6 48 120 0
1 0 97 0

The problem is that the file looks different when I display it in the standard Windows software to display images or when I show it in arcmap.
This is how it looks good and is shown in arcmap:
ARCMAP
This is how it is displayed in the Windows program:
WINDOWS
Does anyone have any idea how to display this in Windows software as it appears in arcmap software?
Thanks


text:
Q: Unit testing angularjs controller using Node.js, Gulp.js and Mocha I am trying to unit test an angularjs controller using Node.js. I am using gulp.js and mocha to run the tests, via gulp-mocha.
This is what my gulpfile.js looks like right now:
(function () {

    var gulp = require('gulp');
    var mocha = require('gulp-mocha');

    gulp.task('default', function () {
        return gulp
            .src('Scripts/Tests/*.js', { read: false })
            .pipe(mocha({
                ui: 'tdd',
                reporter: 'dot',
                globals: {
                    angular: require('./Scripts/angular.js')
                }
            }));
    });

})();

This is the code under test:
(function () {

    var application = angular.module('Main');

    application.controller('MainController', ['$scope', function ($scope) {

        $scope.isDisabled = function () {
            return true;
        };

    }]);

})();

And this is the test file itself:
(function () {

    var chai = require('chai');
    var assert = chai.assert;

    angular.module('Main', []);  // Create an empty module
    require('../MainController.js');  // Fill the module with the controller

    suite('Main Controller', function () {

        test('isDisabled always true', function () {

            var controllerFactory = angular.injector.get('$controller');
            var controller  = controllerFactory('MainController', {
                '$scope': {}
            });

            var result = controller.isDisabled();
            assert.isTrue(result);
        });

    });

})();

I need to make angular a global in order for my test and the file I am testing to work. However, the call to require in gulpfile.js is giving me a Reference Error: window is not defined error. That makes sense, since I am running in Node.js.
What do I need to do to load up angular in Node.js?

A: As @unobf said (and the angularjs documentation says), the trick to testing angular from Node.js was to use Karma. That meant installing karma and karma-mocha, along with karma-chrome-launcher, karma-ie-launcher, karma-firefox-launcher (or whatever) via npm install.
Then I basically had to redo my gulp.js file from scratch:
(function () {

    var gulp = require('gulp');
    var karma = require('karma').server;

    gulp.task('runTests', function (done) {
        karma.start({
            configFile: __dirname + '/karma.config.js',
            singleRun: true
        }, done);
    });

    gulp.task('default', ['runTests']);

})();

I also had to create a karma.config.js file to configure karma to use Chrome, Firefox, IE with mocha. In the same file, I configured mocha to use the tdd UI and the dot reporter:
module.exports = function(config) {
    config.set({
        browsers: ['Chrome', 'Firefox', 'IE'],
        frameworks: ['mocha'],
        files: [
            './Scripts/angular.js',
            './Scripts/chai.js',
            './Scripts/*.js',
            './Scripts/Tests/*.js'
        ],
        singleRun: true,
        client: {
            mocha: {
                reporter: 'dot',
                ui: 'tdd'
            }
        }
    });
};

I learned you have to specify angularjs, chai.js, etc. first so they are picked up first and in global scope for the other files. Along the same lines, the files for the code being tested have to be listed before the test files.
The code being tested didn't change at all. Once my tests were running, I realized my test was broken, and it ended up looking like this to pass:
(function () {

    var assert = chai.assert;

    suite('Main Controller', function () {

        test('isDisabled always true', function () {

            var injector = angular.injector(['ng', 'Main']);
            var $controller = injector.get('$controller');
            var scope = {};
            var controller  = $controller('MainController', {
                '$scope': scope
            });

            var result = scope.isDisabled();
            assert.isTrue(result);
        });

    });

})();

The big take away was that the controller simply populates the $scope object. I call isDisabled() on the $scope object instead. Of course, getting at the controller is a lot of work, so it makes more sense to use the inject method provided by angular-mocks.js:
(function () {

    var assert = chai.assert;

    suite('Main Controller', function () {

        var $scope = {};

        setup(function () {
            module('Main');
            inject(function ($controller) {
                $controller('MainController', {
                    '$scope': $scope
                });
            });
        });

        test('isDisabled always true', inject(function ($controller) {
            var result = $scope.isDisabled();
            assert.isTrue(result);
        }));

    });

})();

Hopefully this is enough to get anyone started who is trying to use Node.js and mocha to test angularjs code.

A: I am doing this in Grunt, but the same principle applies to Gulp. You need to inject the "angular-mocks.js" file to be able to mock the dependency injection. I am using Karma http://karma-runner.github.io/0.12/index.html to do this and set it up in my karma.conf.js file as follows:
module.exports = function(config){
  config.set({
    basePath : '../../',

    files : [
      'bower_components/angular/angular.js',
      'bower_components/angular-mocks/angular-mocks.js',
      ...

Then you can inject a $controller into your tests and do things like test your controller initialization. The test below is initializing the scope and then testing that the controller is adding methods to the scope (note, I am using Jasmine, but the same can be done with mocha) but Jasmine comes with some nice builtin spy capabilities.
describe('analysisController', function () {
    var scope, state;

    beforeEach(function () {
        module('analysis');
        scope = {
            $apply:jasmine.createSpy(),
            ws: {
                registerCallback:jasmine.createSpy(),
                sendMessage:jasmine.createSpy()
            }
        },
        state = {
            go : jasmine.createSpy()
        };
    });
    it('should add a bunch of methods to the scope', inject(function ($controller) {
        $controller('analysisController', {
            $scope : scope,
            $state: state
        });
        expect(typeof scope.colorContrast).toBe('function');
        expect(typeof scope.XPathFromIssue).toBe('function');
    }));
    ...


text:
Q: Magento 2 add column to sales returns grid How to add column to sales returns grid,
returns grid using _prepareColumns to add columns to grid \Magento\Rma\Block\Adminhtml\Rma\Grid

A: Try with below way!
Extend Magento RMA block file to your custom module.

app/code/Namespace/Modulename/Block/Adminhtml/Rma

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

// @codingStandardsIgnoreFile

namespace Namespace\Modulename\Block\Adminhtml\Rma;

/**
 * RMA Grid
 */
class Grid extends \Magento\Rma\Block\Adminhtml\Rma\Grid
{
    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Backend\Helper\Data $backendHelper
     * @param \Magento\Rma\Model\ResourceModel\Rma\Grid\CollectionFactory $collectionFactory
     * @param \Magento\Rma\Model\RmaFactory $rmaFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Magento\Rma\Model\ResourceModel\Rma\Grid\CollectionFactory $collectionFactory,
        \Magento\Rma\Model\RmaFactory $rmaFactory,
        array $data = array())
    {
        parent::__construct(
            $context,
            $backendHelper,
            $collectionFactory,
            $rmaFactory,
            $data);
    }

    /**
     * Prepare related item collection
     *
     * @return \Magento\Rma\Block\Adminhtml\Rma\Grid
     */
    protected function _prepareCollection()
    {
        $this->_beforePrepareCollection();
        return parent::_prepareCollection();
    }

    /**
     * Configuring and setting collection
     *
     * @return $this
     */
    protected function _beforePrepareCollection()
    {
        if (!$this->getCollection()) {
            /** @var $collection \Magento\Rma\Model\ResourceModel\Rma\Grid\Collection */
            $collection = $this->_collectionFactory->create();
            $this->setCollection($collection);
        }
        return $this;
    }

    /**
     * Prepare grid columns
     *
     * @return \Magento\Rma\Block\Adminhtml\Rma\Grid
     */
    protected function _prepareColumns()
    {
        parent::_prepareColumns();
        $this->addColumn(
            'custom_column',
            [
                'header' => __('Custom Column'),
                'index' => 'custom_column',
                'header_css_class' => 'col-name',
                'column_css_class' => 'col-name'
            ]
        );
        return $this;
    }

    /**
     * Prepare massaction
     *
     * @return $this
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('entity_id');
        $this->getMassactionBlock()->setFormFieldName('entity_ids');

        $this->getMassactionBlock()->addItem(
            'status',
            [
                'label' => __('Close'),
                'url' => $this->getUrl($this->_getControllerUrl('close')),
                'confirm' => __(
                    'You have chosen to change status(es) of the selected RMA requests to Close.'
                    . ' Are you sure you want to continue?'
                )
            ]
        );

        return $this;
    }

    /**
     * Get Url to action
     *
     * @param  string $action action Url part
     * @return string
     */
    protected function _getControllerUrl($action = '')
    {
        return '*/*/' . $action;
    }

    /**
     * Retrieve row url
     *
     * @param \Magento\Framework\DataObject $row
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl($this->_getControllerUrl('edit'), ['id' => $row->getId()]);
    }
}

It will be showing like below.

I hope it helps!

A: Step 1 :
    Create Custom Column (Token Number) In Rma Grid Table

Step 2:
    Use preference in di.xml
    "<preference for="Magento\Rma\Block\Adminhtml\Rma\Grid" type="<Vendor>\<ModuleName>\Block\Adminhtml\Rma\Grid" />"

Step 3:

    Create Grid Class   <Vendor>\<ModuleName>\Block\Adminhtml\Rma\Grid

<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace <Vendor>\<ModuleName>\Block\Adminhtml\Rma;

/**
 * Description of Grid
 *
 * @author sagar
 */
class Grid extends \Magento\Rma\Block\Adminhtml\Rma\Grid {

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Backend\Helper\Data $backendHelper
     * @param \Magento\Rma\Model\ResourceModel\Rma\Grid\CollectionFactory $collectionFactory
     * @param \Magento\Rma\Model\RmaFactory $rmaFactory
     * @param array $data
     */
    public function __construct(
            \Magento\Backend\Block\Template\Context $context,
            \Magento\Backend\Helper\Data $backendHelper,
            \Magento\Rma\Model\ResourceModel\Rma\Grid\CollectionFactory $collectionFactory,
            \Magento\Rma\Model\RmaFactory $rmaFactory,
            array $data = array()) {
        parent::__construct(
                $context,
                $backendHelper,
                $collectionFactory,
                $rmaFactory,
                $data);
    }

    /**
     * Prepare related item collection
     *
     * @return \Magento\Rma\Block\Adminhtml\Rma\Grid
     */
    protected function _prepareCollection() {
        $this->_beforePrepareCollection();
        return parent::_prepareCollection();
    }

    /**
     * Configuring and setting collection
     *
     * @return $this
     */
    protected function _beforePrepareCollection() {
        if (!$this->getCollection()) {
            /** @var $collection \Magento\Rma\Model\ResourceModel\Rma\Grid\Collection */
            $collection = $this->_collectionFactory->create();
            $this->setCollection($collection);
        }
        return $this;
    }

    /**
     * Prepare grid columns
     *
     * @return \Magento\Rma\Block\Adminhtml\Rma\Grid
     */
    protected function _prepareColumns() {
        parent::_prepareColumns();
        $this->addColumn(
                'token_number',
                [
                    'header' => __('Token Number'),
                    'index' => 'token_number',
                    'header_css_class' => 'col-name',
                    'column_css_class' => 'col-name'
                ]
        );

        return $this;
    }

    /**
     * Prepare massaction
     *
     * @return $this
     */
    protected function _prepareMassaction() {
        $this->setMassactionIdField('entity_id');
        $this->getMassactionBlock()->setFormFieldName('entity_ids');

        $this->getMassactionBlock()->addItem(
                'status',
                [
                    'label' => __('Close'),
                    'url' => $this->getUrl($this->_getControllerUrl('close')),
                    'confirm' => __(
                            'You have chosen to change status(es) of the selected RMA requests to Close.'
                            . ' Are you sure you want to continue?'
                    )
                ]
        );

        return $this;
    }

    /**
     * Get Url to action
     *
     * @param  string $action action Url part
     * @return string
     */
    protected function _getControllerUrl($action = '') {
        return '*/*/' . $action;
    }

    /**
     * Retrieve row url
     *
     * @param \Magento\Framework\DataObject $row
     * @return string
     */
    public function getRowUrl($row) {
        return $this->getUrl($this->_getControllerUrl('edit'), ['id' => $row->getId()]);
    }

}


text:
Q: Why doesn't Parsec allow white spaces before operators in the table for buildExpressionParser In the code below I can correctly parse white spaces after each of the tokens using Parsec:
whitespace = skipMany (space <?> "")

number :: Parser Integer
number = result <?> "number"
  where
  result = do {
    ds <- many1 digit;
    whitespace;
    return (read ds)
  }

table = result
  where
  result = [
    [Infix (genParser '*' (*)) AssocLeft,
     Infix (genParser '/' div) AssocLeft],
    [Infix (genParser '+' (+)) AssocLeft,
     Infix (genParser '-' (-)) AssocLeft]]
  genParser s f = char s >> whitespace >> return f

factor = parenExpr <|> number <?> "parens or number"
  where
  parenExpr = do {
    char '(';
    x <- expr;
    char ')';
    whitespace;
    return x
  }

expr :: Parser Integer
expr = buildExpressionParser table factor <?> "expression"

However I get a parse error when trying to only parse white spaces before, and after the operators:
whitespace = skipMany (space <?> "")

number :: Parser Integer
number = result <?> "number"
  where
  result = do {
    ds <- many1 digit;
    return (read ds)
  }

table = result
  where
  result = [
    [Infix (genParser '*' (*)) AssocLeft,
     Infix (genParser '/' div) AssocLeft],
    [Infix (genParser '+' (+)) AssocLeft,
     Infix (genParser '-' (-)) AssocLeft]]
  genParser s f = whitespace >> char s >> whitespace >> return f

factor = parenExpr <|> number <?> "parens or number"
  where
  parenExpr = do {
    char '(';
    x <- expr;
    char ')';
    return x
  }

expr :: Parser Integer
expr = buildExpressionParser table factor <?> "expression"

The parse error is:
$ ./parsec_example < <(echo "2 * 2 * 3")
"(stdin)" (line 2, column 1):
unexpected end of input
expecting "*"

Why does this happen?  Is there some other way to parse white space around just the operators?

A: When I test your code, 2 * 2 * 3 parses correctly, but 2 + 2 does not.  Parsing fails because the parser for * consumes some input and backtracking isn't enabled at that position, so other parsers cannot be tried.
An expression parser created by buildExpressionParser tries to parse each operator in turn until one succeeds.   When parsing 2 + 2, the following occurs:

*

*The first 2 is matched by number.  The rest of the input is  + 2 (note the space at the beginning).

*The parser genParser '*' (*) is applied to the input.  It consumes the space, but does not match the + character.

*The other infix operator parsers automatically fail because some input was consumed by genParser '*' (*).

You can fix this by wrapping the critical part of the parser in try.  This saves the input until after char s succeeds.  If char s fails, then buildExpressionParser can backtrack and try another infix operator.
genParser s f = try (whitespace >> char s) >> whitespace >> return f

The drawback of this parser is that, because it backtracks to before the leading whitespace before an infix operator, it repeatedly scans whitespace.  It is usually better to parse whitespace after a successful match, like the OP's first parser example.


text:
Q: GWT Java rpc call working; however, replacement GWTBootstrap - rpc call not working I am just starting to use bootstrap to convert an existing GWT project. The original rpc call works in the following code. However, the replacement is placed straight after the original code and "Connection failed - please retry." is displayed on the screen as a pop-up when triggered. There is nothing in the log. The window displays return the correct values. I will replace the original code when I get the bootstrap working.
package org.AwardTracker.client;
/**
 * The purpose of this View is to allow the account holder
 * to login to their account using an Account Name and password.
 */

import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.Document;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.AttachEvent;
import com.google.gwt.event.logical.shared.AttachEvent.Handler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;

public class LoginView extends Composite {

    private DBConnectionAsync rpc;

    final VerticalPanel verticalPanel = new VerticalPanel();
    final HorizontalPanel horizontalPanel = new HorizontalPanel();
    final Label lblWelcomeToThe = new Label("Welcome to the Award Tracker login page.\r\n\r\nPlease Sign into your account.");
    final FlexTable flexTable = new FlexTable();
    final Label lblAccountName = new Label("*Account name:");
    final Label lblAccountName2 = new Label("(username (e.g., email))");
    final Label lblPassword = new Label("*Password:");

    private PasswordTextBox passwordTextBox;
    private TextBox textBoxAccountName;

    int loginAttempt = 0;
    public String youthMemberID = null;
    int youthMembersLinked = 0;

    public String accountID = null;
    public String accountLevel = null;
    public String scoutGroup = null;
    public String scoutGroupSection = null;

    public LoginView() {
        verticalPanel.addAttachHandler(new Handler() {
            public void onAttachOrDetach(AttachEvent event) {
                if (event.isAttached()) {

                    rpc = (DBConnectionAsync) GWT.create(DBConnection.class);
                    ServiceDefTarget target = (ServiceDefTarget) rpc;
                    String moduleRelativeURL = GWT.getModuleBaseURL() + "MySQLConnection";
                    target.setServiceEntryPoint(moduleRelativeURL);

                    //Display the login page

                    //This is the nice green background with the small Scout logo
                    verticalPanel.setStyleName("gwt-Scout-Background");
                    verticalPanel.setWidth("100%");
                    verticalPanel.setHeight("100%");
                    verticalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
                    verticalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
                    verticalPanel.setBorderWidth(0);

                    //This is the nice green background with the small Scout logo
                    horizontalPanel.setStyleName("gwt-Scout-Background");
                    horizontalPanel.setWidth("100%");
                    horizontalPanel.setHeight("100%");
                    horizontalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);
                    horizontalPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
                    verticalPanel.add(horizontalPanel);

                    //Display the welcome message
                    lblWelcomeToThe.setStyleName("gwt-Label-Login");
                    verticalPanel.add(lblWelcomeToThe);
                    lblWelcomeToThe.setWidth("321px");

                    verticalPanel.add(flexTable);
                    verticalPanel.setCellHorizontalAlignment(flexTable, HasHorizontalAlignment.ALIGN_CENTER);

                    //Display the Account Name text and text box
                    lblAccountName.setStyleName("gwt-Label-Login");
                    flexTable.setWidget(0, 0, lblAccountName);
                    //lblAccountName.setSize("110px", "16px");
                    flexTable.getCellFormatter().setHorizontalAlignment(0, 0, HasHorizontalAlignment.ALIGN_RIGHT);

                    textBoxAccountName = new TextBox();
                    flexTable.setWidget(0, 1, textBoxAccountName);
                    textBoxAccountName.setSize("155px", "20px");

                    //Display the Account Name hint
                    lblAccountName2.setStyleName("gwt-Label-Login");
                    flexTable.setWidget(0, 2, lblAccountName2);
                    //lblAccountName2.setSize("200px", "16px");
                    flexTable.getCellFormatter().setHorizontalAlignment(0, 2, HasHorizontalAlignment.ALIGN_LEFT);

                    //Display the password text and text box.
                    lblPassword.setStyleName("gwt-Label-Login");
                    flexTable.setWidget(1, 0, lblPassword);
                    //lblPassword.setSize("73px", "16px");
                    flexTable.getCellFormatter().setHorizontalAlignment(1, 0, HasHorizontalAlignment.ALIGN_RIGHT);

                    passwordTextBox = new PasswordTextBox();
                    flexTable.setWidget(1, 1, passwordTextBox);
                    passwordTextBox.setSize("155px", "20px");

                    //The following code will be replaced when the bootstrap code is working
                    //Display the sign in button and handle the click event
                    Button btnSignIn2 = new Button("Sign In");
                    btnSignIn2.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            //Store whether details have been entered for error handling
                            //textBoxAccountName.setText("accountName");

                            Integer tracker = 0;
                            if (textBoxAccountName.getText().length() == 0) {
                                    tracker = tracker + 1;
                            }
                            if (passwordTextBox.getText().length() == 0) {
                                tracker = tracker + 2;
                            }

                            //Check if details have been entered and display an error if
                            //they have not been entered.
                            if (tracker == 1) {
                                textBoxAccountName.setStyleName("gwt-TextBox-Error");
                                passwordTextBox.setStyleName("gwt-TextBox");
                                Window.alert("Please enter your Account name.");
                                }else if (tracker == 2) {
                                    textBoxAccountName.setStyleName("gwt-TextBox");
                                    passwordTextBox.setStyleName("gwt-TextBox-Error");
                                    Window.alert("Please enter your Password.");
                                }else if (tracker == 3) {
                                    textBoxAccountName.setStyleName("gwt-TextBox-Error");
                                    passwordTextBox.setStyleName("gwt-TextBox-Error");
                                    Window.alert("Please enter your Account name and Password.");
                                }else {
                                    //If the required details have been entered then search the database for a match
                                    textBoxAccountName.setStyleName("gwt-TextBox");
                                    passwordTextBox.setStyleName("gwt-TextBox");
                                    AsyncCallback<AccountGroup> callback = new AuthenticationHandler<AccountGroup>();
                                    rpc.authenticateAccountGroup(textBoxAccountName.getText(), passwordTextBox.getText(), callback);
                                }
                        }
                    });
                    flexTable.setWidget(3, 1, btnSignIn2);

                    //The following code is for bootstrap
                    RootPanel.get("payPalDonate");
                    RootPanel.get("payPalDonate").setVisible(true);
                    RootPanel.get("login"); //From bootstrap
                    RootPanel.get("login").setVisible(true);
                    Button btnSignIn = Button.wrap(Document.get().getElementById("submit")); //From bootstrap
                    final TextBox textBoxAccountName = TextBox.wrap(Document.get().getElementById("accountName")); //From bootstrap
                    final PasswordTextBox passwordTextBox = PasswordTextBox.wrap(Document.get().getElementById("enterPassword")); //From bootstrap

                    //Display the sign in button and handle the click event
                    btnSignIn.addClickHandler(new ClickHandler() {
                        public void onClick(ClickEvent event) {
                            //Store whether details have been entered for error handling

                            Integer tracker = 0;
                            if (textBoxAccountName.getText().length() == 0) {
                                    tracker = tracker + 1;
                            }
                            if (passwordTextBox.getText().length() == 0) {
                                tracker = tracker + 2;
                            }

                            //Check if details have been entered and display an error if
                            //they have not been entered.
                            if (tracker == 1) {
                                textBoxAccountName.setStyleName("gwt-TextBox-Error");
                                passwordTextBox.setStyleName("gwt-TextBox");
                                Window.alert("Please enter your Account name.");
                                }else if (tracker == 2) {
                                    textBoxAccountName.setStyleName("gwt-TextBox");
                                    passwordTextBox.setStyleName("gwt-TextBox-Error");
                                    Window.alert("Please enter your Password.");
                                }else if (tracker == 3) {
                                    textBoxAccountName.setStyleName("gwt-TextBox-Error");
                                    passwordTextBox.setStyleName("gwt-TextBox-Error");
                                    Window.alert("Please enter your Account name and Password.");
                                }else {
                                    //If the required details have been entered then search the database for a match
                                    textBoxAccountName.setStyleName("gwt-TextBox");
                                    passwordTextBox.setStyleName("gwt-TextBox");
                                    Window.alert("textBoxAccountName.getText() = " + textBoxAccountName.getText());
                                    Window.alert("passwordTextBox.getText() = " + passwordTextBox.getText());
                                    AsyncCallback<AccountGroup> callback = new AuthenticationHandler<AccountGroup>();
                                    rpc.authenticateAccountGroup(textBoxAccountName.getText(), passwordTextBox.getText(), callback);
                                }
                        }
                    });
                }
            }
        });
        initWidget(verticalPanel);

    }

    class AuthenticationHandler<T> implements AsyncCallback<AccountGroup> {
        public void onFailure(Throwable ex) {
            System.out.println("RPC call failed - AuthenticationHandler - Notify Administrator.");
            Window.alert("Connection failed - please retry.");
        }
        public void onSuccess(AccountGroup result) {
            AccountGroup account = result;
            if (account == null) {
                //Only three invalid login attempts are allowed. Disable the account after
                //three invalid login attempts.
                if (loginAttempt > 2){
                    AsyncCallback<Void> callback = new DisableHandler<Void>();
                    rpc.disableAccount(textBoxAccountName.getText(), 0, callback);
                }else{
                    Window.alert("Incorrect Account name or Password entered. Please try again.");
                }
            }else{
                if (account.getLevel() == null) {
                    Window.alert("Your account has not yet been set up. Please contact your administrator.");
                }else{
                    if (account.getArchived() != null) {
                        Window.alert("Your account has been archived. Please contact your administrator.");
                    }else{
                        if (account.getEnabled() == 1){
                            accountLevel = account.getLevel();
                            accountID = account.getAccountId();
                            scoutGroup = account.getScoutGroupId();
                            scoutGroupSection = account.getGroupSection();

                            //Is a Leader or Administrator.
                            //Store the LoginView data for use in subsequent Views.
                            AsyncCallback<ViewData> callback2 = new ViewDataStoreHandler<ViewData>();
                            rpc.setViewData(account.getAccountId(), account.getLevel(), null, null, null,
                                    scoutGroup, null, 0, scoutGroupSection, null, null, callback2);
                        }else{
                            //The account has had three or more invalid passwords entered and has been disabled.
                            Window.alert("Account is disabled. Please contact your administrator.");
                        }
                    }
                }
            }
        }
    }

    class ViewDataStoreHandler<T> implements AsyncCallback<ViewData> {

        public void onFailure(Throwable ex) {
            System.out.println("RPC call failed - ViewDataStoreHandler - Notify Administrator.");
            Window.alert("Connection failed - please retry.");
        }
        public void onSuccess(ViewData result) {
            //The details have been stored
            RootPanel.get("payPalDonate").setVisible(false);
            RootPanel.get("payPalDonate").clear();
            RootPanel.get("login").setVisible(false);
            RootPanel.get("login").clear();

            History.newItem("selectPerson", true);
        }
    }

    class DisableHandler<T> implements AsyncCallback<Void> {
        public void onFailure(Throwable ex) {
            System.out.println("RPC call failed - DisableHandler - Notify Administrator.");
            Window.alert("Connection failed - please retry.");
        }
        public void onSuccess(Void result) {
            Window.alert("You have exceeded your password tries and your Account has been disabled. Please contact your administrator.");
        }
    }

}

I have found that on the server side when I check the password using:
    if (stored_hash == null){
        System.out.println("Incorrect account.");
        account = null;
    }else{
        //Check that the hashed value of the password equals the stored hashed value
        //If it does not then account will be set to null.
        if (BCrypt.checkpw(pass, stored_hash))  {
            System.out.println("Success!");
        }else{
            System.out.println("Incorrect password.");
            account = null;
        }
    }
    //Done
    return account;

If the account is incorrect (i.e., BCrypt is not used) then there is no error returned. However, when BCrypt is used (i.e., the account is correct whether or not the password is correct) then an error code is returned (Throwable value = com.google.gwt.user.client.rpc.StatusCodeException: 0)
I then found Getting com.google.gwt.user.client.rpc.StatusCodeException: 0 in GWT:
I have found that if you hang an rpc call on the server (Thread.wait()) and the browser is refreshed then on the client side just before it loads the page again it will call the onFailure method of the waiting callback with the above mentioned status code which suggests it orginates in the client or that it is a generic error code for non-specific caught exceptions.
My browser is refreshing! So the question now is how to stop it refreshing?

A: After much investigation I found that the issue is not with the Java code. When you return data from a form in gwtBootstrap if refreshes and returns "Throwable value = com.google.gwt.user.client.rpc.StatusCodeException: 0" which is picked up as an error code in GWTJava. So do not use a form use div in the HTML. The full explanation and resolution is at How to stop GWTBootstrap3 from refreshing and loosing my input and returning an error code


text:
Q: mysql query calculate rating sum I have following table
id item_id rating
 1    10     1
 2    10     2
 3    10     2
 4    10     3
 5    10     3
 6    10     3
 7    10     4

How can I write a query so that I can get result as follows:
$ratings = array(
    1 => 1,
    2 => 2,
    3 => 3,
    4 => 1,
    5 => 0
);

I need to use this query to write a php function to calculate average ratings by this function:
$total = 0;
$count = 0;
foreach($ratings as $number=>$frequency) {
  $total += $number * $frequency;
  $count += $frequency;
}
return $total / $count;

A: SELECT
    rating,
    COUNT(rating) as Count
FROM rating
GROUP BY rating

A: The basic COUNTing of records on the table won't produce 5 because there is no value 5 on the rating. But generating subquery which contains values from 1-5 and joining them using LEFT JOIN will do your desired result.
SELECT a.rating, COUNT(b.rating) totalCount
FROM
    (
      SELECT 1 rating UNION SELECT 2 UNION
      SELECT 3 UNION SELECT 4 UNION
      SELECT 5
    ) a
    LEFT JOIN tableName b
      ON a.rating = b.rating
GROUP BY a.rating

*

*SQLFiddle Demo


text:
Q: CSS - Overriding CSS Reset Problem: margin: 0 auto does not work on body. background-color: #EEEEEE on the other hand, is working even though they are on the same block.
index.php:

        <title>MForte</title>
        <link rel="stylesheet" type="text/css" href="css/reset.css">
        <link rel="stylesheet" type="text/css" href="css/bodyStyleSheet.css">

test

test

test

reset.css:
/**
* Eric Meyer's Reset CSS v2.0 (http://meyerweb.com/eric/tools/css/reset/)
* http://cssreset.com
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

bodyStyleSheet.css:
#container {
    margin: 0 auto;
    background-color: #EEEEEE;
}

What I have tried:
1) Swapping <link rel="stylesheet" type="text/css" href="css/reset.css"> and <link rel="stylesheet" type="text/css" href="css/bodyStyleSheet.css"> to each other.
2) Removed the id of the body from the index.php file and replaced the #container by body
3) To test the scenario, since border: 0 is declared on reset.css, I tried to create a table on index.php containing 2 rows. border: 1 is declared on reset.css in the table tag. Border didn't show.

A: Your approach is wrong, you are trying to horizontally center body element which has a default width of 100% so even if you want to horizontally center the body you cannot, as it is 100% in width and actually designers never center the body tag.. so if you want, nest a container div inside the body element, assign some fixed width and than use margin: 0 auto;. So alter your DOM like

#container {
   width: 1000px;
   margin: 0 auto;
}

Also, if you are looking to apply background to entire viewport than leave the background property on the body element, if you want the background only for the horizontally centered element than move the background property in #container

Also, CSS reset has nothing to do with this, CSS Reset is used to reset the default styles applied by browser stylesheet, some prefer to use universal * selector to reset margin and padding and some do reset the outline as well like
* {
   margin: 0;
   padding: 0;
   outline: 0;
}

But some prefer CSS Reset Stylesheets which minimizes cross browser differences to minimal.. So you can opt for any option.

Last but not the least, you are talking about the overriding, using Reset stylesheet, those stylesheet always uses minimal specificity selectors, using class or id will make your selectors anyways specific than the selectors used in the Reset Stylesheet, so don't use !important unless required unless you will end up in a mess, better use specific selectors.

A: Use !important in css/bodyStyleSheet.css
such as
#container {
    margin: 0 auto;
    background-color: #EEEEEE !important;
}

Good article on Smashing Magazine here
http://coding.smashingmagazine.com/2010/11/02/the-important-css-declaration-how-and-when-to-use-it/


text:
Q: Reinitialize dynamically allocated memory I am dynamically allocating memory at the beginning of a for using:
Candset_t* emptycandset(void) {
    Candset_t* cset;

    cset = (Candset_t*)malloc(sizeof(Candset_t));
    cset->size = 0;
    cset->maxsize = MAXSIZE;
    cset->dptr = (Point_t*)malloc(MAXSIZE * sizeof(Point_t));

    return cset;
}

whereby Candset and Point_t are both typedef.
later I free the memory at the end of the loop with:
void destroycandset(Candset_t* cset) {
    free(cset->dptr);
    free(cset);
}

The reason why I am doing this is because I want to reuse the same variable(memory space) in all the iterations of the loop.
This actually cause fragmentation of the heap. Hence, decreased performance. How can I solve this? is it possible to reinitiate a dynamically allocated space? How does this affect the dynamic memory?
Cheers
I am trying to reuse a dynamically allocated memory. However, using malloc and free cause fragmentation of the heap.
Do you know any way to avoid memory fragmentation?
typedef struct point {
    double x, y;
    unsigned int dst;
} Point_t;

typedef struct candset {
    unsigned int size;
    unsigned int maxsize;
    Point_t* dptr;
} Candset_t;

This is what the struct data look like.
I can't tell what the size of the dptr and Candset_t will be; Hence, I have to allocate them dynamically. It make no difference when using new and delete for c++ only.

A: For structures smaller than 1 MB whose lifetime is simple, don't use dynamic allocation at all.
Just create a Candset_t in automatic storage (on the stack).
Automatic storage provides memory extremely efficiently.
If your object is "simple" enough to malloc-and-modify, it is also free to create in automatic storage.
There are people who are used to languages like Java or C#, where creating an object is inherently expensive.
In C++, creating an object can be literally free.  It can also be expensive.  How expensive it is depends on the properties of the object.
Because objects in C++ carry less baggage than in garbage collected languages, the "free" case is really, really free.
To make an object effectively free to use, ensure that it doesn't use dynamically allocated memory at construction time, and to be extra sure avoid virtual functions (sometimes these can also be free).  Next, don't use new or malloc to create it.
Here is a simple "free" class:
struct Candset_t {
  std::size_t size;
  Point_t data[MAXSIZE];
};

so long as MAXSIZE isn't really big, like in the many 1000s, this is going to be a better plan than the original.
If this doesn't work, then you can just move the declaration of Candset_t up a scope, and reuse it.  You do not want to reallocate dptr, but instead write code to clear the memory in it.
Generally, calls to malloc or new take 100x or more the time of a typical line of C++ code.  So avoid them in tight loops.


text:
Q: Generate production build with sourcemaps in Angular - CLI How to keep sourcemaps after production build?
Right now, my command looks like this:
"build-prod": "ng build --app=release -prod && cp -R lang dist"
I tried changing it to:
ng build --app=release --sourceMap=true -prod && cp -R lang dist
but nothing changed.
If I do:
ng build --sourcemap I get sourcemaps but then I get index.html instead of index.prod.html.
Is it possible to edit the first command to build sourcemap files?
this is my tsconfig.json file:

{
    "compileOnSave": false,
    "compilerOptions": {
        "outDir": "./dist/out-tsc",
        "sourceMap": true,
        "declaration": false,
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "target": "es5",
        "typeRoots": [
            "node_modules/@types"
        ],
        "lib": [
            "es2017",
            "dom"
        ]
    }
}

A: You should edit your angular.json like this
"configurations": {
    "production": {
        "fileReplacements": [
            {
                "replace": "src/environments/environment.ts",
                "with": "src/environments/environment.prod.ts"
            }
        ],
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false, // change to true

Then run
ng build --prod

But I wouldnt recommend you turn on source map in production because it will increase a bundle size

A: you can try
ng build --prod --source-map=true|false

angular.io/cli/build


text:
Q: Code Blocks GNU GCC cannot find include file Using the GNU GCC compiler I get the error:
fatal error: stats.h: No such file or directory.

stats.h is a header file I created for the project but for whatever reason it is not being found? I have #include "stats.h" where necessary and I am very confused. Any help appreciated, thanks.

A: Add folder containing stats.h to compiler search directories list
Project | Build options | Search Directories | Compiler


text:
Q: Recommendations for portable download manager? I need a portable download manager which can run of Windows 7 / Windows 2008 Server with ability to run on 32/64 bit.
Any suggestions ?

A: FreeDownloadManager
Full-featured and portable. Highly recommended!

A: Browsers can do the job of download managers. so if you want something small and easy use Opera.


text:
Q: In Quickbook PHP API how to queue up multiple call to same methods using the enqueue() Currently am using the consolibyte php quickbook api for syncing the magento orders as sales orders in the quickbook desktop using the enqueue()
here the problem when you try to sync multiple orders only the last order was queued up with quickbook to sync and the remaing  order were not syncing
here is my code i was using to queue
    $Queue = QuickBooks_WebConnector_Queue_Singleton::getInstance($dsn);
    $Queue->enqueue(QUICKBOOKS_QUERY_CUSTOMER,$customerid,'10', $customers);

A:
here the problem when you try to sync multiple orders only the last order was queued up with quickbook to sync and the remaing order were not syncing

The only way this can happen is if you tell it to happen. e.g. you are telling the framework to only queue up the last order.
Something like this will result in multiple things being queued up, and will work just fine:
$order_ids = array( 1, 2, 3, 4, 5, 6 );
foreach ($order_ids as $order_id)
{
  $Queue->enqueue(QUICKBOOKS_ADD_SALESORDER, $order_id);
}

This:

$Queue->enqueue(QUICKBOOKS_QUERY_CUSTOMER,$customerid,'10', $customers);

Makes little to no sense at all without more context. It doesn't make any sense for the following reasons:

*

*You're not queueing up orders here, you're queuing up customers. If you're trying to queue up orders, why are you using QUICKBOOKS_QUERY_CUSTOMER?

*What is $customers set to?  Why are you setting it?

*Why are you passing in a string '10'?
If you expect an answer to your question post the rest of your code so we can see what you're doing.


text:
Q: spring cloud sidecar for rails app in heroku Does it make sense to take advantage of netflix oss components(zuul, eureka, etc) from rails api microservices deployed in heroku?
What is the right way to deploy both a rails app and a spring cloud sidecar in heroku. same dyno? single web process? Also, what is the recommended approach for a centralized/dynamic configuration in heroku. spring cloud config, archaius, etcd?


text:
Q: Writing to logfile does not work with Android 4.2 Jelly Bean I am trying to integrate some code for a school project that takes sensor values received over bluetooth and write them to a comma separated data log file. I can not get a simple example of the file writing functionality running on Jelly Bean after trying dozens of examples. The code works perfectly fine on my personal device running android 4.0.2. I am trying to run the following example on a motorolla xt1060, and although there is no removable sd card, my understanding is that this does not preclude the use of external storage. I've used both linux with MTPFS and windows with the default drivers to look for the file anywhere on the file-system but it has never shown itself. I can see text files when I create them with the MTPFS mounted via terminal and when I take pictures so I don't think MTP is causing the problem.
Here is the most simple java example I've written that works on 4.0 and not 4.2:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        path.mkdirs();
        File file = new File(path, "test.txt");
        Log.d("FILE_TEST", file.getPath());

        try {
            Log.d("FILE_TEST", "Creating buffer");
            BufferedWriter buf = new BufferedWriter(new FileWriter(file));
            Log.d("FILE_TEST", "Writing to buffer");
            buf.write("Hello FS!\n");
            Log.d("FILE_TEST", "Flushing buffer");
            buf.flush();
            Log.d("FILE_TEST", "Closing file");
            buf.close();
        } catch (IOException e) {
            Log.d("FILE_TEST","Caught Exception:" + e.toString());
        }
    }
}

The manifest xml contains the following:
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

And nothing exciting I can see happens in the log:
02-18 00:26:36.075: I/InputReader(859): Reconfiguring input devices.  changes=0x00000004
02-18 00:26:36.075: I/InputReader(859): Device reconfigured: id=6, name='synaptics_dsx_i2c', size 720x1280, orientation 3, mode 1, display id 0
02-18 00:26:36.533: I/SurfaceFlinger(290): triggers:    (post: 0:16)    (compose: 0:2)  (frame: 0:12)   (gap: 411:6519) (rate: 247) (66116 frames)
02-18 00:26:36.561: I/SurfaceFlinger(290): triggers:    (jitter: 0:0)   (missed: 0) (105353 vsyncs)
02-18 00:26:37.045: I/ActivityManager(859): Config changes=480 {1.0 311mcc480mnc en_US ldltr sw360dp w360dp h567dp 320dpi nrml port finger -keyb/v/h -nav/h s.23?spn}
02-18 00:26:37.051: I/InputReader(859): Reconfiguring input devices.  changes=0x00000004
02-18 00:26:37.051: I/InputReader(859): Device reconfigured: id=6, name='synaptics_dsx_i2c', size 720x1280, orientation 0, mode 1, display id 0
02-18 00:26:37.101: W/ContextImpl(1155): Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1115 android.content.ContextWrapper.sendBroadcast:338 com.motorola.motocare.util.TriggerHelper$TriggerBuilder.send:76 com.motorola.motocare.internal.frameworkevents.PauseResumeTrigger.handleFrameworkEvent:53 com.motorola.motocare.internal.frameworkevents.FwEventMonitor$FrameworkListener.processFrameworkEvent:114
02-18 00:26:37.124: I/SurfaceFlinger(290): triggers:    (post: 0:16)    (compose: 0:2)  (frame: 0:12)   (gap: 411:6520) (rate: 247) (66124 frames)
02-18 00:26:37.127: D/FILE_TEST(19084): /storage/emulated/0/Download/test.txt
02-18 00:26:37.127: D/FILE_TEST(19084): Creating buffer
02-18 00:26:37.127: D/FILE_TEST(19084): Writing to buffer
02-18 00:26:37.127: D/FILE_TEST(19084): Flushing buffer
02-18 00:26:37.127: D/FILE_TEST(19084): Closing file
02-18 00:26:37.186: I/SBar.NetworkController(1008): onReceive: Intent.ACTION_CONFIGURATION_CHANGED Received
02-18 00:26:37.186: I/SBar.NetworkController(1008): updateTelephonySignalStrength:  No service
02-18 00:26:37.290: I/SurfaceFlinger(290): triggers:    (post: 0:16)    (compose: 0:2)  (frame: 0:12)   (gap: 411:6522) (rate: 247) (66132 frames)
02-18 00:26:37.718: I/SurfaceFlinger(290): triggers:    (post: 0:16)    (compose: 0:2)  (frame: 0:12)   (gap: 411:6522) (rate: 247) (66159 frames)
02-18 00:26:37.743: I/InputReader(859): Reconfiguring input devices.  changes=0x00000004
02-18 00:26:37.743: I/InputReader(859): Device reconfigured: id=6, name='synaptics_dsx_i2c', size 720x1280, orientation 1, mode 1, display id 0
02-18 00:26:37.744: I/ActivityManager(859): Config changes=480 {1.0 311mcc480mnc en_US ldltr sw360dp w598dp h335dp 320dpi nrml land finger -keyb/v/h -nav/h s.24?spn}
02-18 00:26:37.776: W/ContextImpl(1155): Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:1115 android.content.ContextWrapper.sendBroadcast:338 com.motorola.motocare.util.TriggerHelper$TriggerBuilder.send:76 com.motorola.motocare.internal.frameworkevents.PauseResumeTrigger.handleFrameworkEvent:53 com.motorola.motocare.internal.frameworkevents.FwEventMonitor$FrameworkListener.processFrameworkEvent:114
02-18 00:26:37.817: I/SurfaceFlinger(290): triggers:    (post: 0:16)    (compose: 0:2)  (frame: 0:12)   (gap: 411:6523) (rate: 247) (66164 frames)
02-18 00:26:37.829: I/SurfaceFlinger(290): triggers:    (jitter: 0:0)   (missed: 0) (105404 vsyncs)

Does anyone have an idea why this would work on 4.0 and not 4.2?

A: /storage/emulated/0/Download/test.txt

According to your log, your text file is being written to the emulated part of the external storage.
In Android 4.2, Google added multi-user support, and it virtualized the external storage. That's what it means when it says emulated.
By the way, you should also check if the Professor didn't create a limited user account just for you. The lack of a data plan shouldn't prevent you from registering with Google Play.

A: When I restarted the phone this morning, the file system was littered with test files I had made. I tested by trying to write other new files and trying to view them from a desktop but they would only become visible after restart of the phone. Emulation isn't the problem, that is then standard new way of android sharing a drive for multiple users. I'll double check the behvior on Windows in a bit to confirm if its a bug with the phone and not just the Linux drivers.


text:
Q: Google Plus & Javascript - Disable scrolling when choosing circles? I've created a lot of Circles. And so when I hover over the "Add to Circles" google plus button, a small div pops up that allows me to vertically scroll through my circles.
The really cool part is that it disable body scrolling. So when I scroll to the bottom of the circles viewer, the body doesn't budge.
How is this possible with javascript?
(I've found a hacky way to do it:
$('body').css({'overflow':'hidden'});
$(document).bind('scroll',function () {
window.scrollTo(0,0);
});

But Google does it better. The body scroll bar stays in place (it doesn't vanish like my code makes it), and the body is still unscrollable...)
It's important to note (and so far overlooked) that the scroll bar on the body page has to stay in place. It can't vanish like overflow:hidden makes it, because that jerks all of the page content to the right. Google solves this problem somehow...
SCREENSHOT:

A: Try using :
$(document).bind('scroll',function (e) {
    e.preventDefault();
    e.stopPropagation();
    return false;
});


text:
Q: powers, last 3 digits For given $a\in\mathbb{N}$ define $x_1(a)=a$ and $x_{k+1}(a)=a^{x_k}$ for $k=1,2,\dots$. Find the last 3 digits of $\sum_{i=1}^{9}x_i(i)$.
the obvious attempt is to work modulo 1000, but maybe something more tricky would work faster?

A: Using Charmicael's Lambda:
$x_i\equiv x_{i+1}\bmod 4\implies x_{i+1}\equiv x_{i+2}\bmod 20 \implies$
$ x_{i+2}\equiv x_{i+3}\bmod 100\implies x_{i+3}\equiv x_{i+4}\bmod 1000$.
Notice if $a\equiv 1,3,4$ we have $a\equiv a^a$ and if $a\equiv 2$ we have $a^a\equiv a^{a^a}$.
Therefore $x_2\equiv x_3$ always. And so $x_5\equiv x_6\equiv x_7\equiv x_8\equiv x_9\bmod 1000$.
So we must only calculate $x_1,x_2,x_3,x_4,x_5 \bmod 1000$ which should be possible using charmicael's lambda and exponentiation by squaring.


text:
Q: Get ID of children Element on click I am trying to get the id of a children component's element.
<navigation (click)="resetRoute($event)"></navigation

In the navigation component there is a list with routerLinks. Each item has an id.
resetRoute(event) {
  const elementId: string = (event.target as Element).id;
  console.log(elementId);
  console.log(event.srcElement.attributes.id);
  console.log(event.target.attributs.id);
}

All of them return blank or undefined. I am using Angular v10 and TypeScript 4.0.5
In my routing.module.ts: There is a wildcard to another component (e.g Component A).
My goal is to get the route of the children element (e.g. Component B) and navigate to it.
How can I do it? Has anyone a solution out there?

A: I already solved it.
resetRoute() {
  const url: string = this.router.url.replace('/oldParam', '/newParam');
  this.router.navigateByUrl(url);
}

The new url ist {baseURI]/newParam/{eventParam}.
The eventParam is set with the click-function


text:
Q: ScalaCheck not failing? I'm trying to use ScalaTest with ScalaCheck to do property based testing. I've got the tests outlined below:
import org.scalatest.prop.PropertyChecks
import org.scalatest.{FlatSpec, Matchers}

object Calc {
  def add(a:Int, b:Int) = a+b

  def div(a:Int, b:Int) = a/b
}

class PropSpec1 extends FlatSpec with Matchers with PropertyChecks {
  behavior of Calc.getClass.getName

  it should "add integers" in {
    forAll { (a: Int, b: Int) =>
      Calc.add(a, b) shouldEqual a + b
    }
  }

  it should "divide integers" in {
    forAll {
      (a:Int, b:Int) => Calc.div(a, b) shouldEqual a/b
    }
  }
}

Now what I'm seeing is that if I keep running the tests in PropSpec1 over and over, sometimes the second test passes, but most of the time it fails. Now, if 0 isn't tested for b, then obviously it'll pass, but I'd have thought that's one of the things it would always try. I see the same behaviour when running sbt clean test repeatedly; sometimes both tests pass.
Is this normal for property based testing, or is there something I need to do (like always providing my own generator)?

A:
but I'd have thought that's one of the things it would always try

Assumptions are the root of all evil.
Basically, all you've asked Scalacheck to generate for you is a sample of Int's. A valid Int can be one of ~4 billion values.
Since you know that a 0 will case a failure of this function (an Exception gets thrown) you can simply filter it out like so:
forAll { (a:Int, b:Int) =>
  whenever(a != 0 && b != 0) {
    Calc.div(a, b) mustEqual a/b
  }
}

P.S If you check the scaladoc for the whenever function there is a similar example to what you've asked here.


text:
Q: Time to reach max Wi-Fi performance after acquiring WifiLock Consider the case: Wi-Fi is connected and the application is about to perform a network-intense operation (e.g. VoIP call). To guarantee link quality during the operation I acquire WifiLock with flag WIFI_MODE_FULL_HIGH_PERF. Lock is released when operation completes.
Does this immediately brings Wi-Fi to full performance or there is a delay? Should I wait for some interval of time before performing the operation?


text:
Q: Java Mockito Test Static property assign with function I will make a Junit test on the following class
public class myClass{
     public final static String myProp = getMyrPop();

     public static String getMyProp() {
          return "someData";
     }
}

When i try to make a test, i can't mock the function getMyProp(){}
@RunWith(PowerMockRunner.class)
@PrepareForTest(MyClass.class)
public class ExternalIdUtilsTest {
    @Before
    public void init(){
        Mockito.when(MyClass.getMyProp()).thenReturn("Albert");
    }

    @Test
    public void testOne() {
        assertEquals(1,1);
    }
}


text:
Q: Java println() Printing chars I'm trying to print two chars with
System.out.println(char1 + char2);

but it's adding the integer values together and printing the sum...
How do I print the chars themselves?

A: You can't dereference a char, IE tostring, but you can let the java know how to interpret your intentions:
System.out.println(char1 + "" +char2);

A: Try:
System.out.println(Character.toString(char1) + Character.toString(char2));

If your variables are chars
Try:
System.out.println(char1.toString() + char2.toString());

If they are java.lang.Characters

A: Try:
 System.out.println(char1+""+char2);


text:
Q: How to change fragment's status bar color? I have activity where I use five fragments on users touch events. I want to set status bar colours for 3 fragments and no statusbar for other two fragments.
If I use below code in one fragment's onCreateView method it changes activity's status bar and I get white color for all the fragments as I have used getActivity() method. So I am searching for solution for fragments.
getActivity().getWindow.setStatusBatColor(Color.White);

I also tried setting my theme in style.xml and applying to fragemnts root layout in xml but its not working also.
styles.xml
<style name="StatusBarColor" parent="AppBaseTheme">
    <item name="android:statusBarColor">#F5F5F5
    </item>
</style>

fragment1.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:theme="@style/StatusBarColor"
android:background="@color/home_bg_white"
tools:context="mycontext">

thank you in advance for the help.

A: This is the simplest thing you can do :
getActivity().getWindow().setStatusBarColor(getActivity().getColor(R.color.white));

A: If you want to change the status bar color programmatically (and provided the device has Android 5.0) then you can use Window.setStatusBarColor(). It shouldn't make a difference whether the activity is derived from Activity or ActionBarActivity.
Just try doing:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Window window = getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    window.setStatusBarColor(Color.BLUE);
}

Just tested this with ActionBarActivity and it works alright.
Note: Setting the FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag programmatically is not necessary if your values-v21 styles file has it set already, via:
<item name="android:windowDrawsSystemBarBackgrounds">true</item>

Edit 2:-
Create a method in your activity
public void updateStatusBarColor(String color){// Color must be in hexadecimal fromat
 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.parseColor(color));
    }
}

Call this method from your fragment
((ActivityName)getActivity()).updateStatusBarColor("#000000")

A: KOTLIN SOLUTION:
When you create an activity and corresponding fragments (1 activity to multi fragments scheme) then you first set a theme in the manifest(can be automatically) and that theme with all their properties are applied to all activity's fragments unless you override the specific property in the desired fragment.
In your case, that property is status bar colour.
To change your status bar colour you need in your fragments onCreate method put next code:
override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        requireActivity().window.statusBarColor = Color.GREEN

    }

But if you in your theme's style put for example
<item name="android:windowTranslucentStatus">true</item>

Your themes xml:
<style name="Theme.MyTheme.NoActionBar" parent="Theme.MaterialComponents.DayNight.NoActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/red_2091765</item>
    <item name="colorPrimaryVariant">@color/purple_700</item>

    <item name="android:statusBarColor"tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <item name="android:windowTranslucentStatus">true</item> //HERE
    <item name="android:windowTranslucentNavigation">true</item>

</style>

then your status bar colour will not be changed because you first need to clear flags or in short you need to override windowTranslucentStatus by doing this:
requireActivity().window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)

So final code in the situation where you have defined windowTranslucentStatus = true is next:
 override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)

                requireActivity().window.clearFlags
                   (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
                requireActivity().window.statusBarColor = Color.GREEN

            }

Now if you want to do the same for the bottom navigation then the pattern is the same and so on.

A: Just Wright this line in your fragment java class
((AppCompatActivity)requiereActivity()).getWindow().setStatusBarColor(R.color.white);


text:
Q: How do you delete every line inside of a string that doesn't contain a specific word? There's a string with multiple lines of random characters, I'd like to delete every line that doesn't contain the word

:tesTWORD:

For example, this part of the original string
"111"1"13648""
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
"101"1"00000368""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
3646475

Would turn into this:
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b

So basically all lines that don't contain the exact word :tesTWORD: get deleted.
I have tried a bunch of different things like playing around with arrays, but nothing worked like it's supposed to

A: You can use \n to split it into an array,then filter the array,finally using join() to form a new string
str.split('\n').filter(d => d.indexOf(':tesTWORD:') > -1).join('\n')

let str = `"111"1"13648""
PA4123:tesTWORD:a6b4ba21ba54f6bde411930bd864b700"""""
"101"1"00000368""
PA1239:tesTWORD:a6b4ba21ba54f6bde411930b0001cb9d"""
PA0545:tesTWOR:b598944d1ba4c787e411800b8043559c""
""
PA1238:tesTWORD:a6b4ba21ba54f6bde411920b6ba5f90b
PA0545:tesWOR:b598944d1ba4c787e411800b8043559c""
3646475`

let result = str.split('\n').filter(d => d.indexOf(':tesTWORD:') > -1).join('\n')

console.log(result)


text:
Q: Scanner.nextLine() throws java.util.InputMismatchException I'm new to classes and stuff like that. All I'm trying to do for now is to make the inventory hold one item and then when it works I'll research on how to make multiple Item objects and how to keep the program going so the "edit" and "remove" methods work. So basically this a test for an inventory  and items project.
Inventory class:
    When I run the project and enter a String: (S1) it tells me this:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at inventory.items.Inventory.add(Inventory.java:24)
at inventory.items.Inventory.main(Inventory.java:98)

Keep in mind that I'm a beginner and any thing you'll tell me will help. I can't seem to figure out to get this code working.
public class Inventory extends Item implements Actions{
int num1, num2;
String S1;
Item a = new Item();
Item b = new Item();
Scanner Sc = new Scanner(System.in);
@Override
public void add() {

System.out.println("Please enter the new item specifications as follows: 1. Quantity  2. Name  3. Price");

 num1 = Sc.nextInt();

 a.setQuantity(num1);

 S1 = Sc.nextLine();

 a.setName(S1);

 num2 = Sc.nextInt();

 a.setPrice(num2);

}

/**
 *
 * @param b
 */
@Override
public void remove(Item b) {
b = null;
System.gc();
}

/**
 *
 * @param E
 */
@Override
public void edit(String E) {
E = Sc.nextLine();

if(a.getName().equals(b)){
System.out.println("Please edit the item specifications as follows: 1. Quantity  2. Name  3. Price ");

 num1 = Sc.nextInt();

 S1 = Sc.nextLine();

 num2 = Sc.nextInt();

 a.setQuantity(num1);

 a.setName(S1);

 a.setPrice(num2);
 }
 else{
 System.out.println("You can't edit a non existent item. The items are case
 sensitive.");
 }
 }

 /**
 *
 * @param Info
 */
 @Override
 public void info(String Info) {
 if(a.getName().equals(Info)){
 System.out.println("Item name : " + a.getName() + " Item price: " +
 a.getPrice() + " Item Quantity: "  + a.getQuantity());
 }
 else{
 System.out.println("Please enter a an existing item name!");
 }

 }
 public static void main (String [] args){
 Inventory inv = new Inventory();

 Scanner Sc1 = new Scanner(System.in);

 Item a = new Item();
 Item b = new Item();

 String I = "";

 System.out.println("Please enter one of the following commands: 1. add   2.
 edit   3. remove    4. info ");

  I = Sc1.nextLine();

 switch (I){
case "add" :
  inv.add();
  break;
case "edit" :
  System.out.println("Enter the name of the item you want to edit: ");
  String Input2 = Sc1.nextLine();
  inv.edit(Input2);
  break;
case "remove" :
  System.out.println("Enter the name of the item you want to remove: ");
  inv.remove(a);
  break;
case "info" :
  System.out.println("Enter the name of the item you want too see its info.");
  String Inf = Sc1.nextLine();
  inv.info(Inf);
default :
  System.out.println("Please enter a valid command! The commands ARE case-
  sensitive.");
}
}
}

Item class:
This is the superclass of the Inventory class. I'm using getters and setters to set values of new objects in it.
class Item{

private int q,p;
private String n;

private int quantity =  0;
private String name = " ";
private int price = 0;

public void setQuantity(int q){
this.quantity = q;
}
public int getQuantity(){
return q;
}

public void setName(String n){
this.name = n;
}
public String getName(){
return n;
}
public void setPrice(int p){
this.price = p;
}
public int getPrice(){
return p;
}
}

Actions interface:
I'm using this interface to set the actions that can be made to an Item object; changing it's properties.
interface Actions {
void add();
void remove(Item b);
void edit(String E);
void info(String Info);
}

A: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt():

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

You have entered a string where it expected an integer, thats why this exception is thrown. Always read the JavaDosc first. That's your first pointer, that will help you eliminate the most of the "i don't know"-errors.
Check the Input you get!

A: Probably Scanner.next() will solve your problem because Scanner.nextInt() will just read the int value and not the end of line, while Scanner.nextLine() reads the remainder of the line with the number on it.
num1 = Sc.nextInt();

a.setQuantity(num1);

S1 = Sc.next();

a.setName(S1);

num2 = Sc.nextInt();

a.setPrice(num2);

or
simply you can add Sc.nextLine() to read the remainder of the line with the number on it.
num1 = Sc.nextInt();
       Sc.nextLine();

a.setQuantity(num1);

S1 = Sc.nextLine();

a.setName(S1);

num2 = Sc.nextInt();

a.setPrice(num2);

A: After you get num field and enter it, next line will be readed by S1 = Sc.nextLine(); and you are trying to write name field, but num2 = Sc.nextInt(); is running. for this reason you are getting error.


text:
Q: How to identify user when using REST API Not sure the title is appropriate, but here is the problem
1) I have REST API developed using Jersey (Java)
2) I want to use Facebook login to authenticate users
3) Now Once user has logged in to my website using FB, and API are beings accessed from my website using Ajax calls, how do I make sure requests are from already logged in user and also how to get the user identity(profile id etc.)
What would be best approach to address such API usage?

A: The user's 'profile' should be stored and accessed from the HttpSession.  Which your web container should manage for you and most likely will use cookies.  For example tomcat sets a cookie called jsessionid and uses that cookie for managing with session to use and therefore which user is making the request.
Generally for a 'REST' service, the end user should be validated every call.
I would recommend looking into Basic Authentication (over ssl only) and/or O-Auth2.


text:
Q: ¿Como puedo hacer una consulta de no coincidentes? ¡Hola, buenas a todos!
Os comento, tengo la siguiente estructura en esta base de datos:

Bien pues tengo que hacer consultas de cosas no coincidentes.
Por ejemplo, mostrar todos los campos de los clientes que no hayan realizado ningún pedido.
Sé que obviamente tendría que buscar en la tabla de pedidos en código de cliente los que no estén y luego con el join mostrar todo de los clientes, pero no se como hacer para buscar en pedidos si el código del cliente esta o no.
Me estoy volviendo loco para intentar sacarlo y sinceramente no se como hacerlo. ¿Alguien me podría guiar un poco o echarme una mano?
¡Muchas gracias!
Base de datos para importar.

A: Éstos serían los clientes que no han hecho pedidos:
SELECT * FROM clientes WHERE Codigo_de_cliente NOT IN (
    SELECT DISTINCT Codigo_de_cliente FROM pedidos
  );

Si prefieres utilizar LEFT JOIN, puedes hacerlo así:
SELECT DISTINCT clientes.* FROM clientes
  LEFT JOIN pedidos USING(Codigo_de_cliente)
  WHERE pedidos.Numero_de_Pedido IS NULL;

En ambos casos el resultado debería ser:

C07 C09 C10 C11

La verdad es que no sabría cómo explicártelas porque, como me dices que estás tan perdido, no sé por dónde empezar. Te propongo que me dejes tus dudas en los comentarios para ir completando la respuesta progresivamente.
Genial que hayas aportado el volcado en SQL de tu dataset, así podremos realizar las comprobaciones con los mismos datos.
El USING(Codigo_de_cliente) es una forma abreviada de
ON clientes.Codigo_de_cliente=pedidos.Codigo_de_cliente

Son totalmente equivalentes, pero USING sólo lo puedes utilizar cuando, como en este caso, los nombres de los campos coinciden.


text:
Q: How would I go about boundary breaking Madagascar for the PC? I have the files for the Madagascar game for the PC, which I'm very interested in looking into the development of. Specifically, I'd like to perform a sort of boundary-break (i.e. develop/download a free look camera mod). However, any kind of modding advice is appreciated. I'm skilled in programming so happy to learn any languages I may need.
(The game was downloaded here:
https://oldgamesdownload.com/madagascar/)


text:
Q: Google sheets: How to save a single sheet in a spreadsheet file as PDF, where the file name is based on a certain cell content? I feel like this is a simple question that has been answered quite a lot before, yet despite the couple of hours I wasted searching this site (and other sites) for a simply, clear answer to my question, I could not find one; hence my question.
Context
I constantly need to issue invoices that provide details for each production/manufacturing order. I have recently transferred pretty much all of our database content from MS Excel to Google Sheets for all the obvious benefits (especially those that come with being cloud-based). The aforementioned invoices are created using a spreadsheet. This spreadsheet is consisting of several sheets, each one responsible for gathering the relevant data from different source spreadsheet. The main sheet, which contains the main invoice interface, is exported as PDF file with a certain name that is derived a certain cell (typically, B6). This cell contains a formula that displays a combination of several other cells, in other words, this cell is constantly changing and is linked to other cells.
Back when I used to use Excel, I searched the internet and was able to create VBA code and link it to macro command which allowed me to export the invoice sheet with the name being derived from the aforementioned cell without problems. As I activate the macro, the file would instantly gets exported as PDF file where the name is right what I wanted (i.e. name is based on the current content of the cell B6).
The Problem
I couldn't get any of the sources I found on the internet (like this one) to work or to replicate what they had, and I could not create one from scratch by myself.
What I Need
How can I pull this off in Google Sheets? I'm really sorry if this is too easy or posted elsewhere, but as I said before, my experience is quite limited and I could not find what I needed anywhere else.

A: Is something like this what you're looking for?
function exportSheet() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var mainSheetName = 'Main Sheet'; //Change 'Main Sheet' to the name of your main sheet
  var mainSheet = ss.getSheetByName(mainSheetName);
  var name = mainSheet.getRange('B6').getValue(); //Gets the pdf name from cell B6
  var sheets = ss.getSheets(); //Pulls all sheets as an array

  for (var i = 0; i < sheets.length; i++) { //Iterates through all sheets
    if (sheets[i].getSheetName() !== mainSheetName) { //Hides all sheets that are not the main one
      sheets[i].hideSheet()
    }
  }

  DriveApp.createFile(ss.getBlob().getAs('application/pdf').setName(name)); //Exports the main sheet

  for (var i = 0; i < sheets.length; i++) { //Brings back all sheets that were hidden
    sheets[i].showSheet()
  }
}

I tested this in a mock sheet and it worked for me. Please let me know if you have any issues with it, or if I misinterpreted something.

Reference: Export Single Sheet to PDF in Apps Script


text:
Q: Compose not refreshing view on change of mutableStateOf value I have a ViewModel with the property
var uiState by mutableStateOf(UiState())
I have a composable that accesses this value like so
fun AppView(viewModel: BridgeViewModel) {
    val uiState = viewModel.uiState

    when {
        uiState.isLoading -> {
            LoadingView()
        }
        uiState.data != null -> {
            TextToShareView(to = uiState.data)
        }
    }
}

After the composable is created I trigger a function in my ViewModel that changes the state like so
 uiState = UiState(isLoading = true)
The problem is, the composable is not being redrawn when I change the value of state.
Any idea? I can't see how this is different to the official sample in the docs.


text:
Q: Grep for single and double digit i have path name as below,

*

*abc4/2012

*abc4/2013

*abc45/2014

*abc45/2014

When i grep for 45 it is showing one instance of 4 and for 4 its showing all 45.
i need to grep both single digit and double digit separately.

A: egrep '([^0-9]4[^0-9]|[^0-9]45[^0-9])'

Does it for me - that is, 4 surrounded by non-digits, or 45 surrounded by non-digits.


text:
Q: Expand columns based on sequence of ids I would like to create new columns from a column containing an id sequence, say ID1-5.
Say, we have the following tibble:
# A tibble: 3 x 2
  group   id_seq
  <chr>   <chr>
1 A       ID_Nr61-63
2 A       ID_Nr67-69
3 B       ID_Nr73-75

My desired output is:
# A tibble: 3 x 6
  group   id_seq      id1      id2      id3      id4
  <chr>   <chr>       <chr>    <chr>    <chr>    <chr>
1 A       ID_Nr61-64  ID_Nr61  ID_Nr62  ID_Nr63  ID_Nr64
2 A       ID_Nr67-69  ID_Nr67  ID_Nr68  ID_Nr69  NA
3 B       ID_Nr73-75  ID_Nr73  ID_Nr74  ID_Nr75  NA

Appreciate your help! Thanks.

A: We may extract the digits from the id_seq, by rowwise,get the sequence (:) to expand the data and reshape from 'long' to 'wide' with pivot_wider
library(dplyr)
library(tidyr)
library(stringr)
library(data.table)
df1 %>%
   mutate(s1 = as.numeric(str_extract(id_seq, "\\d+")),
    s2 = as.numeric(str_extract(id_seq, "\\d+$"))) %>%
   mutate(rn = row_number()) %>%
  rowwise %>%
  summarise(rn, group, id_seq, se = (s1:s2)) %>%
  mutate(id_seq2 = str_replace(id_seq, "\\d+-\\d+$", as.character(se)),
   rn2 = str_c("id", rowid(rn)), se = NULL) %>%
  pivot_wider(names_from = rn2, values_from = id_seq2) %>%
  select(-rn)

-output
# A tibble: 3 × 6
  group id_seq     id1     id2     id3     id4
  <chr> <chr>      <chr>   <chr>   <chr>   <chr>
1 A     ID_Nr61-64 ID_Nr61 ID_Nr62 ID_Nr63 ID_Nr64
2 A     ID_Nr67-69 ID_Nr67 ID_Nr68 ID_Nr69 <NA>
3 B     ID_Nr73-75 ID_Nr73 ID_Nr74 ID_Nr75 <NA>

Or using base R
lst1 <- lapply(sub("-", ":", sub("ID_Nr", "", df1$id_seq)),
    function(x) paste0("id_seq", eval(parse(text = x))))
 mx <- max(lengths(lst1))
m1 <- do.call(rbind, lapply(lst1, `length<-`, mx))
df1[paste0("id", seq_len(ncol(m1)))] <- m1
df1
  group     id_seq      id1      id2      id3      id4
1     A ID_Nr61-64 id_seq61 id_seq62 id_seq63 id_seq64
2     A ID_Nr67-69 id_seq67 id_seq68 id_seq69     <NA>
3     B ID_Nr73-75 id_seq73 id_seq74 id_seq75     <NA>

data
df1 <- structure(list(group = c("A", "A", "B"), id_seq = c("ID_Nr61-64",
"ID_Nr67-69", "ID_Nr73-75")), class = "data.frame", row.names = c("1",
"2", "3"))

A: here's an alternative:
df <- data.frame(group = c("A", "A", "B"),
             id_seq = c("ID_Nr61-63", "ID_Nr67-69", "ID_Nr73-75"))

library(tidyverse)
df %>%
  mutate(id_new = str_remove(id_seq, "ID_Nr")) %>%
  separate(id_new, into = c("start", "end"), sep = "-") %>%
  pivot_longer(cols = c(start, end)) %>%
  mutate(value = as.numeric(value)) %>%
  group_by(id_seq) %>%
  expand(full_ids = full_seq(value, 1)) %>%
  full_join(df) %>%
  mutate(id_pivot = 1:n()) %>%
  ungroup() %>%
  pivot_wider(values_from = full_ids,
              names_from = id_pivot,
              names_prefix = "id") %>%
  mutate(across(starts_with("id"), ~paste0("ID_Nr", .)))

which gives:
# A tibble: 3 x 5
  id_seq          group id1     id2     id3
  <chr>           <chr> <chr>   <chr>   <chr>
1 ID_NrID_Nr61-63 A     ID_Nr61 ID_Nr62 ID_Nr63
2 ID_NrID_Nr67-69 A     ID_Nr67 ID_Nr68 ID_Nr69
3 ID_NrID_Nr73-75 B     ID_Nr73 ID_Nr74 ID_Nr75

A: You can do this (somewhat close to @akrun's answer):
ll <- sapply(str_extract_all(dat$id_seq, "\\(?[0-9,.]+\\)?"),
                  function(x) sprintf("ID_Nr%d", x[1]:x[2]))
mat <- t(sapply(ll, "length<-", max(lengths(ll))))
dat[paste0("id", seq(ncol(mat)))] <- mat

  group     id_seq     id1     id2     id3     id4
1     A ID_Nr61-64 ID_Nr61 ID_Nr62 ID_Nr63 ID_Nr64
2     A ID_Nr67-69 ID_Nr67 ID_Nr68 ID_Nr69    <NA>
3     B ID_Nr73-75 ID_Nr73 ID_Nr74 ID_Nr75    <NA>

A: data.table option
func <- function(s,e) c(sapply(seq_along(s),function(x) paste0("ID_Nr",seq(s[x],e[x]))))
dcast(
  setDT(dat)[, `:=`(s=str_extract(id_seq,"(?<=r)\\d.?"), e=str_extract(id_seq, "\\d.?$"))][
    ,func(s,e), by=.(group,id_seq)][,id:=paste0("id",1:.N), by=.(group,id_seq)],
  group+id_seq~id,value.var="V1"
)

    group     id_seq     id1     id2     id3     id4
   <char>     <char>  <char>  <char>  <char>  <char>
1:      A ID_Nr61-64 ID_Nr61 ID_Nr62 ID_Nr63 ID_Nr64
2:      A ID_Nr67-69 ID_Nr67 ID_Nr68 ID_Nr69    <NA>
3:      B ID_Nr73-75 ID_Nr73 ID_Nr74 ID_Nr75    <NA>

If more helpful in individual steps (much more readable, :)
# function to get id numbers
func <- function(s,e) c(sapply(seq_along(s),function(x) paste0("ID_Nr",seq(s[x],e[x]))))

# get start and end
setDT(dat)[, `:=`(s=str_extract(id_seq,"(?<=r)\\d.?"), e=str_extract(id_seq, "\\d.?$"))]

# create each id number from start and end
dat <- dat[,func(s,e), by=.(group,id_seq)]

# add id column
dat[, id:=paste0("id",1:.N), by=.(group,id_seq)]

# swing to wide
dcast(dat,group+id_seq~id, value.var="V1")

Input:
dat <- tibble(
  group=c("A","A","B"), id_seq=c("ID_Nr61-64", "ID_Nr67-69", "ID_Nr73-75")
)


text:
Q: Serving django with nginx and uWSGI I followed this post to serve my django project. The project runs well with manage.py runserver and I want to set it up for production. Here are my setting files:
nginx.conf:
upstream django {
    server /tmp/vc.sock;
    #server 10.9.1.137:8002;
}

server {
    listen      8001;
    server_name 10.9.1.137;
    charset     utf-8;
    client_max_body_size 25M;

    location /media  {
        alias /home/deploy/vc/media;
    }
    location /static {
        alias /home/deploy/vc/static;
    }

    location / {
        uwsgi_pass  django;
        include     /etc/nginx/uwsgi_params;
    }
}

uwsgi.ini:
[uwsgi]

chdir           = /home/deploy/vc
wsgi-file      = vc/wsgi.py

master          = true
processes       = 2
#socket          = :8002
socket          = /tmp/vc.sock
chmod-socket    = 666
vacuum          = true

If I use TCP port socket (server 10.9.1.137:8002 and socket = :8002), it's going to be fine. However if I comment them out and use Unix sockets(server /tmp/vc.sock and socket = /tmp/vc.sock), the server will return 502 error. How should I fix it?
EDIT
Here's the nginx error log when I run /etc/init.d/nginx restart
nginx: [emerg] invalid host in upstream "/tmp/vc.sock" in /etc/nginx/conf.d/vc.conf:2
nginx: configuration file /etc/nginx/nginx.conf test failed

And this is the warning when I run uwsgi --ini vc/uwsgi.ini:
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***

Can't I run uWSGI as root?

A: roberto's comment should be an answer!

the syntax in nginx for unix socket path is wrong, you need to prefix
  it with unix:

A: Check your nginx error log, very probably is telling you it does not have permissions to the socket. Unix sockets honour file system permissions, so nginx must have write privilege over the socket file. Short answer: 664 is not enough, you need 666


text:
Q: Auto login by device followed by login by user? Question: Does anyone know of any methods to perform a "second" login without using su, or a means to use su that requires the user to enter their username after the su command is issued?
Situation:  We have multiple types of devices that login to a Linux server.  The users can then choose from options on a menu to execute.  The devices auto login to the system with a different account for each device.  The reason we do this is to limit the number of setup accounts to maintain on the devices to one per device.  The ssh clients we have that we can use all tie an automatic login name to the device account in use (see Juice ssh on android for one example).  Maintaining 40 plus accounts per device on each app is too much overhead for us.
Goal: After the device logs in (primary login) provide a secondary login for the user that will allow them to enter their user id and password.
My first inclination would have been 'su', but 'su' needs a username provided with the command or it defaults to root account.  To keep things simple, I am trying avoid writing more shell code to prompt for the username before issuing a command such as 'su - $username' to accomplish this.
Naturally, any application they login to already asks for username and password, but dropping to the shell and other home built functions rely on the login to provide authentication.

A: What does it matter just getting users to type su - username in the shell, if they must type their username and password in any way?  Only 5 extra characters typing :).
If it's not acceptable by users and you are so lazy as not to want to write single script anymore, just install telnet and telnetd on the server and put the following alias in /etc/bash.bashrc.
alias x='telnet localhost'

Updated:  Don't forget to restrict remote accesses to telnetd port (tcp/23).  You can set up firewall (iptables) or traditional TCP wrapper (/etc/hosts.allow, /etc/hosts.deny - consult hosts_access(5) manual page).