text:
Q: how i set the pagination in the admin in magento2 in custom module? pagination is not working in custom module in admin in magento 2
please tell me how it work in magento 2
<?php
namespace Vendor\Module\Block\Adminhtml\Color;

/**
 * Adminhtml news pages grid
 */
class Grid extends \Magento\Backend\Block\Widget\Grid\Extended
{
    /**
     * @var \Magento\Framework\Module\Manager
     */
    protected $moduleManager;

    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory]
     */
    protected $_setsFactory;

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $_productFactory;

    /**
     * @var \Magento\Catalog\Model\Product\Type
     */
    protected $_type;

    /**
     * @var \Magento\Catalog\Model\Product\Attribute\Source\Status
     */
    protected $_status;
    protected $_collectionFactory;

    /**
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    protected $_visibility;

    /**
     * @var \Magento\Store\Model\WebsiteFactory
     */
    protected $_websiteFactory;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Backend\Helper\Data $backendHelper
     * @param \Magento\Store\Model\WebsiteFactory $websiteFactory
     * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $setsFactory
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Catalog\Model\Product\Type $type
     * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $status
     * @param \Magento\Catalog\Model\Product\Visibility $visibility
     * @param \Magento\Framework\Module\Manager $moduleManager
     * @param array $data
     *
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Magento\Store\Model\WebsiteFactory $websiteFactory,
        \Ocodewire\Designtool\Model\Resource\Color\Collection $collectionFactory,
        \Magento\Framework\Module\Manager $moduleManager,
        array $data = []
    ) {

        $this->_collectionFactory = $collectionFactory;
        $this->_websiteFactory = $websiteFactory;
        $this->moduleManager = $moduleManager;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();

        $this->setId('productGrid');
        $this->setDefaultSort('id');
         $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);

    }

    /**
     * @return Store
     */
    protected function _getStore()
    {
        $storeId = (int)$this->getRequest()->getParam('store', 0);
        return $this->_storeManager->getStore($storeId);
    }

    /**
     * @return $this
     */
    protected function _prepareCollection()
    {
        try{

            $collection =$this->_collectionFactory->load();

            $this->setCollection($collection);

            parent::_prepareCollection();

            return $this;
        }
        catch(Exception $e)
        {
            echo $e->getMessage();die;
        }
    }

    /**
     * @param \Magento\Backend\Block\Widget\Grid\Column $column
     * @return $this
     */
    protected function _addColumnFilterToCollection($column)
    {
        if ($this->getCollection()) {
            if ($column->getId() == 'websites') {
                $this->getCollection()->joinField(
                    'websites',
                    'catalog_product_website',
                    'website_id',
                    'product_id=entity_id',
                    null,
                    'left'
                );
            }
        }
        return parent::_addColumnFilterToCollection($column);
    }

    /**
     * @return $this
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function _prepareColumns()
    {
        // echo "dffdsfsd"; die;
        $this->addColumn(
            'color_id',
            [
                'header' => __('Color Id'),
                'type' => 'number',
                'index' => 'color_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );

        $this->addColumn(
            'color_name',
            [
                'header' => __('Color Name'),
                'type' => 'text',
                'index' => 'color_name',
            ]
        );

        $this->addColumn(
            'color_code',
            [
                'header' => __('Color Code'),
                'index' => 'color_code',
                'class' => 'color code',
            ]
        );

        $this->addColumn(
            'color_code',
            [
                'header' => __('Color Code'),
                'index' => 'color_code',
                'class' => 'color code',
            ]
        );

         $this->addColumn(
            'Edit',
            [
                'header' => __('Edit'),
                'type' => 'action',
                'getter' => 'getId',
                'actions' => [
                    [
                        'caption' => __('Edit'),
                        'url' => [
                            'base' => '*/*/edit',
                            'params' => ['store' => $this->getRequest()->getParam('store')]
                        ],
                        'field' => 'id'
                    ]
                ],
                'filter' => false,
                'sortable' => false,
                'index' => 'stores',
                'header_css_class' => 'col-action',
                'column_css_class' => 'col-action'
            ]
        );

        /*{{CedAddGridColumn}}*/
        $block = $this->getLayout()->getBlock('grid.bottom.links');
        if ($block) {
            $this->setChild('grid.bottom.links', $block);
        }

        return parent::_prepareColumns();
    }

     /**
     * @return $this
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('id');
        $this->getMassactionBlock()->setFormFieldName('id');

        $this->getMassactionBlock()->addItem(
            'delete',
            array(
                'label' => __('Delete'),
                'url' => $this->getUrl('*/*/massDelete'),
                'confirm' => __('Are you sure?')
            )
        );
        return $this;
    }

    /**
     * @return string
     */

    /**
     * @param \Magento\Catalog\Model\Product|\Magento\Framework\Object $row
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl(
            '*/*/edit',
            ['store' => $this->getRequest()->getParam('store'), 'id' => $row->getId()]
        );
    }

     public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', ['_current' => true]);
    }
}

A: Change below line
 $collection =$this->_collectionFactory->load();

To:
 $collection =$this->_collectionFactory->create();

A:
Try This Code

<?php
namespace Vendor\Module\Block\Adminhtml\Color;

/**
 * Adminhtml news pages grid
 */
class Grid extends \Magento\Backend\Block\Widget\Grid\Extended
{
    /**
     * @var \Magento\Framework\Module\Manager
     */
    protected $moduleManager;

    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory]
     */
    protected $_setsFactory;

    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $_productFactory;

    /**
     * @var \Magento\Catalog\Model\Product\Type
     */
    protected $_type;

    /**
     * @var \Magento\Catalog\Model\Product\Attribute\Source\Status
     */
    protected $_status;
    protected $_collectionFactory;

    /**
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    protected $_visibility;

    /**
     * @var \Magento\Store\Model\WebsiteFactory
     */
    protected $_websiteFactory;

    /**
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Backend\Helper\Data $backendHelper
     * @param \Magento\Store\Model\WebsiteFactory $websiteFactory
     * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Set\CollectionFactory $setsFactory
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Catalog\Model\Product\Type $type
     * @param \Magento\Catalog\Model\Product\Attribute\Source\Status $status
     * @param \Magento\Catalog\Model\Product\Visibility $visibility
     * @param \Magento\Framework\Module\Manager $moduleManager
     * @param array $data
     *
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,
        \Magento\Backend\Helper\Data $backendHelper,
        \Magento\Store\Model\WebsiteFactory $websiteFactory,
        \Ocodewire\Designtool\Model\Resource\Color\CollectionFactory $collectionFactory,
        \Magento\Framework\Module\Manager $moduleManager,
        array $data = []
    ) {

        $this->_collectionFactory = $collectionFactory;
        $this->_websiteFactory = $websiteFactory;
        $this->moduleManager = $moduleManager;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();

        $this->setId('productGrid');
        $this->setDefaultSort('id');
         $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);

    }

    /**
     * @return Store
     */
    protected function _getStore()
    {
        $storeId = (int)$this->getRequest()->getParam('store', 0);
        return $this->_storeManager->getStore($storeId);
    }

    /**
     * @return $this
     */
    protected function _prepareCollection()
    {
        try{

            $collection =$this->_collectionFactory->create();

            $this->setCollection($collection);

            parent::_prepareCollection();

            return $this;
        }
        catch(Exception $e)
        {
            echo $e->getMessage();die;
        }
    }

    /**
     * @param \Magento\Backend\Block\Widget\Grid\Column $column
     * @return $this
     */
    protected function _addColumnFilterToCollection($column)
    {
        if ($this->getCollection()) {
            if ($column->getId() == 'websites') {
                $this->getCollection()->joinField(
                    'websites',
                    'catalog_product_website',
                    'website_id',
                    'product_id=entity_id',
                    null,
                    'left'
                );
            }
        }
        return parent::_addColumnFilterToCollection($column);
    }

    /**
     * @return $this
     * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
     */
    protected function _prepareColumns()
    {
        // echo "dffdsfsd"; die;
        $this->addColumn(
            'color_id',
            [
                'header' => __('Color Id'),
                'type' => 'number',
                'index' => 'color_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );

        $this->addColumn(
            'color_name',
            [
                'header' => __('Color Name'),
                'type' => 'text',
                'index' => 'color_name',
            ]
        );

        $this->addColumn(
            'color_code',
            [
                'header' => __('Color Code'),
                'index' => 'color_code',
                'class' => 'color code',
            ]
        );

        $this->addColumn(
            'color_code',
            [
                'header' => __('Color Code'),
                'index' => 'color_code',
                'class' => 'color code',
            ]
        );

         $this->addColumn(
            'Edit',
            [
                'header' => __('Edit'),
                'type' => 'action',
                'getter' => 'getId',
                'actions' => [
                    [
                        'caption' => __('Edit'),
                        'url' => [
                            'base' => '*/*/edit',
                            'params' => ['store' => $this->getRequest()->getParam('store')]
                        ],
                        'field' => 'id'
                    ]
                ],
                'filter' => false,
                'sortable' => false,
                'index' => 'stores',
                'header_css_class' => 'col-action',
                'column_css_class' => 'col-action'
            ]
        );

        /*{{CedAddGridColumn}}*/
        $block = $this->getLayout()->getBlock('grid.bottom.links');
        if ($block) {
            $this->setChild('grid.bottom.links', $block);
        }

        return parent::_prepareColumns();
    }

     /**
     * @return $this
     */
    protected function _prepareMassaction()
    {
        $this->setMassactionIdField('id');
        $this->getMassactionBlock()->setFormFieldName('id');

        $this->getMassactionBlock()->addItem(
            'delete',
            array(
                'label' => __('Delete'),
                'url' => $this->getUrl('*/*/massDelete'),
                'confirm' => __('Are you sure?')
            )
        );
        return $this;
    }

    /**
     * @return string
     */

    /**
     * @param \Magento\Catalog\Model\Product|\Magento\Framework\Object $row
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl(
            '*/*/edit',
            ['store' => $this->getRequest()->getParam('store'), 'id' => $row->getId()]
        );
    }

     public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', ['_current' => true]);
    }
}

The Factory class name is the name of Model class and append with the Factory word. So for our example, we will have TopicFactory class. You must not create this class. Magento will create it for you. Whenever Magento's object manager encounters a class name that ends in the word 'Factory', it will automatically generate the Factory class in the var/generation folder if the class does not already exist. You will see the factory class in

var/generation/<vendor_name>/<module_name>/Model/ClassFactory.php

To instantiate a model object we will use automatic constructor dependency injection to inject a factory object, then use factory object to instantiate the model object.

For More Click Here
I Hope This Helps You

A: It seems this file may be fine.
I would look at file like your grid layout file: specifically, are you having a formkey defined into your layout file?

A: Please follow this
https://meetanshi.com/blog/create-admin-grid-magento-2/
Still you have any issue. Please let me know.
Thanks.


text:
Q: purpose of with() in javascript function I seeing a java script function on web page which used with() at the top of function and rest of function implementation doing within with() statement. I put the function code below for reference.
function calculate()
{
     with (document.loan)
    {
      var loan = parseFloat(loan_amount.value);
      //function implementation goes here
    }
}

Form is define like this in page with name of loan.
<form name="loan" id="loan-form">
   <input type="text" id="loan_amount"/>
  // remaining form elements here
</form>

What is doing this "with" statement and what's it scope ?

A: JavaScript's with statement was intended to provide a shorthand for writing recurring accesses to objects.
So instead of writing
myObj.obj2.obj3.bing = true;
myObj.obj2.obj3.bang = true;

You can write
with (myObj.obj2.obj3) {
    bing = true;
    bang = true;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create incremental number column in pandas dataframe I have a dataframe with incremental float values
   Number
0 0.679484
1 0.079027
2 0.003132
3 0.092761
4 0.055500
5 0.055500
6 0.055500
7 0.003132

i need to add a new column assigning number between 1 -5 based on existing column on the basis of their values in ascending order.

A: You can use Series.rank with method 'dense' which assigns rank from minimum to maximum incrementing by 1 between groups
df['rank'] = df['Number'].rank(method = 'dense').astype(int)

    Number      rank
0   0.679484    5
1   0.079027    3
2   0.003132    1
3   0.092761    4
4   0.055500    2
5   0.055500    2
6   0.055500    2
7   0.003132    1


text:
Q: error of install numpy on linux red hat I am trying to install numpy  from http://www.scipy.org/Download .
by git clone git://github.com/numpy/numpy.git numpy
But, when I ran python setup.py install
I got:
SystemError: Cannot compile 'Python.h'. Perhaps you need to install python-dev|python-devel
Where to get python-dev ?
I tried:
$ easy_install python-devel
Searching for python-devel
Reading http://pypi.python.org/simple/python-devel/
Couldn't find index page for 'python-devel' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for python-devel
error: Could not find suitable distribution for Requirement.parse('python-devel')

and
$ easy_install python-dev
Searching for python-dev
Reading http://pypi.python.org/simple/python-dev/
Couldn't find index page for 'python-dev' (maybe misspelled?)
Scanning index of all packages (this may take a while)
Reading http://pypi.python.org/simple/
No local packages or download links found for python-dev
error: Could not find suitable distribution for Requirement.parse('python-dev')

Any help will be appreciated.
In order to solve the problem of python-dev, I have installed python2.6 in my local dir.
But, when I used python setup.py install --user to install numpy ,
I got:
$ python setup.py install --user
'import site' failed;
use -v for traceback Traceback (most recent call last): File "setup.py", line 18,
in  import os ImportError:
No module named os
in python2.6
I got: >>> import os Traceback (most recent call last): File "", line 1, in  ImportError: No module named os
Any help will be appreciated. thanks
The following links are not helpful because I do not have root right and cannot use sudo.
example1
example2

A: python-dev is not a python module. Actually it's "Header files, a static library and development tools for building Python modules, extending the Python interpreter or embedding Python in applications." You can install it through Synaptic Package Manager,Software Center or yum.

A: On CentOS, the python development libraries are under the name python-devel, not python-dev.
Use sudo yum install python-devel to install them on your CentOS system.

A: If you are in Ubuntu(e.g. Ubuntu 12.04), it is very easy,
sudo apt-get install python-numpy

or you can compile from source through pip(I think on RedHat almost the same):
sudo apt-get install python-dev
sudo apt-get install python-pip
pip install numpy


text:
Q: Only accept numerics characters in textbox I try to do a things very easy but it doesn't works...
I want my textbox accepts only numerics characters. I found a lot of parts of code on internet but none working...
I try this code for example :
    private void TxtNumPoste_TextChanged(object sender, KeyPressEventArgs e)
    {
        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != '.'))
        {
            e.Handled = true;
        }

        // only allow one decimal point
        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
        {
            e.Handled = true;
        }
    }

TxtNumPoste is the name of my TextBox.
Is a person sees an error ?
Thanks for your help.


text:
Q: Shortest Path from city 0 to N (by road/ by Air mixed cost) Okay, I need a nudge in the right direction. I have an array of costs of travelling from city 0 to N and an array of costs of travelling from city 0 to N by flight. I have a limit K on the number of flights I can take when travelling.
For example
N = 3 // there are 3 cities to be visited 0->1 ->2 ->3 in consecutive order
roadTime = { 1, 2, 3};
flightTime = { 2, 1, 6};
K = 2; //take a maximum of 2 flights

I am allowed to travel all by road or use some road and at most K flights and find the minimum cost of travelling from 0 to 3 in the example.
What I tried:
Started out by hand trying to find a possible solution and came up with a binary tree but couldn't represent the tree structure in code (C#) without pulling my hair out - I'm too new to graphs to even think about applying them. But in the process of working it out I then I stumbled on an idea and, thinking I had nailed it, I realized I could find the permutations of the trip from 0 to N with a mix of road cost and flight cost to get the minimum cost:
public int minTime(int N, int[] roadTime, int[] flightTime, int K)
    {
        int n = 0;
        int min = roadTime.Sum();
        while (K > 0)
        {
            char[] s = (new string('A', N - K) + new string('B', K)).ToCharArray();
            do
            {
                n = 0;
                for (int i = 0; i < s.Length; i++)
                {
                    if (s[i] == 'A')
                    {
                        n += roadTime[i];
                    }
                    else
                    {
                        n += flightTime[i];
                    }
                }
                min = (n < min) ? n : min;
            } while (permute(s));
            K--;
        }
        return min;
    }
    public Boolean permute(char[] a)
    {
        int N = a.Length, i = N - 2;
        for (; i >= 0; i--)
            if (a[i] < a[i + 1])
                break;
        if (i < 0) return false;

        for (int j = N - 1; j >= i; j--)
        {
            if (a[j] > a[i])
            {
                var temp = a[i];
                a[i] = a[j];
                a[j] = temp;
                break;
            }
        }
        for (int j = i + 1; j < (N + i + 1) / 2; j++)
        {
            var temp = a[j];
            a[j] = a[N + i - j];
            a[N + i - j] = temp;
        }
        return true;

    }

This works fine but naturally as N is > than 12, there is factorial growth in the number of permutations of the costs. My solution works well up to about 15 cities in reasonable time. I need to find a way to solve this problem so that I can find a minimum cost for 1 to no less than 50 cities.
Even thinking about it intuitively, how can you be sure that you have a minimum of anything if you haven't tried them all?
The idea of permutations is stuck in my head for now so I'm finding it hard to see another way other than through my present 'rose coloured glasses'. I need a nudge to a totally new line of thinking.
Any help is greatly appreciated.
EDIT!!! 18/May/2014:
Found the answer after a nudge in the right direction from Dukeling. Hope someone else finds this useful
public int minTime(int N, int[] roadTime, int[] flightTime, int K)
    {
        int n = 0;
        int min = roadTime.Sum();
        do
        {
            n = 0;
            var sortedDict = (from entry in cost(roadTime, flightTime, N)
                              orderby entry.Value descending
                              where entry.Value > 0 select entry
                  ).Take(K)
                  .ToDictionary(pair => pair.Key, pair => pair.Value);

            for (int i = 0; i < N; i++)
            {
                if (sortedDict.ContainsKey(i))
                {
                    n += flightTime[i];
                }
                else
                {
                    n += roadTime[i];
                }
            }
            min = (n < min) ? n : min;
            K--;
        } while (K > 0);

        return min;
    }
    static Dictionary<int, int> cost (int[] a1, int[] a2, int N)
    {
        Dictionary<int, int> d = new Dictionary<int, int>();
        for(int i = 0; i < N; i++)
        {
            d.Add(i, a1[i] - a2[i]);
        }
        return d;
    }

A: What you want to do is pick flights for at most K routes where it will give the biggest improvement (and obviously not pick any more if there aren't any more that would result in an improvement).
So, in your example:
roadTime   = { 1, 2, 3};
flightTime = { 2, 1, 6};
improvement    -1 1  -3

The only one that shows an improvement (and thus also the biggest improvement) is the second one, so we pick the flight for that one.
Hint - a priority queue might help. No graphs required.

A: Just in case, I would like to offer the Dynamic Programming approach as a vision of your problem.
Assume, that we have a function, which defines the cost for getting to the city, having some number of allowed fly attempts (and unlimited road attempts).
So, the cost of getting to the some city, is depends on the cost of getting to the previous city and number of allowed fly attempts:
Cost(cityNum, flyAttempts) =
    min(
       Cost(cityNum - 1, flyAttempts)    + roadTimeTo[cityNum], // moving by road
       Cost(cityNum - 1, flyAttempts - 1) + flyTimeTo[cityNum], // moving by fly
    );

The base of Dynamic Programming, is:
1) Cost of getting to the starting city:
Cost[0, n] = 0 // n - is any number

2) Cost of getting to any city, when there are no fly attempts:
Cost[n, 0] = Cost[n - 1, 0] + roadCost[n] // n - is any number

We can use bottom-up Dynamic Programming, to solve your problem (I will provide valid Java solution):
public class Fly {

    public static void main(String[] args) {
        int citiesNum = 4;
        int flyAttempts = 2;
        int[] roadCost = new int[] { 1, 2, 3 };
        int[] flyCost = new int[] { 2, 1, 6 };

        int shortestWay =
                shortestWay(roadCost, flyCost, citiesNum, flyAttempts);

        System.out.println(shortestWay);
    }

    public static int shortestWay(
            int[] roadCost,
            int[] flyCost,
            int citiesNum,
            int flyAttempts) {

        // Cost matrix
        int[][] cost = new int[citiesNum][flyAttempts + 1];

        int lastCity = citiesNum - 1;

        // Initializing base conditions of Dynamic Programming
        for (int i = 0; i <= flyAttempts; i++) {
            cost[0][i] = 0;
        }
        for (int i = 1; i <= lastCity; i++) {
            cost[i][0] = cost[i - 1][0] + roadCost[i - 1];
        }

        // Calculating cost matrix
        for (int i = 1; i <= lastCity; i++) {
            for (int j = 1; j <= flyAttempts; j++) {
                cost[i][j] = Math.min(
                        cost[i - 1][j] + roadCost[i - 1],
                        cost[i - 1][j - 1] + flyCost[i - 1]);
            }
        }

        return cost[lastCity][flyAttempts];
    }
}


text:
Q: loading data from json files Im trying to figure something out. If I want to load JSON data from a local file in my angular app, is there a way for me to include or to read the file in angular, or do I need to use some file API to read from the file and store the objects in a array. ty

A: you can use $http for loading json data from json file
var name = angular.module("app", []);

name.controller("ctrlu", ['$scope','$http', function($scope, $http)
        {
            $http.get('js/data.json').success (function(data){
                $scope.guitarVariable = data;
        });

        }]
);

Note:you don't need to include(reference) json file in index.html page


text:
Q: using smtp class in python to send automated emails So i am experimenting with the SMTP module in python and the code i was using, wasnt working. i found a solution on stack overflow which literally was the same code as mine but worked.
Can someone please find a difference or tell me why my code wasnt working
my code is the second block
import smtplib
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login('example@gmail.com','password')
server.sendmail('example@gmail.com','recipient@gmail.com','msg')
server.close()
print("SUCCESS")

import smtplib
server = smtplib.SMTP('smpt.gmail.com', 587)
server.ehlo()
server.starttls()
server.login('example@gmail.com','password')
server.sendmail('example@gmail.com','recipient@gmail.com','msg')
server.close()
print("SUCCESS")

there is no literal difference but the first one works and the second one doesnt

A: Maybe you meant to type
smtp.gmail.com instead of stmp.gmail.com
Next time try diffchecker.com or something similar to make sure the two blocks of code are actually the same, because in this case they aren't in a very important way.

A: I guess you didn't configure your google account to accept your smtp requests.

To be able to send emails via your Gmail account, you need to provide access to it for your application. You can Allow less secure apps or take advantage of the OAuth2 authorization protocol. It's a way more difficult but recommended due to the security reasons.

https://julien.danjou.info/sending-emails-in-python-tutorial-code-examples/


text:
Q: How to test component events when event and handler are in different components? In the reference jasmine test resource, component event(egComponentEvent) registration and handler is done in same component(egEventHandling).Thus, we are able to test the result after event is fired.
https://github.com/forcedotcom/LightningTestingService/blob/master/lightning-component-tests/test/default/staticresources/jasmineExampleTests.resource
/**
     * Component under test: 'c:egEventHandling'
     * This spec shows how to validate a component's handling of component- and
     * application-level events.
     */
    describe('c:egEventHandling', function() {
        it('handles component- and application-level events', function(done) {
            $T.createComponent("c:egEventHandling", null)
            .then(function(component){
                var cmpEvent = component.getEvent("sampleEvent");
                cmpEvent.setParams({"data":"component event fired"});
                cmpEvent.fire()
                expect(component.get("v.message")).toBe("component event fired");
                $T.fireApplicationEvent("c:egApplicationEvent", {"data":"application event fired"});
                expect(component.get("v.message")).toBe("application event fired");
                done();
            }).catch(function(e) {
                done.fail(e);
            });
        });
    });

Facing issue to test the results after component event is fired, when event registration and its handler is done in different components.
We are firing a component level  event in component 1 and the handler is being invoked in Component 2 ,
We are struggling in testing component event where as component is getting fired but we are not able to see the handler invoked in the Component 2
Kindly help us in getting the correct solution for the below code
 $T.createComponent("c:tagr_Tag",attributes,true)
  .then(function(component) {
  var evt = component.getEvent('componentEvent');
  evt.setParam('entity', entity);
  evt.fire();
expect(evt.fire()).tobe.(true);
}

Here event is getting fired from tagr_Tag but handler is not getting invoked from different component.Please help us in arriving to the solution using any approach like spyon or something else.
Thanks in Advance


text:
Q: If you fail a timed quest, are you penalized? The board in front of Pierre's often offers 2-day timed quests. I haven't noticed if failing these quests penalizes me somehow (for instance, lowering my reputation with the quest-giver).
Does failing a quest have any consequences?

A: Thankfully, failing a timed quest does not have any bad consequences. Even if you fail one of those, your relationships and your reputation will stay intact.


text:
Q: Unable to open PDF after it's generated (vb.net) (asp.net) Sorry for this question, but I'm new in .net and vb.net. I really need your help! I generate a PDF file in asp.net (vb.net). It should be opened in a browser automatically, but it gives an error - Failed to load PDF document. I see it's created on a drive and opens properly. What could be an issue?
Protected Sub ExportToPDF(sender As Object, e As EventArgs)

    Response.ContentType = "application/pdf"
    Dim pdfDoc As New Document(PageSize.A4, 50.0F, 10.0F, 10.0F, 10.0F)
    PdfWriter.GetInstance(pdfDoc, New
       FileStream(Context.Server.MapPath("~/ejik.pdf"), FileMode.CreateNew))
    pdfDoc.Open()
    pdfDoc.Add(New Paragraph("What is going on?"))
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.End()

End Sub

Thank you in advance!
P.S.: Sorry, I forgot to mention that I use iTextSharp to create a PDF

A: Your code is all wrong. You are creating a web application, and you create an object of type Document so that you can write a PDF file to disk. (Do you even need that file on disk? You are writing a web application!) Then, instead of sending the file to the end user, you write a Document object to the Response instead of (the bytes of) the file. That can never work, can it?
It would be better if you created the PDF file in memory first:
MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(Assinatura());
document.Close();

Then you take the bytes of that file in memory, and send them to the Response:
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ejik.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();

This is what the comment meant. Instead of pdfDoc, you need to send the byte array of the PDF file. See also iTextSharp is producing a corrupt PDF with Response


text:
Q: Creating a Multiwindowed Cocoa Program - Launching Procedure Suggestions? I'm porting an application I developed in Visual Studio 2008 over to Cocoa.  I'm currently doing a 'learn-as-you-go' approach to Cocoa, so I can experiment with different ideas and techniques in smaller, simpler projects and eventually combine them into one big application.
My program logic is as follows (in a dumbed-down sense).  Items in the list are mandated by my boss.

*

*Application is started
1a. Verify CD program is in drive.

*Verify license. If found and is valid, skip to step 7

*Display license agreement.

*Display serial number prompt.

*Verify and save serial number.

*Hide all prior windows.

*Load main application window

*Intercept requests and commands from main application window, including making a duplicate main application window

*Exit program when requested by user

What would the best bet be for this type of application?  From another question I asked, I found out that I should keep the 'main application' window in a separate XIB file from the rest, because I might need to clone and interact with it.
I know that since Cocoa and Objective-C is based off of C, there is a Main method somewhere.  But what would you all suggest as a starting place for an application like this?

A: So some of this comes down to organization. Like Julien mentioned, you'll want a YouappnameApplicationDelegate class - in fact, Xcode will create and set this up for you when you create a project.
implement the applicationDidFinishLaunching method (which also should be provided by what Xcode gave you), and implement your logic for steps 1 and 2 there (and steps 7, 8, 9).
Steps 3 thru 5 you'll probably want to implement in another class. RegistrationWindowController, or something like that. You may even want to create this window in another nib file (not inside the MainMenu.nib file that Xcode gives you). In the YouappnameApplicationDelegation's applicationDidFinishLaunching method you'd load this nib (see code sample below). That way your code is well organized - which is what Cocoa really guides you to do.
Ok, so now how to load that new nib file:
myInstanceVariable = [[RegistrationWindowController alloc] initWithWindowNibName: @"MyNibName"];
[myInstanceVariable showWindow: self];

RegistrationWindowController should be a subclass of NSWindowController.
That should take you a pretty long way into your research, hope it does help!


text:
Q: Android Emulator Never starts I'm trying starting emulator though Android SDK, I've installed Intel HAXM prperly , the emulator window shows up but it never starts!
I'm getting this:
Starting emulator for AVD 'MyAVD' emulator: WARNING: Increasing RAM size to 1024MB emulator: WARNING: VM heap size set below hardware specified minimum of 48MB emulator: WARNING: Setting VM heap size to 256MB Hax is enabled Hax ram_size 0x40000000 HAX is working and emulator runs in fast virt mode. emulator: WARNING: Host CPU is missing the following feature(s) required for x86_64 emulation: SSE4.1 SSE4.2 POPCNT Hardware-accelerated emulation may not work properly! console on port 5554, ADB on port 5555 VCPU shutdown request EAX=80000001 EBX=01b81000 ECX=c0000080 EDX=00000000 ESI=00013c80 EDI=01fcf000 EBP=00100000 ESP=00547084 EIP=001000fa EFL=00000046 [---Z-P-] CPL=0 II=0 A20=1 SMM=0 HLT=0 ES =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] CS =0010 00000000 ffffffff 00c09b00 DPL=0 CS32 [-RA] SS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] DS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] FS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] GS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] LDT=0000 00000000 00000000 00008200 DPL=0 LDT TR =0020 00000000 00000fff 00808900 DPL=0 TSS64-avl GDT= 000000000053b020 00000030 IDT= 0000000000000000 00000000 CR0=80000011 CR2=0000000000000000 CR3=0000000001fc9000 CR4=00000020 DR0=0000000000000000 DR1=0000000000000000 DR2=0000000000000000 DR3=0000000000000000 DR6=00000000ffff0ff0 DR7=0000000000000400 EFER=0000000000000500 VCPU shutdown request EAX=80000001 EBX=01b81000 ECX=c0000080 EDX=00000000 ESI=00013c80 EDI=01fcf000 EBP=00100000 ESP=00547084 EIP=001000fa EFL=00000046 [---Z-P-] CPL=0 II=0 A20=1 SMM=0 HLT=0 ES =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] CS =0010 00000000 ffffffff 00c09b00 DPL=0 CS32 [-RA] SS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] DS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] FS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] GS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] LDT=0000 00000000 00000000 00008200 DPL=0 LDT TR =0020 00000000 00000fff 00808900 DPL=0 TSS64-avl GDT= 000000000053b020 00000030 IDT= 0000000000000000 00000000 CR0=80000011 CR2=0000000000000000 CR3=0000000001fc9000 CR4=00000020 DR0=0000000000000000 DR1=0000000000000000 DR2=0000000000000000 DR3=0000000000000000 DR6=00000000ffff0ff0 DR7=0000000000000400 EFER=0000000000000500 VCPU shutdown request EAX=80000001 EBX=01b81000 ECX=c0000080 EDX=00000000 ESI=00013c80 EDI=01fcf000 EBP=00100000 ESP=00547084 EIP=001000fa EFL=00000046 [---Z-P-] CPL=0 II=0 A20=1 SMM=0 HLT=0 ES =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] CS =0010 00000000 ffffffff 00c09b00 DPL=0 CS32 [-RA] SS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] DS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] FS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] GS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] LDT=0000 00000000 00000000 00008200 DPL=0 LDT TR =0020 00000000 00000fff 00808900 DPL=0 TSS64-avl GDT= 000000000053b020 00000030 IDT= 0000000000000000 00000000 CR0=80000011 CR2=0000000000000000 CR3=0000000001fc9000 CR4=00000020 DR0=0000000000000000 DR1=0000000000000000 DR2=0000000000000000 DR3=0000000000000000 DR6=00000000ffff0ff0 DR7=0000000000000400 EFER=0000000000000500 VCPU shutdown request EAX=80000001 EBX=01b81000 ECX=c0000080 EDX=00000000 ESI=00013c80 EDI=01fcf000 EBP=00100000 ESP=00547084 EIP=001000fa EFL=00000046 [---Z-P-] CPL=0 II=0 A20=1 SMM=0 HLT=0 ES =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] CS =0010 00000000 ffffffff 00c09b00 DPL=0 CS32 [-RA] SS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] DS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] FS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] GS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] LDT=0000 00000000 00000000 00008200 DPL=0 LDT TR =0020 00000000 00000fff 00808900 DPL=0 TSS64-avl GDT= 000000000053b020 00000030 IDT= 0000000000000000 00000000 CR0=80000011 CR2=0000000000000000 CR3=0000000001fc9000 CR4=00000020 DR0=0000000000000000 DR1=0000000000000000 DR2=0000000000000000 DR3=0000000000000000 DR6=00000000ffff0ff0 DR7=0000000000000400 EFER=0000000000000500 VCPU shutdown request EAX=80000001 EBX=01b81000 ECX=c0000080 EDX=00000000 ESI=00013c80 EDI=01fcf000 EBP=00100000 ESP=00547084 EIP=001000fa EFL=00000046 [---Z-P-] CPL=0 II=0 A20=1 SMM=0 HLT=0 ES =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] CS =0010 00000000 ffffffff 00c09b00 DPL=0 CS32 [-RA] SS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] DS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] FS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] GS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] LDT=0000 00000000 00000000 00008200 DPL=0 LDT TR =0020 00000000 00000fff 00808900 DPL=0 TSS64-avl GDT= 000000000053b020 00000030 IDT= 0000000000000000 00000000 CR0=80000011 CR2=0000000000000000 CR3=0000000001fc9000 CR4=00000020 DR0=0000000000000000 DR1=0000000000000000 DR2=0000000000000000 DR3=0000000000000000 DR6=00000000ffff0ff0 DR7=0000000000000400 EFER=0000000000000500 VCPU shutdown request EAX=80000001 EBX=01b81000 ECX=c0000080 EDX=00000000 ESI=00013c80 EDI=01fcf000 EBP=00100000 ESP=00547084 EIP=001000fa EFL=00000046 [---Z-P-] CPL=0 II=0 A20=1 SMM=0 HLT=0 ES =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] CS =0010 00000000 ffffffff 00c09b00 DPL=0 CS32 [-RA] SS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] DS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] FS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] GS =0018 00000000 ffffffff 00c09300 DPL=0 DS [-WA] LDT=0000 00000000 00000000 00008200 DPL=0 LDT TR =0020 00000000 00000fff 00808900 DPL=0 TSS64-avl GDT= 000000000053b020 00000030 IDT= 0000000000000000 00000000 CR0=80000011 CR2=0000000000000000 CR3=0000000001fc9000 CR4=00000020 DR0=0000000000000000 DR1=0000000000000000 DR2=0000000000000000 DR3=0000000000000000 DR6=00000000ffff0ff0 DR7=0000000000000400 EFER=0000000000000500

Emulator Screen
Emulator Properties
I'm just using the SDK without any Eclipse or Android Studio. This is for testing Ionic Apps.

A: Okay, so I just want to test my ionic apps, whether any emulator or something else. So the best way I found out to use Ionic Lab and run application through CLI commands. Well the Genymotion Emulator worked for me but it was crashing a lot so I decided to go for Ionic Lab. Thanks for the support.


text:
Q: opencart htaccess: How to fix seo keywords in url I have successfully created custom seo url for opencart. But there is a problem.
When I click on products from the main page, it works perfectly fine in displaying what I want:
mywebsite.com/products/classic-print-dress
Then for example I would like to click on category -> dresses, this works fine too:
mywebsite.com/categories/dresses
Here is the problem, when I click category -> Dresses -> Classic Print Dress, I get:
mywebsite.com/categories/dresses/products/classic-print-dress
whereas it should be redirecting to mywebsite.com/products/classic-print-dress
This is wrong and I have no idea why. It seems like it is adding the seo keywords to the url... Where did it go wrong??

A: Yes, Opencart will add category's seo keywords to the url. Basically, you can't tweak its SEO URLs without additional extension.
And even if you overwrite standard seo_url.php, you also need to provide grateful fallback to standard SEO URL module, so existing extensions could work.
You may want to try this SEO URL extension.


text:
Q: All my apps crashing on launch on physical iPhones I was working on a new app but when I tried it on a real device it crashed with a message of

dyld: Library not loaded: @rpath/CFAlertViewController.framework/CFAlertViewController

So, I tried to clean the build, clean project and delete DerivedData, but still crashing with the same message.
I decided to uninstall CFAlertViewController pod and tried again to run the app and it crashed again with no message.

in the end, I removed all pods and the app working successfully on my iPhone.
I tried all my previous apps that contain Cocoa pods but they all crashing on a real device.
I searched a lot for a solution but nothing works for me.
I'm using:

*

*Xcode 11.3.1

*iOS 13.3.1

*Cocoapods 1.8.4

A: In your podfile comment the use_framework! line and run your pod install again.
It is a problem in iOS 13.3.1 with dynamic frameworks


text:
Q: How to know if the uploaded file has been changed? If the user uploads some file to my server and I want to make sure that the file hasn't been changed from the last time the user uploaded it, how can I get this information?
I have a log table with User_id and FileName (the User_id is unique). I delete the file after I read the contents.

A: You can store a hash of the file before deleting it. To see if it is the same file being uploaded, compare the hash with the previous hash. You can do this with one of the HashAlgorithm classes in System.Cryptography, such as SHA1.

"A cryptographic hash function is a deterministic procedure that takes
  an arbitrary block of data and returns a fixed-size bit string, the
  (cryptographic) hash value, such that an accidental or intentional
  change to the data will change the hash value"

Here is some example code to get you started, assuming the variable stream is a stream with your file data (you could use FileStream to open it):
var sha = new System.Security.Cryptography.SHA1Managed();
byte [] hash = sha.ComputeHash(stream);

Now, the variable hash will contain the hash, a fingerprint of the file contents. Even a small change (such as a single bit) will result in a different hash value, but taking the hash on the same file will always return the same hash.

A: Hash is the generic kind of function. Usually to detect changes into large chunks of data, like files, is used some crc
Under linux there is the standard utility cksum
You can spawn a cksum filename and grab the output. Store it, for example in your database, and check on new file incoming.


text:
Q: How to test if a kinit is needed? I would like to add something to my .bashrc file to run a kinit if I need one.  Is there a way to test if I need to do a kinit? Something like this:
if [ kinitNeeded ];
    do kinit;
done

kinitNeeded() { ??? }

A: You could try klist -s. From the man page:
"causes klist to run silently (produce no output), but to still set the exit status according to whether it finds the credentials cache.  The exit status is '0' if klist finds a credentials cache, and '1' if it does not or if the tickets are expired."

A: Try:
klist -s; echo $?

Return 0 if is OK, 1 otherwise

A: I found a solution, but it's a bit of a hack.
if [ `klist 2>&1 | grep -i 'No credentials' | wc -l` -gt 0 ]; then
    kinit
fi


text:
Q: Difference between read and write access (data, IoT) i am a lawyer and currently writing an essay about data access in ioT environments. I often stumble over the distinction between read access and write access. Could someone provide me with an example, preferably in an ioT, mobile app oder plattform context.
(a little context for those who are interested: My argument is that many complementary IoT services require not just read but write access.)
Thank you very much!!

A: Reading data means looking at it. Writing data means changing it. This is fairly basic computing jargon.
For example, when you look at your bank statement online, that is a read; when you send money to someone, that is a write.
I hope you can see why writing might be considered more dangerous than reading.
The word "access" can mean the reading and writing itself, or it can mean whether they're allowed to read and write the data - it's often clear from the context. I could say that "I gave you read-only access to my bank account", which means I told the bank's computer system to allow you to look at my bank account, but not change it. Read-only access can help to mitigate security threats - if someone finds out your password, they can see what's in my account but they can't steal the money.
If a device needs write access to do its job, obviously you can't give it read-only access as a security mitigation, because then it wouldn't be able to do its job.


text:
Q: How to sum up values from each child node into parent in JSON using javascript? I receive a JSON from server which is fluid in structure. Which is a chapter has a stage(s) and/or review-set at root. If a stage exists for sure there will be a review-set array of object or another stage. The review-set contains 2 attributes which hold data.
Here is the sample JSON
    {
    "id": "chapter",
    "chapterName": "Example Chapter",
    "stages": [
        {
            "id": "stage",
            "stages": [
                {
                    "id": "stage",
                    "stages": [],
                    "reviewSets": [
                        {
                            "id":"reviewset-1",
                            "yettoanswer": 2,
                            "answered": 4
                        }
                    ],
                }
            ],
            "reviewSets": [
                {
                    "id": "reviewset-2",
                    "yettoanswer": 3,
                    "answered": 5
                },
                {
                    "id": "rewviewset-3",
                    "yettoanswer": 6,
                    "answered": 0
                }
            ]
        },
        {
            "id": "stage",
            "stages": [
                {
                    "id": "stage",
                    "stages": [],
                    "reviewSets": [
                        {
                            "id": "reviewset-4",
                            "yettoanswer": 0,
                            "answered": 8
                        },
                        {
                            "id": "reviewset-5",
                            "yettoanswer": 4,
                            "answered": 4
                        }
                    ]
                }
            ],
            "reviewSets": [
                {
                    "id": "reviewset-6",
                    "yettoanswer": 1,
                    "answered": 2
                },
                {
                    "id": "reviewset-7",
                    "yettoanswer": 6,
                    "answered": 4
                }
            ]
        }
    ],
    "reviewSets": [
        {
            "id": "reviewset-8",
            "yettoanswer": 0,
            "answered": 2
        },
        {
            "id": "reviewset-9",
            "yettoanswer": 1,
            "answered": 2
        }
    ],
}

Notice, stages and review-sets are array of objects. It can be null, one object or multiple objects.
I want to get the count of "yettoanswer" and "answered" at each "stage" and at root. The result I am looking for is as below:
{
    "id": "chapter",
    "chapterName": "Example Chapter",
    "yettoanswer" : 22,
    "answered" : 31,
    "stages": [
        {
            "id": "stage",
            "yettoanswer" : 11,
            "answered" : 9,
            "stages": [
                {
                    "id": "stage",
                    "yettoanswer" : 2,
                    "answered" : 4,
                    "stages": [],
                    "reviewSets": [
                        {
                            "id":"reviewset-1",
                            "yettoanswer": 2,
                            "answered": 4
                        }
                    ],
                }
            ],
            "reviewSets": [
                {
                    "id": "reviewset-2",
                    "yettoanswer": 3,
                    "answered": 5
                },
                {
                    "id": "rewviewset-3",
                    "yettoanswer": 6,
                    "answered": 0
                }
            ]
        },
        {
            "id": "stage",
            "yettoanswer":11,
            "answered":18,
            "stages": [
                {
                    "id": "stage",
                    "yettoanswer":4,
                    "answered" : 12,
                    "stages": [],
                    "reviewSets": [
                        {
                            "id": "reviewset-4",
                            "yettoanswer": 0,
                            "answered": 8
                        },
                        {
                            "id": "reviewset-5",
                            "yettoanswer": 4,
                            "answered": 4
                        }
                    ]
                }
            ],
            "reviewSets": [
                {
                    "id": "reviewset-6",
                    "yettoanswer": 1,
                    "answered": 2
                },
                {
                    "id": "reviewset-7",
                    "yettoanswer": 6,
                    "answered": 4
                }
            ]
        }
    ],
    "reviewSets": [
        {
            "id": "reviewset-8",
            "yettoanswer": 0,
            "answered": 2
        },
        {
            "id": "reviewset-9",
            "yettoanswer": 1,
            "answered": 2
        }
    ],
}

I would like to achieve above using javascript.

A: As Nina mentioned in the comment, you probably forgot to count the yettoanswers of reviewSets in root as there should be (by your logic) 23, and not 22.

var root = JSON.parse('{ "id": "chapter", "chapterName": "Example Chapter", "stages": [{ "id": "stage", "stages": [{ "id": "stage", "stages": [], "reviewSets": [{ "id": "reviewset-1", "yettoanswer": 2, "answered": 4 }] }], "reviewSets": [{ "id": "reviewset-2", "yettoanswer": 3, "answered": 5 }, { "id": "rewviewset-3", "yettoanswer": 6, "answered": 0 }] }, { "id": "stage", "stages": [{ "id": "stage", "stages": [], "reviewSets": [{ "id": "reviewset-4", "yettoanswer": 0, "answered": 8 }, { "id": "reviewset-5", "yettoanswer": 4, "answered": 4 }] }], "reviewSets": [{ "id": "reviewset-6", "yettoanswer": 1, "answered": 2 }, { "id": "reviewset-7", "yettoanswer": 6, "answered": 4 }] }], "reviewSets": [{ "id": "reviewset-8", "yettoanswer": 0, "answered": 2 }, { "id": "reviewset-9", "yettoanswer": 1, "answered": 2 }] }');
sumAnswers(root);
console.log(root); // `JSON.stringify(root)` if you need a JSON result

function sumAnswers(stage) {
  // introduce new properties to the current stage
  stage.yettoanswer = 0;
  stage.answered = 0;
  // sum up the values of reviewSets
  stage.reviewSets.forEach(function(child) {
    stage.yettoanswer += child.yettoanswer;
    stage.answered += child.answered;
  });
  // call this function for each stage and then
  // sum up the values of stages
  stage.stages.forEach(function(child) {
    sumAnswers(child);
    stage.yettoanswer += child.yettoanswer;
    stage.answered += child.answered;
  });
}

A: You could iterate over the relevant keys and build the sum of the sub levels. the assign to properties to the actual level.

var object = { id: "chapter", chapterName: "Example Chapter", stages: [{ id: "stage", stages: [{ id: "stage", stages: [], reviewSets: [{ id: "reviewset-1", yettoanswer: 2, answered: 4 }], }], reviewSets: [{ id: "reviewset-2", yettoanswer: 3, answered: 5 }, { id: "rewviewset-3", yettoanswer: 6, answered: 0 }] }, { id: "stage", stages: [{ id: "stage", stages: [], reviewSets: [{ id: "reviewset-4", yettoanswer: 0, answered: 8 }, { id: "reviewset-5", yettoanswer: 4, answered: 4 }] }], reviewSets: [{ id: "reviewset-6", yettoanswer: 1, answered: 2 }, { id: "reviewset-7", yettoanswer: 6, answered: 4 }] }], reviewSets: [{ id: "reviewset-8", yettoanswer: 0, answered: 2 }, { id: "reviewset-9", yettoanswer: 1, answered: 2 }] };

[object].reduce(function sum(r, o) {
    var v = ['stages', 'reviewSets'].reduce(function (r, k) {
            return (o[k] || []).reduce(sum, r);
        }, { yettoanswer: 0, answered: 0 });

    Object.keys(r).forEach(function (k) {
        o[k] = (o[k] || 0) + v[k];
        r[k] += o[k];
    });
    return r;
}, { yettoanswer: 0, answered: 0 })

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Options request before Post Requests Can anyone please explain in detail that why ajax uses OPTIONS request before POST request while using headers in APIs.
Is there any way to bypass the OPTIONS request, I just want POST request on my server.
Thanks in advance :)

A: Consider using Axios
https://www.npmjs.com/package/axios
axios.get( url,
{ headers: {"Content-Type": "application/json"} } ).then( res => {
if(res.data.error) {
} else {
doAnything( res.data )
}
}).catch(function (error) {
doAnythingError(error)
});


text:
Q: $A\ne 0:V\to V$ be linear,real vec space $V$ $A\ne 0:V\to V$ be linear,real vec space $V$, $\dim V=n$,$V_0=A(V),\dim V_0=k<n$ and for some $\lambda\in\mathbb{R}, A^2=\lambda A$
Then

*

*$\lambda=1$

*$|\lambda|^n=1$

*$\lambda$ is the only eigen value of $A$

*There is a subspace $V_1\subseteq V$ such that $Ax=0\forall x\in V_1$
$4$ is true definitely as I can chose $V_1$ as kernel of $A$ which is non trivial subspace of $V$, well assuming $\lambda\ne 0$ we get charpoly for $A$ is $x(x-\lambda)=0$ so $0,\lambda$ are eigen value  with some multiplicity so $3$ is false, I have no idea about $1$ and $2$, could any one tell me?

A: Both (1) and (2) are not true.
We'll choose:
$n=2 $
$ A=\left(\begin{array}{cc}
2 & 0\\
0 & 0
\end{array}\right) $
$ V = Sp\left\{(1,0),(0,1) \right\} $
then:
$ \dim(V)=2 $
$ \dim(AV)=1<2 $ (easy multiply)
and we get:
$ A^{2}=2A $. Therefor, those are falses.


text:
Q: Python matplotlib produces empty subplot when trying to make 4 subplots plt.rcParams["figure.figsize"] = (40, 40)

fig, axs = plt.subplots(2, 2)

plt.locator_params(axis='x', nbins=6)

axs[0, 0].plot(xcoords, ycoords)
axs[0, 1].scatter(xcoords,ycoords,s=1)

axs[1, 0].bar(xcoords, ycoords)
axs[1, 1].bar(ycoords, xcoords)

plt.show()

First 3 graphs get created as expected, but the fourth one is just blank
Screenshot
Any help appriciated

A: The default width of a bar for matplotlib.pyplot.bar() is 0.8. That is usually fine, but if your x-axis runs from 0 to 110.000 or so, that is tiny. So tiny, that Matplotlib will not draw the bars, or more likely, they will not be rendered (and even if they were rendered, you wouldn't be able to see them).
So the data is there, just "invisible".
Increase the bar width. For example:
axs[1, 1].bar(ycoords, xcoords, width=100)


text:
Q: Approximation of Cauchy distribution I have a ratio of two random, (dependent or independent) normally distributed variables.
Knowing that the resulting Cauchy-distribution does not produce any moments. May I ask: Is there an approximation to a Cauchy distribution? Can I still get something out of my set of ratios?

A: The ratio of two arbitrary normal random variables is not in general Cauchy.
Even the ratio of two jointly normal random variables is not in general Cauchy.
Let's assume you're dealing with a ratio that does have a Cauchy distribution. Then all manner of quantities converge - including quantiles and many functions of quantiles, trimmed and winsorized moments, and cdfs.

A: Your question assumes that the distribution of the denominator is centered at 0. If this is so, the median and the mad will converge (to 0 and 1, respectively).

nn<-exp(seq(log(10),log(100000),l=20))
aa<-rep(NA,length(nn))
bb<-rep(NA,length(nn))
for(i in 1:length(nn)){
    x1<-rt(nn[i],df=1)
    aa[i]<-median(x1)
    bb[i]<-mad(x1,constant=1)
}
par(mfrow=c(2,1))
plot(bb,type="l",ylab="mad",xlab="log sample size")
plot(aa,type="l",ylab="med",xlab="log sample size")

btw, you have to change the consistency factor in the computation of the mad
 from $1.4826=1/\Phi^{-1}(0.75)$ to $1=1/t^{-1}_{0.75}$ (the quantile function of the Cauchy distribution evaluated at $q=0.75$)

A: First, the ratio is Cauchy only if the denominator distribution is centered at 0.
In any cases, the statistics on the ratio of $y$ and $x$ can be approximated as:
$$\hat{\mu}_{y:x} = \mu_y/\mu_x + \sigma^2_x * \mu_y  / \mu_x^3 + cov(x,y) * \sigma^2_x * \sigma^2_y / \mu_x^2$$
$$\hat{\sigma}^2_{y:x} = \sigma^2_x\times\mu_y / \mu_x^4 + \sigma^2_y / \mu_x^2 - 2 * cov(x,y) * \sigma^2_x * \sigma^2_y / \mu_x^3$$
if one supposes that the variances are neglictable with respect to the mean (see the post How to parameterize the ratio of two normally distributed variables, or the inverse of one?).
However, I think that as suggested in other answers, using the quantiles would be more appropriated.


text:
Q: How to divide this into two elements?

@media (max-width: 1000px) {
    #sub { display: none; }
    #sub2 { width:50%; }
    #sub2 > div:nth-of-type(1):before { content: "First Name - "; }
    #sub2 > div:nth-of-type(2):before { content: "Last Name - "; }
    #sub2 > div:nth-of-type(3):before { content: "Middle Name - "; }
}

First Name

Last Name

Middle Name

foo first

foo Last

foo Middle

When the screen size is of a mobile, I apply css that hides the #sub and put the width of #sub2 as 50%. Then I use div:nth-of-type(1):before {content: "First Name - "; } etc to display the sub headers before the values. Everything works, but the result is something like this:
First Name - first
Last Name - Last
Middle Name - middle

I cannot align the values because what ever style I am setting it's going for the entire "First Name - first". Not just the value "first". How can I fix this?

A: You can float #sub to the left, then #sub2 will be next to #sub. Then you can style #sub and #sub2 separably.

#sub span {display:none;}
@media (max-width: 1000px) {
  #sub {width:120px;float:left;}
  #sub span {display:inline-block;}
}

First Name  -

Last Name  -

Middle Name  -

foo first

foo Last

foo Middle


text:
Q: fa-fa displays a flag icon. Why is this happening? When the class name is specified as "fa-fa" it displays flag icon. However this is not documented in font-awesome. Is this a bug?

A: fa is an alias for fontawesome and it is documented here to show the flag.


text:
Q: How to escape a loop I have a while loop in Main() which goes through several methods. Although one method named ScanChanges() has an if / else statement, in the case of if, it must jump to Thread.Sleep(10000) (at the end of the loop).
static void Main(string[] args)
{
    while (true)
    {
        ChangeFiles();
        ScanChanges();
        TrimFolder();
        TrimFile();
        Thread.Sleep(10000);
    }
}

private static void ChangeFiles()
{
    // code here
}

private static void ScanChanges()
{
}

FileInfo fi = new FileInfo("input.txt");
if (fi.Length > 0)
{
    // How to Escape loop??
}
else
{
    Process.Start("cmd.exe", @"/c test.exe -f input.txt > output.txt").WaitForExit();
}

A: Make ScanChanges return some value indicating whether you must skip to the end of the loop:
class Program
    {
        static void Main(string[] args)
        {

            while (true)
            {
                ChangeFiles();

                bool changes = ScanChanges();

                if (!changes)
                {
                    TrimFolder();

                    TrimFile();
                }
                Thread.Sleep(10000);
            }
        }

private static void ChangeFiles()
{
  // code here
}

private static bool ScanChanges()
{
     FileInfo fi = new FileInfo("input.txt");
     if (fi.Length > 0)
     {
         return true;
     }
     else
     {
         Process.Start("cmd.exe", @"/c test.exe -f input.txt > output.txt").WaitForExit();

         return false;
      }
}

A: Have ScanChanges return a bool if you've reached that if statement within ScanChanges, and then have another if statement in the while loop that skips over those two procedures if ScanChanges comes back true.

A: Make the return value out of ScanChanges, it may be boolean if it going to break loop return true else return false.
Then set break loop condition in main.

A: Use break to get out of the loop.
if (fi.Length > 0)
{
    break;
}


text:
Q: How to find out selected radio option, when android:radiobutton="@null" in android? I am creating a set of radio options where the radio buttons are removed, and I would like to know which option is selected.
Here is the code
 <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="200dp"
        android:orientation="horizontal"
        android:gravity="center_horizontal"
        android:id="@+id/languages"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">

        <RadioButton
            android:id="@+id/english"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingRight="20dp"
            android:text="@string/langtext_english"
            android:textSize="16dp"
            android:checked="true"
            android:button="@null" />

        <RadioButton
            android:id="@+id/bahasaIndonesia"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/langtext_indonesian"
            android:textSize="16dp"
            android:button="hide"/>
    </RadioGroup>

I don't want to show the radio button, but I would like to know which option is selected. onCheckedChangedListener doesn't work as there is no  button. How to do this?
When the option is touched or clicked, I would like to show a Toast.
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
        langChosen = (RadioGroup) rootView.findViewById(R.id.languages);
        langChosen.setOnClickListener(new RadioGroup.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast abc = new Toast(getContext());
                abc.makeText(getContext(), v.toString(),Toast.LENGTH_LONG);
            }

A: You mentioned

I don't want to show the radio button, but I would like to know which option is selected. onCheckedChangedListener doesn't work as there is no button.

I would not say that is true. The RadioGroup still registers changes of the checked radio button. The android:button attribute of RadioButtonjust represents the button you see next to the text/content of the radio button. You still can register to click events of the radio button element itself.
Could it be that you just forgot to call show() on your toast, so you think it's not working?
I supply a tested solution for you here. Let me know if it works for you too.
    RadioGroup group = (RadioGroup)this.findViewById(R.id.languages);
    group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            RadioButton b = (RadioButton)findViewById(radioGroup.getCheckedRadioButtonId());
            Toast.makeText(MainActivity.this, b.getText(), Toast.LENGTH_SHORT).show();
        }
    });

Note that MainActivity.this must be replaced with your corresponding context.

A: I would try the OnClick method with the two buttons, then the method is called, use the ischecked() method to detremine which of the buttons is checked.


text:
Q: Remote Desktop only connects on same network (not using local IP) What could explain remote desktop connection (RDC) failure depending on the client network? I have a RDC that uses my public IP, but the connection only works when the client is on the same network as the host. I would think that the client network would be irrelevant when using the public IP.

*

*Remote desktop connections are enabled on the host.

*The host firewall is letting RD through.

*Port forwarding is set up on the router.

*The whatsmyip.org port scanner shows that the RD port is open.

*I set up the connection on two different Android devices.*

*The connection uses the public IP (or a domain name set up through DDNS).

While a client device is on the local network, I can start the connection with no trouble. Then I disconnect and turn off the WiFi on the client so that it is using the wireless carrier network, and the connection fails with error 0x3000062 ("Remote Desktop Gateway is temporarily unavailable"). I have also tried this with the client on networks at shops around town and from work and always get the same error.
I saw in this question that the person said their ISP was blocking the port. The ISP claims that they are not blocking any ports. My router is behind a modem provided by the ISP, but they claim that the modem is not blocking anything.
*I do not have any other device to test with; I am trying to use the RDC to do work on an Android tablet while my laptop is being repaired.


text:
Q: Scraping a website with selenium in python: Problem in clicking "download images" Buttons Good morning. I am new in using python and webscraping. I have to download a series of images from this link (just the last part of the urll change for the following pages): https://historisch.cbs.nl/detail.php?nav_id=0-1&index=2&id=30568043
What I want to do is click on the two download buttons in order that at the end I download the images on my laptop (https://i.stack.imgur.com/zWAJg.png).
Here is my code until now:
browser = webdriver.Chrome(service=s, options=chrome_options)
for i in range(8047,8051):
    no = str(i)
    browser.get ("https://historisch.cbs.nl/detail.php?nav_id=1-1&index=2&id=3056"+str(i)+".jpeg")

download = WebDriverWait(browser, 5).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="downloadDirect"]')))
download.click()
t.sleep(1)

download = WebDriverWait(browser, 3).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="downloadResLink"]')))
download.click()

I recive this error:
----> 8 download = WebDriverWait(browser, 5).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="downloadDirect"]')))
      9 download.click()
     10 t.sleep(1)

~\anaconda3\lib\site-packages\selenium\webdriver\support\wait.py in until(self, method, message)
     88             if time.monotonic() > end_time:
     89                 break
---> 90         raise TimeoutException(message, screen, stacktrace)
     91
     92     def until_not(self, method, message: str = ""):

TimeoutException: Message:
Stacktrace:
Backtrace:
    Ordinal0 [0x00371ED3+2236115]
    Ordinal0 [0x003092F1+1807089]
    Ordinal0 [0x002166FD+812797]
    Ordinal0 [0x002455DF+1005023]
    Ordinal0 [0x002457CB+1005515]
    Ordinal0 [0x00277632+1209906]
    Ordinal0 [0x00261AD4+1120980]
    Ordinal0 [0x002759E2+1202658]
    Ordinal0 [0x002618A6+1120422]
    Ordinal0 [0x0023A73D+960317]
    Ordinal0 [0x0023B71F+964383]
    GetHandleVerifier [0x0061E7E2+2743074]
    GetHandleVerifier [0x006108D4+2685972]
    GetHandleVerifier [0x00402BAA+532202]
    GetHandleVerifier [0x00401990+527568]
    Ordinal0 [0x0031080C+1837068]
    Ordinal0 [0x00314CD8+1854680]
    Ordinal0 [0x00314DC5+1854917]
    Ordinal0 [0x0031ED64+1895780]
    BaseThreadInitThunk [0x75B4FA29+25]
    RtlGetAppContainerNamedObjectPath [0x779A7BBE+286]
    RtlGetAppContainerNamedObjectPath [0x779A7B8E+238]

If someone could help me, I would be very grateful.

A: You're trying to click on a button located in an iframe. You need to switch to that iframe first, then locate the button, then click on it:
WebDriverWait(browser, 5).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, '//iframe[@class="detail-media-viewer"]')))
t.sleep(5) ## let elements within iframe load properly
[.. do your stuff locating/clicking whatever buttons are there]

If you plan on interacting /locating again some elements from the main page(outside iframe) you need to switch back to main page:
browser.switch_to.default_content()

Selenium documentation can be found here: https://www.selenium.dev/documentation/


text:
Q: Aligned partitioning of 2TB disk with Linux fdisk Is there a way to create a single 2TB partition, which is 4096-byte-sector aligned, on a disk using the standard Linux fdisk (I have tried version 2.17.2)?
I've tried the following things and ran into the described error:

*

*If I simply use the -u flag, it sets the cluster size to one sector of 512 byte. Then, the partition would have to be 3,906,250,000 clusters long and fdisk truncates this number to 2,147,483,647 (2^31-1).

*If I use -b 4096, it allows me to create the partition just fine (with length 488,281,506 sectors), but if I check the size of the resulting partition using blockdev --getsize64, it shows that the partition is only 250GB big, i.e. it is still using a sector size of 512.

*If I try to set the sector and head count using -S 64 -H 32, for example, then it always sets the sector count back to 63, which doesn't divide evenly into 4096 (I know, 32 dividing evenly by 8 is technically enough, but - call me perfectionist - I'd really like to have the partition start at sector 2048 (1MB aligned), as I read is the recommended setting these days.

Is there some combination of parameters that I can pass to fdisk, that will allow me to create a partition that starts at 1MB (sector 2048 [256] for 512-[4096-]byte sectors) and is exaclt 2TB long (3,906,250,000 [488,281,506] sectors for 512-[4096-]byte sectors)?
(I read that I can just use gparted and have it change the drive to GPT partitioning, but I'd really like to know if there is a way to do it with standard fdisk and an MBR partition. I don't see a reason why MBR partitions shouldn't allow for this...)

A: UPDATE:
Newer versions of fdisk (e.g. v2.20.1) do not have the issue of truncating the cluster number as described in the question any more. Therefore, one can now simply use
fdisk -c /dev/sdX

to create a partition starting at 2048 and ending at 3906252047 to create the desired layout.
ORIGINAL ANSWER:
I found one way to do it:
fdisk -S 16 -H 1 -c /dev/sdX

Then, I can create a partition that starts at 129 and ends at 244,140,753.
Now, if I do fdisk -l -u /dev/sdX, I will get:
Disk /dev/sdX: 2000.4 GB, 2000365289472 bytes
1 heads, 16 sectors/track, 244185216 cylinders, total 3906963456 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xee3e796d

   Device Boot      Start         End      Blocks   Id  System
/dev/sdX1            2048  3906252047  1953125000   fd  Linux raid autodetect

and blockdev --getsize64 /dev/sdX1 gives me exactly 2,000,000,000,000.
Now the big question: Does anyone see a problem with the -S 16 -H 1? :)

A: Recent versions of fdisk start the first partition at sector 2048 by default. If you're seeing some other behavior, then either you're using a rather elderly version of fdisk or there's a bug in the version of fdisk that you're using.
You could also use parted or GParted for this task. They both work with MBR disks as well as with GPT disks, so using one of these tools does not necessitate switching to GPT. That said, GPT does have certain advantages, even on smaller disks. They're minor, but you might want to consider using GPT to get these advantages. (These include having CRCs of important data structures to spot problems, having a backup of important data structures to help recovery from some types of problems, having partition labels, eliminating the awkward primary/extended/logical quagmire, and of course supporting over-2TiB disks.)


text:
Q: How can I visit every instance of a particular class using the python Abstract Syntax Tree? My overall goal is to write a flake8 plugin which lints every instantiation of a certain class: Foo which means that I want to traverse the AST of the code and identify every Node which instantiates a Foo
It's easy to write a basic linter, which finds Calls() where the thing being Call()-ed is a Foo:
class FooVisitor(BaseVisitor):
    def generic_visit(self, node):
        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                if node.func.id == "Foo":
                    print("Foo instantiated!!")
        ast.NodeVisitor.generic_visit(self, node)

but then it's trivial to "evade" the linter by simple re-assignment.
import Foo
Bar = Foo
f = Bar()       <----- "f doesn't get linted because Name.id = Bar not Foo"

It's easy enough to "fix" this simple case by keeping a list of Foo aliases in my visitor:
class FooVisitor(BaseVisitor):
    foo_aliases = ["Foo"]

    def generic_visit(self, node):
        if isinstance(node, ast.Assign):
            if isinstance(node.value, ast.Name):
                if node.value.id in self.foo_aliases:
                    self.foo_aliases.append(node.targets[0].id)

        if isinstance(node, ast.Call):
            if isinstance(node.func, ast.Name):
                if node.func.id in self.foo_aliases:
                    print("Foo instantiated!!")
        ast.NodeVisitor.generic_visit(self, node)

but there many are other ways to "evade" my linter.
here are some examples:
import Foo

def get_Foo():
    return Foo

Bar = get_Foo()
f = Bar()

import Foo

def get_Foo():
    return {"foo": Foo}

Bar = get_Foo()["foo"]
f = Bar()

import Foo

def get_Foo():
    return [Foo]

[f() for f in get_Foo()]

etc...
How can I write an general AST visitor which can visit every instantiation of Foo accounting for renames, re-assignments, import-aliases and any other "tricks"?


text:
Q: Is it possible to find the Jewel of Dirgest? Covetous Shen is looking for a particular jewel:

The jewel contains a... powerful creature named Dirgest. He was trapped within it for terrible crimes against his people. [...] Now a flaw has developed in the jewel. Through it, Dirgest can consume the holder's life. I intend to seal his prison, trapping him in it forever.

Most of the other follower/artisan quests come to some kind of resolution (even if it is pretty much non-interactive and tangential to the game), but I don't remember this one ever going anywhere.  Is there more dialog with Shen that I haven't seen where he achieves his goal?
If this isn't resolved through dialog, does Dirgest's jewel exist within the game?  If so, what happens if you manage to find it?  Is Dirgest at all important in the overall lore of the series, or is he just a macguffin for Shen to be seeking?

A: No. This is just a story being spun by Shen to allow for continued conversation and dialog with him. It is not an item you can find in game.

A: Reaper of Souls has brought with it the ability to find the Jewel of Dirgest, though not as you might expect.
Act V takes you to Pandamonium, where you venture into Westmarch. Covetous Shen may give you a quest that takes you into the Unearthed Ruins, where the Jewel of Dirgest should rest.
While Dirgest has made an escape, shattering the jewel, his minion Vekriss lies in wait. Defeating him releases Liria's soul, and provides a cryptic conclusion to the story of The Jewel of Dirgest, as well as the true origins of Shen.

Liria: Zei? Is that you?
Shen: Zei is gone and no more. He is a legend and a myth. The man who stands before you is but a simple jeweler. I have seen the years, And I have loved and lost, and I have grieved and wept.
Liria: Whoever you are, you have freed me, and I am happy to have looked upon your face.
Shen: And I am filled with joy to have seen yours once again. Farewell, and go upon this last journey.

A: Yes, you do find it, though only in  an added quest in Reaper of Souls. It's broken, though, and you slay the Demon who freed Dirgest. You actually get some confirmation that Shen's Zei, as well! And, sorry. You get the Crusader in ROS, not a shapeshifter. :P


text:
Q: Not able to load maven depedency for spark-cloudant. getting Missing artifact cloudant-labs:spark-cloudant:jar:2.0.0-s_2.11 In Java I am adding below maven dependency,
<dependency>
            <groupId>cloudant-labs</groupId>
            <artifactId>spark-cloudant</artifactId>
            <version>2.0.0-s_2.11</version>
        </dependency>

but it is not loading package even in pom.xml file showing below error,

Missing artifact cloudant-labs:spark-cloudant:jar:2.0.0-s_2.11

Can anyone help me please why it is causing issue?
I am able to add another maven dependencies but particularly this is not working..

A: It's not in the official maven repository. (http://search.maven.org/#search%7Cga%7C1%7Cspark-cloudant)
But when you check: https://mvnrepository.com/artifact/cloudant-labs/spark-cloudant/2.0.0-s_2.11 there is note:

Note: this artifact it located at Spark Packages repository
(https://dl.bintray.com/spark-packages/maven/)

So you will need to add following to your pom.xml:
<repositories>
    <repository>
      <id>bintray</id>
      <name>bintray.com</name>
      <url>https://dl.bintray.com/spark-packages/maven/</url>
    </repository>
</repositories>

EDIT:
According to https://spark.apache.org/news/new-repository-service.html

Bintray, the original repository service used for https://spark-packages.org/, is in its sunset process, and will no longer be available from May 1st. To consume artifacts from the new repository service, please replace "dl.bintray.com/spark-packages/maven" with "repos.spark-packages.org" in the Maven pom files or sbt build files in your repositories.

So this should work:
<repositories>
    <repository>
      <id>bintray</id>
      <name>bintray.com</name>
      <url>https://repos.spark-packages.org</url>
    </repository>
</repositories>

A: Check your maven repo to verify that the file name and version matches what you've specified. Most Maven repo's give you an example of what to use, copy/paste.
ex: Sonatype Nexus is a repo that I use and they let you search and get snippets so you never have to worry about typing things wrong.


text:
Q: Identifying a block of unicode using regular expressions I have a list of paths corresponding to xlsx files that I want to import into Stata:
     +--------------------------------------------------------------------+
     |                                                               path |
     |--------------------------------------------------------------------|
  1. |                              G:\Data_backup\Soufang_data\house.dta |
  2. |                        G:\Data_backup\Soufang_data\import_data.log |
  3. |                G:\Data_backup\Soufang_data/哈尔滨\哈尔滨_house.txt  |
  4. |                 G:\Data_backup\Soufang_data/哈尔滨\哈尔滨_land.txt  |
  5. |             G:\Data_backup\Soufang_data/哈尔滨/house\0_银泰城.xlsx  |
     |--------------------------------------------------------------------|
  6. |      G:\Data_backup\Soufang_data/哈尔滨/house\1000_芦家街住宅.xlsx  |
  7. |        G:\Data_backup\Soufang_data/哈尔滨/house\1001_国泰小区.xlsx  |
  8. | G:\Data_backup\Soufang_data/哈尔滨/house\1002_花园街193号小区.xlsx  |
  9. |        G:\Data_backup\Soufang_data/哈尔滨/house\1003_中发郦苑.xlsx  |
 10. |        G:\Data_backup\Soufang_data/哈尔滨/house\1004_荣耀宝座.xlsx  |
     +--------------------------------------------------------------------+

Moreover, each path contains an uncertain Unicode expression (Chinese characters), which is actually a city name (the first block of Unicodes, such as "哈尔滨" in this case).
I would like to extract this Unicode string using a function like regexr.
How can I write the code?

A: Use this patter to match Chinese characters:
[\u4e00-\u9fa5]+

Only take the first match if there is one. Please check out this demo

A: Try this one:
[^\w^\:\\\/]+

https://regex101.com/r/bC2oR0/1
Hope this helps.

A: Stata's otherwise excellent FAQs have not quite caught up with the new Unicode versions of the regular expression functions that were introduced in version 14. These are based on the ICU regular expression engine. The older regexr() ones you mentioned are just for plain ASCII, as is stated in the help file (see help f_regexm). You can learn more about the differences between the two sets of functions here.
If I understand your question, I want something like:
gen city_name = ustrregexs(0) if ustrregexm(path,"[\u4e00-\u9fa5]+")==1

Working from the end, the if-statement at the end will limit to paths where you have one or more relevant Unicode characters and the 0 in ustrregexs(0) tells Stata to return the entire string that satisfies the regular expression in previous ustrregexm() match.

A: If the path structure for the xlsx files is always the same, you could alternatively use a combination of the substr(), strpos() and strrpos() functions:
clear

input strL string
"G:\Data_backup\Soufang_data/哈尔滨/house\0_银泰城.xlsx"
"G:\Data_backup\Soufang_data/哈尔滨/house\1000_芦家街住宅.xlsx"
"G:\Data_backup\Soufang_data/哈尔滨/house\1001_国泰小区.xlsx"
"G:\Data_backup\Soufang_data/哈尔滨/house\1002_花园街193号小区.xlsx"
"G:\Data_backup\Soufang_data/哈尔滨/house\1003_中发郦苑.xlsx"
"G:\Data_backup\Soufang_data/哈尔滨/house\1004_荣耀宝座.xlsx"
end

generate new_string = substr(string, strpos(string, "/") + 1, abs(strpos(string, "/") - ///
                      strrpos(string, "/")) - 1)

list

     +-------------------------------------------------------------------------------+
     |                                                             string   new_st~g |
     |-------------------------------------------------------------------------------|
  1. |             G:\Data_backup\Soufang_data/哈尔滨/house\0_银泰城.xlsx       哈尔滨 |
  2. |      G:\Data_backup\Soufang_data/哈尔滨/house\1000_芦家街住宅.xlsx       哈尔滨 |
  3. |        G:\Data_backup\Soufang_data/哈尔滨/house\1001_国泰小区.xlsx       哈尔滨 |
  4. | G:\Data_backup\Soufang_data/哈尔滨/house\1002_花园街193号小区.xlsx       哈尔滨 |
  5. |        G:\Data_backup\Soufang_data/哈尔滨/house\1003_中发郦苑.xlsx       哈尔滨 |
     |-------------------------------------------------------------------------------|
  6. |        G:\Data_backup\Soufang_data/哈尔滨/house\1004_荣耀宝座.xlsx       哈尔滨 |
     +-------------------------------------------------------------------------------+


text:
Q: Unable to share data between Components in Angular using service I have a login page, where, for the moment, I just have a button that changes the value of the message to be shared between my 'login' page and my 'home' page
However, the updated value of the message is seen only in login component's html as the {{message}}
login.component.ts:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  message: string;
  constructor(public dataService: DataService) { }

  ngOnInit(): void {
    this.dataService.currentMessage.subscribe(message => this.message = message)
  }

  newMessage() {
    console.log(this.message);
    this.dataService.changeMessage("new message");
    //this.dataService.username = "changed";
    console.log(this.message);
  }
}

data.service.ts:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  //username: string;
  private messageSource = new BehaviorSubject<string>("default message");
  currentMessage = this.messageSource.asObservable();

  constructor() {
  //  this.username="original"
  }

  changeMessage(message: string) {
    this.messageSource.next(message)
  }

}

and home.component.ts:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  message: string;
  constructor(public dataService: DataService) { }

  ngOnInit(): void {
    this.dataService.currentMessage.subscribe(message => this.message = message)
  }

}

Why is the {{message}} in my home page staying the same as "default message" when it is changing in the login page on clicking on the button? Please help!


text:
Q: What is Dialyzer's success typing in Elixir? Before asking, I have tried to search on Google to understand it, Because Elixir is not widely used, The number of articles is less. The articles which describe Success typing give too abstract information making it difficult for me to understand.
Can someone please help me to understand it in detail with an example? if possible, please

A: Dialyzer and Elixir's use of types and specs is perhaps one of the most confusing things about the language.  Elixir is unusual because it is a compiled language that is dynamically typed (!!).  The "looseness" of the variable typing is by design: having flexibility there is one of the things that helps you do hot-code swapping (which was one of the things for which Erlang was designed).
Support for type-specs was added after-the-fact.  These declarations are non-essential decorations on top of the functional code -- they don't need to be there, and they don't necessarily need to be totally accurate, which makes them confusing for those of us who have familiarity with strongly-typed languages where any loose interpretation is not tolerated.
Dialyzer offers a way to evaluate the correctness of the function typing -- it can help identify places where perhaps the listed specs are not accurate.  Again, what's confusing here is that this process isn't as strict as we as programmers might expect: sometimes Dialyzer complains about things that are working fine, and sometimes it sees no errors where things are problematic (although its accuracy has improved a lot IMO in the past year alone).
To make sense of this, I find it helpful to remember the purpose of the specs/annotations: they help communicate to humans what a function accepts and returns (the downstream benefits this provides to the compiler I regard as secondary).  So just remember that if you choose to add success-typing to your functions, go slowly and check with Dialyzer often -- any errors that it comes up with should be seen as a disagreement between what YOU say the code should receive and return vs. what Dialyzer sees the code ACTUALLY doing.  If you don't define any specs, there is no disagreement. Combing through your code helps you identify all the possible values that a function might return and Dialyzer is a really good instrument for helping you verify that what you say your function does is what it is actually capable of.


text:
Q: How electricity is consumed I'm trying to understand something about electricity. Is electricity being wasted when you use it?
I mean when you use an electrical appliance, you need to plug it into a socket right? So you create a circle, where electricity goes into your device and returns back into socket... So does any of electricity actually wasted by the device, or does it just go through the device?
Understand what I mean? What the difference between electricity traveling through power cables, or traveling through a TV or a washing machine?


text:
Q: Double backslash in zsh is interpreted to a single backslash ('\\' -> \) In zsh:
>> echo '\\'
\

I expected strings between single quotes to be not interpreted at all, (bash would show //). So I wonder why zsh turns the double backslash here into a single backslash.
Maybe this is an option I can set?

A: ➜  ~ echo $SHELL
/bin/zsh
➜  ~ echo "//"
//
➜  ~ echo '//'
//
➜  ~ echo //
//
➜  ~ echo "\/"
\/
➜  ~ echo '\/'
\/
➜  ~ echo \/
/
➜  ~ which echo
echo: shell built-in command
➜  ~

You may noticed that the zsh has its own built-in echo, therefore you can control the behaviour you expect by the -e/-E option. See http://zsh.sourceforge.net/Doc/Release/Shell-Builtin-Commands.html
➜  ~ echo -E '\\'
\\
➜  ~ echo -e '\\'
\
➜  ~ echo -e '//'
//
➜  ~ echo -E '//'
//
➜  ~

A: echo, by default, is POSIX-compliant in zsh, which means that echo itself will treat certain pairs of characters starting with \ specially. It is true that inside single quotes, nothing is escaped. A single backslash can appear inside single quotes:
% echo '\'
\

Two backslashes can also be passed to echo using '\\'. However, now echo itself treats \\ as a pair representing a single backslash, because certain other pairs are treated specially. Just to name two, \t represents a horizontal tab
% echo 'a\tb'
a   b

while \n represents a linefeed
% echo 'a\nb'
a
b

That means to be able to print the two characters \ and n, for example, you need some way of specifying a backslash without it escaping the following n. That way is with \\:
% echo '\\n'
\n


text:
Q: Cavendish's experiment on concentric conducting shells In a paper  were there was a section addressing Cavendish's experiment on concentric conducting shells which was basically the following : Two conducting spherical shells were put together (like the Russian doll) and a conducting link was connecting these two spheres , a charge was put on the outermost sphere , then we cut the link with silk a a silk thread ,take off the outermost, and see if the inner one had any electrical charge on it , the experiment showed that indeed it doesn't contain any charge . Then the author stated that this was a consequence of the inverse square law , and that if the electric field didn't follow this very law , then upon putting charges on the outermost sphere charges would migrate through the conducting link to the smaller sphere and it would have a charge on it .
How did the author deduce this conclusion ? Why ,if the electric field didn't have the inverse square behavior , the charges would migrate to the smaller sphere ?

A:
How did the author deduce this conclusion?

For the charges to move from the large sphere to the small sphere, there would have to be an electric field inside the large sphere.
The inverse square law could be used to prove that the field inside a conductive hollow charged sphere is zero. It goes like this:
For any given point inside a conductive hollow charged sphere, the fields produced by patches of charge, subtending the equal solid angles on the opposite sides of the sphere, will cancel each other, because the charge magnitudes of the patches will be proportional to the square of their distances to the point of interest, while their fields will be inversely proportional to the square of the same distances.

Why, if the electric field didn't have the inverse square behavior,
  the charges would migrate to the smaller sphere?

The inverse square law is pretty fundamental, so there is no reliable way to tell what exactly would happen, if it did not hold, but, ignoring that for the purpose of the discussion, this would, at least, mean that the proof above would not work.
That does not automatically mean though that the charges would move from the large sphere to the small sphere.
In fact, we can always argue that, as long as the charges repel each other, they should distribute themselves over the outer surface of the large sphere, because this is most favorable distribution from the potential energy standpoint, and, therefore there won't be any charges on the small sphere inside, even with a conducting link connecting the spheres.


text:
Q: How to create an side paragraph in HTML alongside an image? I have image I would like to display in HTML alongside an paragraph, with some information. Essentially, I need the page to have the image on one side of the page and the paragraph on the other. Does a grid need to be use? Is There another way to do this without a grid.
I would suspect that if I do not put a
 after  tag that it will just align itself to  the right.
Is there some CSS involved to do this?

A: The other way to accomplish this (other than the way Sohaib put) is to simply just have both elements be floated to the left or to the right. Margin added to help move the text.

img,
p {
  display: inline-block;
}
img {
  float: left;
  height: 300px;
}
p {
  margin-left: 1rem;
}

Hello World

A: Just float and display CSS properties needed !

img , p {
  display: inline-block;
}

img {
  float: left;
  height: 300px;
}
p {
  float: right;
}

Hello World