text:
Q: Not able to install using apt-get after changing username I recently changed username of my ubuntu account to "admin", earlier it used to be "sunbeam". Now I'm trying to install pylint using apt-get, but I'm getting the following error
admin@inspiron-5567:~$ sudo apt-get install pylint
[sudo] password for admin:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  blt libtcl8.6 libtk8.6 python-astroid python-backports.functools-lru-cache python-concurrent.futures python-configparser python-egenix-mxdatetime python-egenix-mxtools python-isort python-lazy-object-proxy
  python-logilab-common python-mccabe python-setuptools python-singledispatch python-tk python-wrapt tk8.6-blt2.5
Suggested packages:
  blt-demo tcl8.6 tk8.6 pylint-doc python-egenix-mxdatetime-dbg python-egenix-mxdatetime-doc python-egenix-mxtools-dbg python-egenix-mxtools-doc pyro python-unittest2 python-setuptools-doc tix python-tk-dbg
The following NEW packages will be installed:
  blt libtcl8.6 libtk8.6 pylint python-astroid python-backports.functools-lru-cache python-concurrent.futures python-configparser python-egenix-mxdatetime python-egenix-mxtools python-isort
  python-lazy-object-proxy python-logilab-common python-mccabe python-setuptools python-singledispatch python-tk python-wrapt tk8.6-blt2.5
0 upgraded, 19 newly installed, 0 to remove and 5 not upgraded.
Need to get 0 B/3,667 kB of archives.
After this operation, 21.7 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
WARNING: The following packages cannot be authenticated!
  libtcl8.6 libtk8.6 tk8.6-blt2.5 blt python-lazy-object-proxy python-wrapt python-singledispatch python-backports.functools-lru-cache python-setuptools python-astroid python-concurrent.futures python-isort
  python-mccabe python-configparser python-logilab-common pylint python-egenix-mxtools python-egenix-mxdatetime python-tk
Install these packages without verification? [y/N] y
Get:1 file:/home/sunbeam/subuntu1804  libtcl8.6 8.6.8+dfsg-3 [881 kB]
Err:1 file:/home/sunbeam/subuntu1804  libtcl8.6 8.6.8+dfsg-3
  File not found - /home/sunbeam/subuntu1804/./repo/libtcl8.6_8.6.8+dfsg-3_amd64.deb (2: No such file or directory)
Get:2 file:/home/sunbeam/subuntu1804  libtk8.6 8.6.8-4 [693 kB]
Err:2 file:/home/sunbeam/subuntu1804  libtk8.6 8.6.8-4
  File not found - /home/sunbeam/subuntu1804/./repo/libtk8.6_8.6.8-4_amd64.deb (2: No such file or directory)
Get:3 file:/home/sunbeam/subuntu1804  tk8.6-blt2.5 2.5.3+dfsg-4 [572 kB]
Err:3 file:/home/sunbeam/subuntu1804  tk8.6-blt2.5 2.5.3+dfsg-4
  File not found - /home/sunbeam/subuntu1804/./repo/tk8.6-blt2.5_2.5.3+dfsg-4_amd64.deb (2: No such file or directory)
Get:4 file:/home/sunbeam/subuntu1804  blt 2.5.3+dfsg-4 [4,944 B]
Err:4 file:/home/sunbeam/subuntu1804  blt 2.5.3+dfsg-4
  File not found - /home/sunbeam/subuntu1804/./repo/blt_2.5.3+dfsg-4_amd64.deb (2: No such file or directory)
Get:5 file:/home/sunbeam/subuntu1804  python-lazy-object-proxy 1.3.1-1 [20.8 kB]
Err:5 file:/home/sunbeam/subuntu1804  python-lazy-object-proxy 1.3.1-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-lazy-object-proxy_1.3.1-1_amd64.deb (2: No such file or directory)
Get:6 file:/home/sunbeam/subuntu1804  python-wrapt 1.9.0-3 [27.5 kB]
Err:6 file:/home/sunbeam/subuntu1804  python-wrapt 1.9.0-3
  File not found - /home/sunbeam/subuntu1804/./repo/python-wrapt_1.9.0-3_amd64.deb (2: No such file or directory)
Get:7 file:/home/sunbeam/subuntu1804  python-singledispatch 3.4.0.3-2 [9,848 B]
Err:7 file:/home/sunbeam/subuntu1804  python-singledispatch 3.4.0.3-2
  File not found - /home/sunbeam/subuntu1804/./repo/python-singledispatch_3.4.0.3-2_all.deb (2: No such file or directory)
Get:8 file:/home/sunbeam/subuntu1804  python-backports.functools-lru-cache 1.4-2 [5,960 B]
Err:8 file:/home/sunbeam/subuntu1804  python-backports.functools-lru-cache 1.4-2
  File not found - /home/sunbeam/subuntu1804/./repo/python-backports.functools-lru-cache_1.4-2_all.deb (2: No such file or directory)
Get:9 file:/home/sunbeam/subuntu1804  python-setuptools 39.0.1-2 [329 kB]
Err:9 file:/home/sunbeam/subuntu1804  python-setuptools 39.0.1-2
  File not found - /home/sunbeam/subuntu1804/./repo/python-setuptools_39.0.1-2_all.deb (2: No such file or directory)
Get:10 file:/home/sunbeam/subuntu1804  python-astroid 1.6.0-1 [108 kB]
Err:10 file:/home/sunbeam/subuntu1804  python-astroid 1.6.0-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-astroid_1.6.0-1_all.deb (2: No such file or directory)
Get:11 file:/home/sunbeam/subuntu1804  python-concurrent.futures 3.2.0-1 [34.2 kB]
Err:11 file:/home/sunbeam/subuntu1804  python-concurrent.futures 3.2.0-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-concurrent.futures_3.2.0-1_all.deb (2: No such file or directory)
Get:12 file:/home/sunbeam/subuntu1804  python-isort 4.3.4+ds1-1 [30.4 kB]
Err:12 file:/home/sunbeam/subuntu1804  python-isort 4.3.4+ds1-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-isort_4.3.4+ds1-1_all.deb (2: No such file or directory)
Get:13 file:/home/sunbeam/subuntu1804  python-mccabe 0.6.1-2 [8,092 B]
Err:13 file:/home/sunbeam/subuntu1804  python-mccabe 0.6.1-2
  File not found - /home/sunbeam/subuntu1804/./repo/python-mccabe_0.6.1-2_all.deb (2: No such file or directory)
Get:14 file:/home/sunbeam/subuntu1804  python-configparser 3.5.0-1 [59.6 kB]
Err:14 file:/home/sunbeam/subuntu1804  python-configparser 3.5.0-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-configparser_3.5.0-1_all.deb (2: No such file or directory)
Get:15 file:/home/sunbeam/subuntu1804  python-logilab-common 1.4.1-1 [369 kB]
Err:15 file:/home/sunbeam/subuntu1804  python-logilab-common 1.4.1-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-logilab-common_1.4.1-1_all.deb (2: No such file or directory)
Get:16 file:/home/sunbeam/subuntu1804  pylint 1.8.3-1 [342 kB]
Err:16 file:/home/sunbeam/subuntu1804  pylint 1.8.3-1
  File not found - /home/sunbeam/subuntu1804/./repo/pylint_1.8.3-1_all.deb (2: No such file or directory)
Get:17 file:/home/sunbeam/subuntu1804  python-egenix-mxtools 3.2.9-1 [75.3 kB]
Err:17 file:/home/sunbeam/subuntu1804  python-egenix-mxtools 3.2.9-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-egenix-mxtools_3.2.9-1_amd64.deb (2: No such file or directory)
Get:18 file:/home/sunbeam/subuntu1804  python-egenix-mxdatetime 3.2.9-1 [68.3 kB]
Err:18 file:/home/sunbeam/subuntu1804  python-egenix-mxdatetime 3.2.9-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-egenix-mxdatetime_3.2.9-1_amd64.deb (2: No such file or directory)
Get:19 file:/home/sunbeam/subuntu1804  python-tk 2.7.15~rc1-1 [25.9 kB]
Err:19 file:/home/sunbeam/subuntu1804  python-tk 2.7.15~rc1-1
  File not found - /home/sunbeam/subuntu1804/./repo/python-tk_2.7.15~rc1-1_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/libtcl8.6_8.6.8+dfsg-3_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/libtcl8.6_8.6.8+dfsg-3_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/libtk8.6_8.6.8-4_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/libtk8.6_8.6.8-4_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/tk8.6-blt2.5_2.5.3+dfsg-4_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/tk8.6-blt2.5_2.5.3+dfsg-4_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/blt_2.5.3+dfsg-4_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/blt_2.5.3+dfsg-4_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-lazy-object-proxy_1.3.1-1_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-lazy-object-proxy_1.3.1-1_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-wrapt_1.9.0-3_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-wrapt_1.9.0-3_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-singledispatch_3.4.0.3-2_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-singledispatch_3.4.0.3-2_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-backports.functools-lru-cache_1.4-2_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-backports.functools-lru-cache_1.4-2_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-setuptools_39.0.1-2_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-setuptools_39.0.1-2_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-astroid_1.6.0-1_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-astroid_1.6.0-1_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-concurrent.futures_3.2.0-1_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-concurrent.futures_3.2.0-1_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-isort_4.3.4+ds1-1_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-isort_4.3.4+ds1-1_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-mccabe_0.6.1-2_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-mccabe_0.6.1-2_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-configparser_3.5.0-1_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-configparser_3.5.0-1_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-logilab-common_1.4.1-1_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-logilab-common_1.4.1-1_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/pylint_1.8.3-1_all.deb  File not found - /home/sunbeam/subuntu1804/./repo/pylint_1.8.3-1_all.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-egenix-mxtools_3.2.9-1_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-egenix-mxtools_3.2.9-1_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-egenix-mxdatetime_3.2.9-1_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-egenix-mxdatetime_3.2.9-1_amd64.deb (2: No such file or directory)
E: Failed to fetch file:/home/sunbeam/subuntu1804/./repo/python-tk_2.7.15~rc1-1_amd64.deb  File not found - /home/sunbeam/subuntu1804/./repo/python-tk_2.7.15~rc1-1_amd64.deb (2: No such file or directory)
E: Unable to fetch some archives, maybe run apt-get update or try with --fix-missing?

I already used answers from How to change administrator username? to change my username from "sunbeam" to "admin" but now as I use the "apt-get" to install anything, it tries to fetch files from /home/sunbeam/subuntu1804/./repo/.. which clearly doesn't exist now as sunbeam is renamed to admin. So my question is how to install anything using apt-get as file paths have changed?
How can I fix the problem?

A: the following is from comments
It looks like an incorrect entry in your sources (/etc/apt/sources) to me, where you need to modify an entry that points to your old user directory to your new $HOME path (I'm assuming you hard-coded the old directory as a source which has now changed)
The command
grep sunbeam /etc/apt/sources.list

I would expect to produce no results. If it does; these need to be changed to reflect your new $HOME directories name.
The fastest fix in my opinion is to edit the file & make it reflect the new directory.  I would use
sudo vim /etc/apt/sources.list

but you can replace vim with your favorite editor, or change the file with sed (stream-edit) etc.


text:
Q: Parenthesis in Node Express POST Route not found I am mocking a POST route in Express for testing MS XRM.
Working Route:
http://localhost:3000/api/data/v8.0/something

app.post('/api/data/v8.0/something', function (req, res) {
  res.send({data:'1234A'});
});

Failing Route:
http://localhost:3000/api/data/v8.0/something(ABC)/somethingelse

app.post('/api/data/v8.0/something(ABC)/somethingelse', function (req, res) {
  res.send({data:'1234A'});
});

A: Parentheses in route paths have special meaning, but it looks like you can escape them like this:
app.post('/api/data/v8.0/something[(]ABC[)]/somethingelse', function (req, res) {
  res.send({data:'1234A'});
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Merge array recursively in extended class I have the following code in php:
<?php
interface someInterface {
    public function foo();
}

class A implements someInterface {
    public function foo(){
        return [
            'a' => 'some value',
            'b' => 'some value',
            'c' => [
                'ca' => 'some value',
                'cb' => 'some value',
                'cc' => 'some value'
            ]
        ];
    }
}

class B extends A {
    public function foo(){
        return [
            'a' => 'some value 2',
            'c' => [
                'ca' => 'some value 3',
                'cb' => 'some value 4'
            ]
        ];
    }
}

Doing the following
$b = new B();
var_dump($b->foo());

must give me the following output
[
    'a' => 'some value 2',
    'b' => 'some value',
    'c' => [
        'ca' => 'some value 3',
        'cb' => 'some value 4',
        'cc' => 'some value'
    ]
]

Does anyone know how to achieve this?
Anyone can extend class A and I don't want other users to manually use array_merge_recursive for achieving this.
Thanks in advance

A: You can have a class in the middle that does the work. It should have another method that will be inherited and later used. The only condition here is to not use foo() in public, but getFoo() instead
interface someInterface {
    public function foo();
}

class A implements someInterface {
    public function foo(){
        return [
            'a' => 'some value',
            'b' => 'some value',
            'c' => [
                'ca' => 'some value',
                'cb' => 'some value',
                'cc' => 'some value'
            ]
        ];
    }
}

class Middle extends A {
    public function getFoo() {
        return array_merge_recursive(parent::foo(), $this->foo());
    }
}

class B extends Middle {
    public function foo(){
        return [
            'a' => 'some value 2',
            'c' => [
                'ca' => 'some value 3',
                'cb' => 'some value 4'
            ]
        ];
    }
}

$b = new B();
var_dump($b->getFoo());

This could also be achieved making foo() protected and a magic __call() method which does the work of getFoo(). Then calling $b->foo() will trigger __call() thus resulting in merging that parent and this contexts of foo() and spitting them out.
By the way, array merge recursive will not result into the exactly the same output you do want, anyway, you can do whatever logic you need in getFoo() (or in __call())
A problem here could be that if foo() has lower access modifier than public you cannot have it in an interface. Luckily, abstract classes could have abstract protected methods which will obligate the childred to implement this method.
A sample scenario of the __call() way and obligating members to have protected foo() could be:
abstract class Base {
    abstract protected function foo();
}

abstract class A {
    protected function foo(){
        return [
            'a' => 'some value',
            'b' => 'some value',
            'c' => [
                'ca' => 'some value',
                'cb' => 'some value',
                'cc' => 'some value'
            ]
        ];
    }
}

class Middle extends A {
    public function __call($name, $args) {
        if ($name == 'foo')
            return array_merge_recursive(parent::foo(), $this->foo());
    }
}

class B extends Middle {
    protected function foo(){
        return [
            'a' => 'some value 2',
            'c' => [
                'ca' => 'some value 3',
                'cb' => 'some value 4'
            ]
        ];
    }
}

$b = new B();
var_dump($b->foo());

This way B will have some problems with autocompletion of foo.
If One does not know the "hack" when writing $b-> will not recieve suggestion for foo().
A little more hacks can resolve this in at least Netbeans and PHPStorm
Annotating that Middle has a public foo() method before definition of Middle class:
/**
 * @method foo
 */
class Middle extends A {

Later annotating that the instance of B is actually an instance of Middle:
$b = new B();
/* @var $b Middle */

Afterwards writing $b-> will result into suggesting the foo() method.
It might be better if there is another class that inherits B and has no methods, but only annotations, but as I understood, classes like B will be written from other people and they might not be familiar with this convention.

A: You could try with this:
<?php

interface someInterface
{
    public function foo();
}

class A implements someInterface
{
    public function foo()
    {
        return [
            'a' => 'some value',
            'b' => 'some value',
            'c' => [
                'ca' => 'some value',
                'cb' => 'some value',
                'cc' => 'some value'
            ]
        ];
    }
}

class B extends A
{
    public function foo()
    {
        $parent = parent::foo();
        $arr = [

            'a' => 'some value 2',
            'c' => [
                'ca' => 'some value 3',
                'cb' => 'some value 4'
            ]
        ];

        return $this->mergeArrays($arr, $parent);

    }

    private function mergeArrays($ar1, $ar2)
    {
        foreach ($ar1 as $key => $item) {
            if (is_array($item)) {
                if (isset($ar2[$key])) {
                    $ar2[$key] = $this->mergeArrays($item, $ar2[$key]);
                } else {
                    $ar2[$key] = $item;
                }
            } else {
                $ar2[$key] = $item;
            }
        }
        return $ar2;
    }

}

$b = new B();
var_dump($b->foo());

Output:

array(3) { ["a"]=> string(12) "some value 2" ["b"]=> string(10) "some
  value" ["c"]=> array(3) { ["ca"]=> string(12) "some value 3" ["cb"]=>
  string(12) "some value 4" ["cc"]=> string(10) "some value" } }


text: Q: When I updated Ubuntu it ask me to restart when I restart it then it say that Ubuntu has been blocked by current security When I updated my Ubuntu it ask me  to restart , when I restart it says Ubuntu has been blocked by current security policy then I click OK it say verification failed access denied then I click enter then it say default default boot device missing or boot failed insert recovery media and hit any key then select boot manager to choose a new boot device or recovery media then there is three option I click three but it say no bootable device -- please restart system plz help me


text:
Q: Accumulation point and Adherence points of $X \subset R$: $ X = \left\{1, \frac{1}{2}, \frac{1}{3}, \frac{1}{4},..., \frac{1}{n},...\right\}$ The Set $X \subset R$: $$ X = \left\{1, \frac{1}{2}, \frac{1}{3}, \frac{1}{4},..., \frac{1}{n},...\right\}$$

*

*Each value of $X$ set is a point of adherence? Yes.

*Each value of $X$ set is isolated, because is not an accumulation point? Yes

*There is only one accumulation point: $0$?

*$0$ is also an adherence value?
I thinking Iam making a confusion on the last 2 questions:
The third and fourth question are correct?
I think they are. But I can't formulate a formal answer.
Any help?

A: The sequence $\{ 1/n\}_1^\infty $ converges to $0$ so every neighborhood of $0$ contains infinitely many points of the sequence, so $0$ is  a limit point.
$0$ is the only limit point becasue the points of the sequende are isolted points.
A limit point is an adherent point as well, so $0$ is an adherent point for your set.

A: I assume the metric is Euclidean metric.

for 3rd one

A point $a\in \mathbb R$ is an accumulation point of $X$ if for all $r\gt 0, \{B(a,r)-\{a\}\}\cap X\neq \emptyset$.
Let $a\in \mathbb R\setminus\{0\}$.
If $a\lt0,$ choose $r=\frac{|a|}{2}$.
If $a\gt1,$ choose $r=\frac{a-1}{2}$.
If $a\in(0,1)\setminus X,a$ lies in between $\frac{1}{n+1},\frac{1}{n}$for some $n\in \mathbb Z^+$ choose $r=\min \{\frac{1}{2}(\frac{1}{n}-a),\frac{1}{2}(a-\frac{1}{n+1})\}$.
If $a\in X,$ $a=\frac{1}{n}$for some $n\in \mathbb Z^+$ choose $r=\frac{1}{2}(\frac{1}{n}-\frac{1}{n+1})$.
Then for all cases, $\{B(a,r)-\{a\}\}\cap X =\emptyset$.

fourth one

Let $r\gt0$. Then by Euclidean property there is $N\in \mathbb Z^+$ s.t $\frac{1}{r}\gt N$.
Then $B(0,\frac{1}{N})\subseteq B(0,r)$.
So $\frac{1}{N+1} \in  (B(0,\frac{1}{N})\cap X)\subseteq (B(0,r)\cap X )$.
Thus $B(0,r)\cap X \neq \emptyset$ and clerly $B(0,r)\cap \mathbb R\setminus X \neq \emptyset$ Therefore $0$ is an adherence point.


text:
Q: How to install the QField Sync plugin? I am having trouble installing the QField Sync plugin to work with the great QField android app. and would like assistance doing so. The steps I have followed thus far are reproduced below.
(Using QGIS 2.18 via OSGEO4w installer on Windows 7)
When I attempt to install it through the Plugin Manager I get an error message telling me to install the "QGIS2compat" plugin:

http://i.imgur.com/ZilPcBg.png
I select "uninstall" plugin from this dialog.
Then I install the "QGIS2compat" plugin which seems to work properly:

However if I then attempt to install the "QField Sync" plugin afterwards (without restarting) I get the following message:

http://i.imgur.com/Ifi2rMM.png
So I uninstall and, after restarting QGIS (having installed "QGIS2compat" and not "QField Sync") and before QGIS loads fully I get the following error message and "Processing Toolbox" is disabled:

http://i.imgur.com/sajANgT.png
When I try to install the "QField Sync" plugin now, I get the same "UIC" error message as above but I leave it installed anyway and the Plugin Manager tells me that it is "broken" - I also can't find it in any of the Plugin panels/toolbars.

http://i.imgur.com/b1HQkfP.png
So I restart QGIS and get the following error messages in the Log from start up:

http://i.imgur.com/dUtBdAN.png
So I uninstall "QGIS2compat", restart QGIS, the "Processing toolbox" returns but I still have no "QFIELD Sync".
Can anyone help me to install "QField Sync" properly?
[EDIT: Further to the above, now using QGIS version 2.18.11 win7, following similar steps to above, I get the following error:

http://i.imgur.com/d20SKfQ.png]

A: [EDIT: Unfortunately the answer/fix discussed below is no longer working and the same or similar circumstances to those described in the question above persist ... will re-edit if things change again]
This question/problem has now been answered/fixed!
Either one or both of updating to the latest version of QGIS (2.18.1 in this instance) as well as what seems to be an update to the version of the plugin I was having trouble with has resolved the issue.
At the time of the problem the QField Sync plugin was version 0.4 though the 'Available version ... (in QGIS Official Plugin Repository)' is now: 0.8.7
Thanks to all the wonderful folks at QField (opengis.ch) and on GIS SE!

A: Same problem with QGIS 2.18.24 and QfieldSync 1.0.0.
BUT if you :

*

*uninstall QFieldSync

*uninstall qgis2compat

*check the "show experimental extensions" checkbox in the QGIS's extensions parameters

*reinstall QfieldSync,

The problem disapears of its own.
You have installed the 1.1.3 version of QFieldSync, which doesn't need qgis2compat anymore, and works perfectly.


text:
Q: Why can't I hold A D Z keys respectively, while D G C can? I've just noticed a strange behavior of my keyboard.
First, I tried holding A, which created a bunch of aaaaa.
Then I held D, which created aaaaaddddd.
However, when I pressed Z, the key pressing was not detected.
The stranger thing is that when I tested the finding with the D, G, and C combination, it did produce the ccccc.
Furthermore, two separate keys A & Z, or D & Z still work.
I've also found that the last key is only received when the first two keys are among the middle keys of the rows, i.e. D to K, or E to I.
The numpad keys also suffer from this behavior.
This problem is found on all the keyboards I've tested so far (which are all connected to Windows PCs/Laptops). Yet I'm not sure if it's universal on every keyboards. Do you have any explanation to this strange behavior?

A: Keyboard ghosting is when a keyboard doesn't register a key being pressed,
even though the user has pressed it correctly. This feature was used
principally by Windows in the famous Ctrl-Alt-Delete.
Most keyboards today can support up to three ghosted keys,
but this may differ between keyboards.
For such keyboards, three key-presses will be recognized, but following
keys will be ignored. However, the architecture of the internal electrical
circuits will determine how well this will work for any given three keys.
You may find "anti-ghosting" keyboards, which will typically list the
number of supported keys, such as "25-key anti-ghosting".
This won't cover the entire keyboard for anti-ghosting, but will
rather target individual keys that the manufacturer considers tend
to be held down together.
There exist also n-key rollover keyboards that have no upper key limit,
meaning no ghosting at all.


text:
Q: How to reset facebook and twitter auth credentials in meteor telescope I have set my facebook and twiiter auth credentials, however its throwing a redirect URL error. Is there a way to reset the configuration on telescope and redo the social login set up again.
Thanks,
Mayank

A: This should reset your social login setup (from meteor mongo shell):
db.meteor_accounts_loginServiceConfiguration.remove()


text:
Q: How to run this form in QTCreator? I am following 'C++ GUI programming with QT 2ndEd'. I design a form using QTCreator 'Widget' template and save it as form.ui in a directory. Then I write main.cpp file in same directory. The 'Run' option is not enable still. The book says to run qmake to create .pro file and a makefile. How I do that.

A: I don't know what you mean by the 'widget' template because it is not listed in my QTCreator options.
You should create a 'Qt Gui application' project in QTCreator, and then add that form.ui to your new project. With some code to create the form and show it you can build and run it.
How to create a projectin Qt Creator

A: This is probably too late but I feel it is good to add some details regarding this issue. The whole point of the example stated in the book is to show you how to create applications without invoking Qt Creator. In your case, once you've done creating your form, you need to add it in the .pro file as follows:
FORMS += form.ui

This is because you are using your own .pro but the author lets qmake to create the .pro. The difference is that in your own project file, you can customize the file as you wish. This is why you need explicitly to add the form to .pro. If you are lazy, then let the qmake does the job as the author did.


text:
Q: EnableQueryAttribute with PageSize messes up pre-sorted list When I set the [EnableQuery] attribute on a ApiController method in WebAPI 2.2 it seems to break the ordering of response.
[ResponseType(typeof(IEnumerable<Project>))]
[Route("api/user/{userId}/project")]
[EnableQuery(PageSize = 100)]
public async Task<HttpResponseMessage> GetForUser(string userId)
{
    // This gets all projects for the user, and sorts by the last access date
    IEnumerable<Project> projects = await this.projectOperations.GetProjectsForUser(userId);

    return this.Request.CreateResponse(HttpStatusCode.OK, projects);
}

I'm calling it without any OData query parameters, and the resulting project list is 89 items, so in my mind it should not process the array at all.
I've verified that it is in fact the EnableQueryAttribute that does this by creating a new class deriving from EnableQueryAttribute:
public class TestEnableQueryAttribute : EnableQueryAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        // Here the response content is
        // ObjectContent<IEnumerable<Project>>

        base.OnActionExecuted(actionExecutedContext);

        // Afterwards the response content is
        // ObjectContent<System.Web.Http.OData.Query.TruncatedCollection<Project>>
    }
}

The weird thing is that it seems to sort it by the Id property of the Project class. Is this some kind of undocumented convention?
Anyone know how to stop it from messing with my sorting?
I want to have paging, but unless i actually specify a $orderby query parameter it shouldn't do any ordering on its own.

A: By default, Web API sorts on the primary key (usually ID) if no sort options are given, so that the order of the results are stable for pagination.
You can override this with an attribute to sort as per your returned results - tested with Microsoft.AspNet.OData 5.6.0.
[EnableQuery(EnsureStableOrdering = false)]

In earlier versions you might need to invoke ODataQueryOptions yourself - see http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/supporting-odata-query-options.


text:
Q: Conditional uniform convergence in probability I am wondering if it makes sense to say that a (uniform) convergence in probability is conditional on a random variable. Or maybe, there is another way to express that.
Assume two real-valued random variables $X_n$ and $Y_n(\theta)$, where $Y_n$ depends on some parameter $\theta \in \Theta$. I know that $\Theta$ is a compact subset of $\mathbb{R}$.
Convergence in probability: I show that, for any $\varepsilon > 0$ and $\theta \in \Theta$, $\mathbb{P}\left(|Y_n(\theta) - \mathbb{E}(Y_n(\theta)|X_n)|>\varepsilon | X_n\right) \to 0$ as $n$ grows to infinity. So, I conclude that $Y_n(\theta)$ converges in probability to $\mathbb{E}(Y_n(\theta)|X_n)$ conditionally on $X_n$. Is that terminology correct?
Uniform convergence in probability: I also show that, for any $\varepsilon > 0$, $Y_n(\theta)$ and $\mathbb{E}(Y_n(\theta)|X_n)$ are continuously differentiable in $\theta$ and their derivative are bounded on the compact $\Theta$. Can I also say that $Y_n(\theta)$ converges uniformly in probability to $\mathbb{E}(Y_n(\theta)|X_n)$ conditionally on $X_n$?


text:
Q: Pycharm py.test coverage 'Coverage' object has no attribute 'export' I'm trying to run a py.test with coverage in pycharm. On my home pc it works like a charm, however on my laptop I'm getting this stacktrace
/home/david/PycharmProjects/pyCardDeck/virtualenv/bin/python /opt/pycharm/helpers/coverage_runner/run_coverage.py run --omit=\"/opt/pycharm/helpers*\" /opt/pycharm/helpers/pycharm/pytestrunner.py -p pytest_teamcity /home/david/PycharmProjects/pyCardDeck tests
Testing started at 13:15 ...
============================= test session starts ==============================
platform linux -- Python 3.5.2, pytest-3.0.1, py-1.4.31, pluggy-0.3.1
rootdir: /home/david/PycharmProjects/pyCardDeck, inifile:
plugins: cov-2.3.1
collected 35 items

tests/test_card.py ..
tests/test_deck.py ..............................Traceback (most recent call last):
  File "/opt/pycharm/helpers/coverage_runner/run_coverage.py", line 44, in <module>
    main()
  File "/home/david/PycharmProjects/pyCardDeck/virtualenv/lib/python3.5/site-packages/coverage/cmdline.py", line 753, in main
...

========================== 35 passed in 0.89 seconds ===========================
    status = CoverageScript().command_line(argv)
  File "/home/david/PycharmProjects/pyCardDeck/virtualenv/lib/python3.5/site-packages/coverage/cmdline.py", line 480, in command_line
    return self.do_run(options, args)
  File "/home/david/PycharmProjects/pyCardDeck/virtualenv/lib/python3.5/site-packages/coverage/cmdline.py", line 638, in do_run
    self.coverage.export()
AttributeError: 'Coverage' object has no attribute 'export'

Process finished with exit code 1

Running py.test --cov manually works, so it's something inside of Pycharm magic. My laptop is running with Pycharm 2016.1.4 and coverage 4.2

A: That line in cmdline.py should read self.coverage.save(). It's never said export. You should reinstall coverage.py.  I have no idea what changed it.


text:
Q: Formatting the message in Python logging I would like to understand if it's possible and how is it possible, to modify the message part of a log message, using the Python logging module.
So basically, you can format a complete log as:
format = '{"timestamp": "%(asctime)s", "logger_level": "%(levelname)s", "log_message": %(message)s}'

However, I would like to make sure the message part is always in json format. Is there any way I can modify the format of only the message part, maybe with a custom logging.Formatter?
Thank you.

A: The format specification %(message)s tells Python you want to format a string. Try it with %(message)r and it should do the job:
>>> logging.error('{"log_message": %r}', {"a": 55})
ERROR:root:{"log_message": {'a': 55}}

A: There's an example in the Logging Cookbook which shows one way of doing this.Basically:
import json
import logging

class StructuredMessage:
    def __init__(self, message, /, **kwargs):
        self.message = message
        self.kwargs = kwargs

    def __str__(self):
        return '%s >>> %s' % (self.message, json.dumps(self.kwargs))

_ = StructuredMessage   # optional, to improve readability

logging.basicConfig(level=logging.INFO, format='%(message)s')
logging.info(_('message 1', foo='bar', bar='baz', num=123, fnum=123.456))

Of course, you can adapt this basic idea to do something closer to what you want/need.
Update: The formatting only happens if the message is actually output. Also, it won't apply to logging from third-party libraries. You would need to subclass Logger before importing any other modules which import logging to achieve that, but it's a documented approach.


text:
Q: Get the first 300 character of ckeditor content without tags I am using CKEDITOR and after the user enters in the description I want to take the first 300 characters and place them within a summary text box. I am using the code below to make the content move after moving from the description ckeditor box. When i alert the value it will include < p > tags. I cannot strip the string incase the user intends to use them.
CKEDITOR.replace( 'property_description' );
CKEDITOR.instances['property_description'].on('blur', function() {
    var value = CKEDITOR.instances['property_description'].getData();
    alert(value);
});

A: Using plain javascript:
CKEDITOR.replace('property_description');
CKEDITOR.instances['property_description'].on('blur', function() {
    var html = CKEDITOR.instances['property_description'].getData();
    var tmp = document.createElement('div');

    // Strip HTML
    tmp.innerHTML = html;
    var value = tmp.textContent || tmp.innerText;

    // alert truncated value
    alert(value.substring(0, 300);
});

Using jQuery:
CKEDITOR.replace('property_description');
CKEDITOR.instances['property_description'].on('blur', function() {
    var html = CKEDITOR.instances['property_description'].getData();
    var value = $('<div/>', { html: html }).text();

    // alert truncated value
    alert(value.substring(0, 300);
});

A: CKEDITOR.replace( 'property_description' );
CKEDITOR.instances['property_description'].on('blur', function() {
    var value = CKEDITOR.instances['property_description'].getData();
    var chars = (((value.replace(/(<([^>]+)>)/ig, "")).replaceHtmlEntites()).replace(/ /g, '')).substring(0, 300);
        alert(chars)
});

String.prototype.replaceHtmlEntites = function () {
    var s = this;
    var translate_re = /&(nbsp|amp|quot|lt|gt);/g;
    var translate = {"nbsp": "", "\t": "", "amp": "&", "quot": "\"", "lt": "<", "gt": ">"};
    return ( s.replace(translate_re, function (match, entity) {
        return translate[entity];
    }) );
};

Try this with jQuery


text:
Q: Modifie child link with Spring Data Rest Today a have a model and this model has some childs:
{
  "_embedded": {
    "emailTemplates": [
      {
        "identifier": "XPTO",
        "message": "Email whatever",
        "active": true,
        "_links": {
          "self": {
            "href": "http://localhost:8080/emailTemplates/1"
          },
          "communicationChannel": {
            "href": "http://localhost:8080/emailTemplates/1/communicationChannel"
          }
        }
      }
    ]
  },
  "_links": {
    "self": {
      "href": "http://localhost:8080/emailTemplates"
    },
    "profile": {
      "href": "http://localhost:8080/profile/emailTemplates"
    }
  }
}

Look that communicationChannel return with link father to childs.
I need some tip to return a link direct to child like:
 "communicationChannel": {
            "href": "http://localhost:8080/communicationChannel/1"
          }

How can i solve that ?


text:
Q: MediaException: MEDIA_UNAVAILABLE when running project from exported JAR file This is not a duplicate, because Media objects cannot be initialized with getResourceAsStream(). From the docs: "only HTTP, FILE, and JAR URIs are supported."
My JavaFX project works perfectly when I run it from Eclipse, but breaks when I run the executable JAR that I export. I have tried each type of library handling, but none of it works. I'm using JavaFX 2.2 and Eclipse Oxygen March 2018.
public static Media gameMusic;
public static MediaPlayer gameMusicPlayer;
public static MediaView gameMusicMediaView;

// adds music, once for each audio file to be played
gameMusic = new Media(new File("resources/data/music/Kevin_MacLeod_-_Ouroboros_-_Full_Mix.wav").toURI().toString());
bulletSound = new AudioClip(new File("resources/data/music/Photon gun shot.wav").toURI().toString());
explosionSound = new AudioClip(new File("resources/data/music/Explosion+3.wav").toURI().toString());

The directory structure:
+src
  -source files
+resources
  +data
    +music
      -music files
    +fxml
      -fxml files
    +other folders

The error output:
MediaException: MEDIA_UNAVAILABLE : /Users/username/Desktop/resources/data/music/Kevin_MacLeod_-_Ouroboros_-_Full_Mix.wav (No such file or directory)
at javafx.scene.media.Media.<init>(Media.java:407)
at application.Main.start(Main.java:77)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)

Note: when I fixed the code for the filepaths to include the executable's name, it breaks in both Eclipse and the executable

A: The error is pretty simple that it says MEDIA_UNAVAILABLE means that your project is unable to find the resources from the given path. It is probably due to the relative path, you need to provide an Absolute path to find resources from the system.
You could try something like this
Media media = new Media(getHostServices().getDocumentBase() + "/com/projectName/resources/hello.mp3");
MediaPlayer player = new MediaPlayer(media);

EDIT
From the hostServices.getCodeBase() javadoc:

If the application is not packaged in a jar file, this method returns the empty string.

And make sure you have proper imports and extended your app with Application class
import javafx.application.Application;
import javafx.application.HostServices;

public class App extends Application {

}


text:
Q: expander stuck after isexpanded I'm using a storyboard and eventTrigger to fire many event when tab is Clicked which works, but after the expander expanded ,the Expander getting stuck after IsExpanded set to true by storyboard
the Question is how i can make the expander Collapsed/Expanded manual again after it sit to  to true by storyboard??
<Storyboard x:Key="Operation">

            <BooleanAnimationUsingKeyFrames  Storyboard.TargetProperty="(IsExpanded)" Storyboard.TargetName="ExpanderAnetArticle" FillBehavior="HoldEnd">
                <DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
            </BooleanAnimationUsingKeyFrames>

        </Storyboard>

   </Window.Resources>

    <Window.Triggers>

<EventTrigger RoutedEvent="UIElement.MouseLeftButtonUp" SourceName="CtrlTiOperation">
            <BeginStoryboard x:Name="Operation_BeginStoryboard" Storyboard="{StaticResource Operation}"/>
            <BeginStoryboard x:Name="Tabfocus_BeginStoryboard" Storyboard="{StaticResource Tabfocus}"/>
        </EventTrigger>

A: Your FillBehavior="HoldEnd" means that you cannot change the property from code because is retained by StoryBoard.
In a previous answer to your similar question i suggested you to provide Stop value for FillBehavior, but this is wrong because with Stop the value will be reverted at the end of the Animation.
You can put a completed event in you animation and so something like this:
private void animation_Completed(object sender, EventArgs e)
{
  bool isexpanded = Exp1.IsExpanded;
  Exp1.BeginAnimation(Expander.IsExpandedProperty, null);
  Exp1.IsExpanded = isexpanded;
}

where Exp1 is your Expander.
You take fhe value, stop the animation and then put the value back.
IT works well.
It's not the only method , but i'm doing some test for myself knowledge.


text:
Q: Reset UIKeyboard State I have a UITextView which the keyboard enters values into. However, if you clear the text value (i.e uitextview.text = @""), the keyboard's state does not reset to the lowercase alphabet keyboard.
That is, if I was in the middle of typing "hello.." and the textview gets cleared, the keyboard still shows the symbols, rather than back to the alphabetical letters.
Is there a way to get around this?

A: It turns out
[textview resignFirstResponder]

immediately followed by
[textview becomeFirstResponder]

does the trick. It does seem a little "hacky" though, but with Apple not providing any direct access to the keyboard, it seems that this is the only way.


text:
Q: Basic easy rules for statistics In a binomial experiment, if we observe $x=0$ positive individual among $n$ individuals, then the proportion of positive individuals is significantly lower than $3/n$ with a type 1 error less than and very close to $5\%$. This fact, sometimes called the "rule of three", is a consequence of the inequalities $$\exp\left(-\frac{np}{1-p}\right) \leq \Pr(X=0) \leq \exp(-np).$$
Do you know other such basic easy rules for statistics? I find them very interesting and useful. This principle is not really a "rule of thumb" because it has a reliable theoretical foundation, but I don't see another tag for this question (I hope it is not off-topic)

A: Check out Gerald van Belle's book "Statistical Rules of Thumb" a very nice little paperback text loaded with examples of rules of thumb and explanations including the "Rule of three" that you mention above.


text:
Q: Add Range header support IIS 10 I have built a web server for loading video (.mp4) in IIS.
Other devices/browsers include mobile work fine except for iOS(safari, chrome on safari...). I searched everywhere I can and know that iOS(safari, chrome on safari...) need range header to play video (.mp4) file.
How can I add range header in IIS to make iOS(safari, chrome on safari...)  can play video (.mp4) file?
Thanks

A: Video not work in safari has nothing to do with iis, this is caused by byte-range requests.
Byte-range requests are when a client asks a server for only a specific portion of the requested file. The primary purpose of this is to conserve bandwidth usage by only downloading small sections of the file as needed (a video in your case). If you inspect the Safari video request, you may notice a Range header set to bytes=0-1. This is Safari's way of testing if your HTTP servers accept byte ranges before requesting a larger chunk of data.
To fix your server config, take a look at Apple's recommendations.


text:
Q: How to use Python to retrieve xml page that requires http login? When I access a page on an IIS server to retrieve xml, using a query parameter through the browser (using the http in the below example) I get a pop-up login dialog for username and password (appears to be a system standard dialog/form). and once submitted the data arrives. as an xml page.
How do I handle this with urllib? when I do the following, I never get prompted for a uid/psw.. I just get a traceback indicating the server (correctly ) id's me as not authorized. Using python 2.7 in Ipython notebook
f = urllib.urlopen("http://www.nalmls.com/SERetsHuntsville/Search.aspx?SearchType=Property&Class=RES&StandardNames=0&Format=COMPACT&Query=(DATE_MODIFIED=2012-09-28T00:00:00%2B)&Limit=10")
s = f.read()
f.close()

Pointers to doc also appreciated! did not find this exact use case.
I plan to parse the xml to csv if that makes a difference.

A: You are dealing with http authentication. I've always found it tricky to get working quickly with the urllib library. The requests python package makes it super simple.
url = "http://www.nalmls.com/SERetsHuntsville/Search.aspx?SearchType=Property&Class=RES&StandardNames=0&Format=COMPACT&Query=(DATE_MODIFIED=2012-09-28T00:00:00%2B)&Limit=10"
r = requests.get(url, auth=('user', 'pass'))
page = r.text

If you look at the headers for that url you can see that it is using digest authentication:

{'content-length': '1893', 'x-powered-by': 'ASP.NET',
  'x-aspnet-version': '4.0.30319', 'server': 'Microsoft-IIS/7.5',
  'cache-control': 'private', 'date': 'Fri, 05 Oct 2012 18:20:54 GMT',
  'content-type': 'text/html; charset=utf-8', 'www-authenticate':
  'Digest realm="Solid Earth", nonce="MTAvNS8yMDEyIDE6MjE6MjUgUE0",
  opaque="0000000000000000", stale=false, algorithm=MD5, qop="auth"'}

So you will need:
from requests.auth import HTTPDigestAuth
r = requests.get(url, auth=HTTPDigestAuth('user', 'pass'))

A: There are many ways to do it but i suggest you start with urllib2 and it's batteries included.
import urllib2, base64

req = urllib2.Request("http://webpage.com//user")
b64str = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % b64str)
result = urllib2.urlopen(req)

You can use requests, beautifulsoup,mechanize or selenium if your task gets harder. Googling will give you enough examples for each one of these,

A: This can be done in a couple of ways:

*

*Use urllib/urllib2 and requests as others have suggested

*Use Mechanize to simulate manual form-filling and get back the response


text:
Q: Steam error when adding friends I've got few problems in Steam, where I can't add friends. I'm trying to add my first Steam friend but it comes up with one of these messages:
"Could not invite %s. Their friends list is full."

Does anyone know what the problem is, and how to fix it?

A: Friendslist of people are limited and only goes up by leveling up. That person has it filled, so you can't add him/her unless s/he levels up or unfriends someone.


text:
Q: Authorization error while using JWT in gRPC ASP.NET I used gRPC to try to make JWT authorization, but when I try to authorization, I get an error on the client:
Grpc.Core.RpcException: "Status(StatusCode="Unimplemented", Detail="Bad gRPC response. HTTP status code: 404")"

I can't figure out what this is about.
My gRPC Server:
Startup.cs:
using AspNetCore.Identity.Mongo;
using GrpcServiceTiEventsy.MongoDB.Identity;
using GrpcServiceTiEventsy.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using MongoDB.Driver;
using System.Security.Claims;
using System.Text;

namespace GrpcServiceTiEventsy
{
    public class Startup
    {

        private readonly SymmetricSecurityKey _securityKey;
        public static MongoClient MongoDbClient { get; private set; }
        public static IConfiguration Configuration { get; private set; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            _securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Token:SecretKey"]));
            MongoDbClient = new MongoClient(Configuration.GetConnectionString("MongoDB"));
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();

            services.AddSingleton<IMongoClient, MongoClient>(sp => MongoDbClient);

            services.AddIdentityMongoDbProvider<DatabaseAccount, DatabaseRole>(identity =>
                {
                    identity.Password.RequiredLength = 8;
                    identity.Password.RequireNonAlphanumeric = false;
                    identity.Password.RequireLowercase = false;
                    identity.Password.RequireUppercase = false;
                    identity.Password.RequireDigit = false;
                },
                mongo =>
                    mongo.ConnectionString = Configuration.GetConnectionString("MongoDB") + "/TiEventsyIdentity"
                );

            services.AddAuthorization(options =>
            {
                options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
                {
                    policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                    policy.RequireClaim(ClaimTypes.Name);
                });
            });

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(
                opt =>
                {
                    opt.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateActor = false,

                        ValidateIssuer = true,
                        ValidIssuer = Configuration["Token:Issuer"],

                        ValidateAudience = true,
                        ValidAudience = Configuration["Token:Audience"],

                        ValidateLifetime = true,

                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = _securityKey
                    };
                });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();
                endpoints.MapGrpcService<LoginService>();
                endpoints.MapGrpcService<RefreshedTokenService>();
                endpoints.MapGrpcService<RegistrationService>();
            });
        }
    }

}

TokensGenerator.cs:
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Grpc.Core;
using GrpcServiceTiEventsy.MongoDB.Identity;
using Microsoft.IdentityModel.Tokens;
using MongoDB.Driver;

namespace GrpcServiceTiEventsy.Models.Tokens
{
    public static class TokensGenerator
    {

        private static readonly SymmetricSecurityKey SecurityKey
            = new (Encoding.ASCII.GetBytes(Startup.Configuration["Token:SecretKey"]));

        public static async Task<(string, string)> CreateTokens(DatabaseAccount account) =>
            (CreateJwt(account), await CreateRefreshToken(account));

        public static async Task<(string, string)>  CreateTokens(DatabaseAccount account, string jwtToken, string refreshToken)
        {
            if (ValidateJwtToken(jwtToken) && ValidateRefreshToken(account, refreshToken))
                return (CreateJwt(account), await CreateRefreshToken(account));

            throw new RpcException(Status.DefaultSuccess,"Tokens are not real");
        }

        private static bool ValidateRefreshToken(DatabaseAccount account, string token)
            => account.RefreshToken == token;

        private static bool ValidateJwtToken(string token)
        {
            var tokenHandler = new JwtSecurityTokenHandler();

            try
            {
                tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateActor = false,

                    ValidateIssuer = true,
                    ValidIssuer = Startup.Configuration["Token:Issuer"],

                    ValidateAudience = true,
                    ValidAudience = Startup.Configuration["Token:Audience"],

                    ValidateLifetime = false,

                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = SecurityKey

                }, out var validatedToken);

                return true;
            }
            catch
            {
                return false;
            }

        }

        private static string CreateJwt(DatabaseAccount account)
        {
            var claims = new[] { new Claim(ClaimTypes.Name, account.UserName) };

            var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);

            var expiresDays = Convert.ToInt32(Startup.Configuration["Token:LifetimeDay"]);

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = new JwtSecurityToken(
                Startup.Configuration["Token:Issuer"],
                Startup.Configuration["Token:Audience"],
                claims,
                expires: DateTime.Now.AddDays(expiresDays),
                signingCredentials: credentials);

            return tokenHandler.WriteToken(token);
        }

        private static async Task<string> CreateRefreshToken(DatabaseAccount account)
        {
            var randomNumber = new byte[32];

            using (var rng = RandomNumberGenerator.Create())
                rng.GetBytes(randomNumber);
            var token = Convert.ToBase64String(randomNumber);

            var identityDb = Startup.MongoDbClient.GetDatabase("TiEventsyIdentity");
            var accountsCollection = identityDb.GetCollection<DatabaseAccount>("Users");

            var user = await accountsCollection.Find(ac => ac.Id == account.Id).FirstOrDefaultAsync();

            if (user != null)
            {
                var filter = Builders<DatabaseAccount>.Filter.Eq(s => s.Id, account.Id);
                var update = Builders<DatabaseAccount>.Update.Set(s => s.RefreshToken, token);

                await accountsCollection.UpdateOneAsync(filter, update);
            }
            else throw new RpcException(Status.DefaultSuccess,"No such user exists");

            return token;
        }
    }
}

GreeterService.cs:
using System.Threading.Tasks;
using Grpc.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;

namespace GrpcServiceTiEventsy.Services
{
    public class GreeterService : Greeter.GreeterBase
    {
        private readonly ILogger<GreeterService> _logger;
        public GreeterService(ILogger<GreeterService> logger)
        {
            _logger = logger;
        }

        [Authorize]
        public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
        {
            return Task.FromResult(new HelloReply
            {
                Message = "Hello " + request.Name
            });
        }
    }
}

My Client:
Program.cs:
using System;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Net.Client;
using GrpcServiceTiEventsy;

Console.WriteLine("Param...");

var channel = GrpcChannel.ForAddress("https://localhost:5001");

Console.WriteLine("Log...");

var l = new Login.LoginClient(channel);
var tokens = await l.LogAsync(new LoginRequest { Email = "igorka@gmail.com", Password = "pas@jKH$KJJT34592345" });
Console.WriteLine($"\n Access: {tokens.AccessToken}" +
                  $"\n Refresh: {tokens.RefreshToken}" +
                   "\n");

var credentials = CallCredentials.FromInterceptor((context, metadata) =>
{
    metadata.Add("Authorization", $"Bearer {tokens.AccessToken}");
    return Task.CompletedTask;
});

channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
{
    Credentials = ChannelCredentials.Create(new SslCredentials(), credentials)
});

Console.WriteLine("Test Auth...");
var te = new Greeter.GreeterClient(channel);
var outD = await te.SayHelloAsync(new HelloRequest { Name = "igorka@gmail.com" });
Console.WriteLine("Out: " +outD);

Error inferred here var outD = await te.SayHelloAsync(new HelloRequest { Name = "igorka@gmail.com" });
If you wait for additional information, you will denigrate it in comments.

A: After a long debug and reading articles, I made the right Startup.cs.
Here is the working Startup.cs:
using AspNetCore.Identity.Mongo;
using GrpcServiceTiEventsy.MongoDB.Identity;
using GrpcServiceTiEventsy.Services;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using MongoDB.Driver;
using System.Text;
using Microsoft.AspNetCore.Identity;

namespace GrpcServiceTiEventsy
{
    public class Startup
    {

        private readonly SymmetricSecurityKey _securityKey;
        public static MongoClient MongoDbClient { get; private set; }
        public static IConfiguration Configuration { get; private set; }

        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
            _securityKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Token:SecretKey"]));
            MongoDbClient = new MongoClient(Configuration.GetConnectionString("MongoDB"));
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddGrpc();

            services.AddSingleton<IMongoClient, MongoClient>(sp => MongoDbClient);

            services.AddIdentityMongoDbProvider<DatabaseAccount, DatabaseRole>(identity =>
                {
                    identity.Password.RequiredLength = 8;
                    identity.Password.RequireNonAlphanumeric = false;
                    identity.Password.RequireLowercase = false;
                    identity.Password.RequireUppercase = false;
                    identity.Password.RequireDigit = false;
                },
                mongo =>
                    mongo.ConnectionString = Configuration.GetConnectionString("MongoDB") + "/TiEventsyIdentity"
                ).AddDefaultTokenProviders();

            services
                .AddAuthorization()
                .AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(
                opt =>
                {
                    opt.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateActor = false,

                        ValidateIssuer = true,
                        ValidIssuer = Configuration["Token:Issuer"],

                        ValidateAudience = true,
                        ValidAudience = Configuration["Token:Audience"],

                        ValidateLifetime = true,

                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey = _securityKey
                    };
                });
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>();
                endpoints.MapGrpcService<LoginService>();
                endpoints.MapGrpcService<RefreshedTokenService>();
                endpoints.MapGrpcService<RegistrationService>();
            });
        }
    }
}


text:
Q: What is the .app folder? How can it be turned into a .dmg archive? I am using electron-packager on Mac OS X Sierra. I can easily package my entire application, which creates a release folder. Within it, there is a folder called <AppName>.app, which I can open.
I wanted to make a .dmg to easily distribute it. However, this folder behaves in pretty mysterious ways. I went to Disk Utility, and selected new image from folder. When I go to select my .app folder, it somehow appears as a full application already. It doesn't appear as a folder.
I tried taring the folder.
tar -cvzf app.tar.gz MyApp.app

However, when I extract it in finder, it also turns out to be a whole, working application.
What is this strange behavior of the .app folder and how can it be distributed as an installable .dmg?

A: Application on macOS are typically stored in an "application bundle" (completely unrelated to Webpack/Browserify, by the way).
In Finder, and also in file dialogs, these appear to be single items. As you call it, a "full application". Under the hood, however, these items are really directories/folders. If you look at it from a lowerlevel point of view, say from Terminal, you'll see a directory called MyApp.app.
If you want to create a DMG from it, use the release folder that contains the application bundle. If there are other files there that you don't want to add to the DMG, either remove them, or create a new empty directory, move the app there, and use that as the folder to create the DMG from.


text:
Q: django signals. how to create a unique dispatch id? sometimes signals in django are triggered twice. In the docs it says that a good way to create a (unique) dispatch_uid is either the path or name of the module[1] or the id of any hashable object[2].
Today I tried this:
import time
my_signal.connect(my_function, dispatch_uid=str(time.time()))

However I am afraid that in a multiuser environment (like in the case of a web site). This might be broken. What is a good and safe way to create such an id in a multiuser environment?
[1] https://code.djangoproject.com/wiki/Signals
[2] https://docs.djangoproject.com/en/dev/topics/signals/#preventing-duplicate-signals

A: Just use string to the module, like 'apps.models.signal_name'

A: Using the time as a dispatch id won't work. The issue isn't whether your environment is multi-user or not. It's whether the code that connects the signals is imported more than once.
Say your module was imported twice, 5 seconds apart. You have effectively done the following.
my_signal.connect(my_function, dispatch_uid=1332407342.51)
my_signal.connect(my_function, dispatch_uid=1332407352.51)

Your signal has been connected twice with different dispatch ids. This default project structure for Django 1.3 and earlier allows this double import to occur, as modules can often be imported as project.my_app.module and my_app.module.
If you choose a convention like my_app.models.function_name as Dmitry suggests, then the second time the module is imported, the signal will not be connected twice because the dispatch id has not changed. It's up to you not to reuse the same dispatch id to register different callback functions with the same signal.


text:
Q: Комментирование куска текста в vim Есть любой кусок текста, хотелось бы его полностью закомментировать за пару действий вне зависимости от его размера.

A: Плагином пользоваться не хотелось бы по той простой причине - что нужна универсальность) Частенько приходится работать с разных машин, в том числе и чужих - поэтому только чистый vim)
Для себя нарыл сейчас такой вариант:
ctr+v дальше } - до конца абзаца либо j,k выделение. Дальше I , # и <ESC>

A: Я для этого пользуюсь плагином tComment. С ним можно выделить текст, нажать комбинацию клавиш  (горячие клавиши настраиваются), и нужные строки будут закомментарены. Раскомментаривание происходит так же. Плюс есть ещ несколько полезных горячих клавиш.

A: Можно использовать The NERD Commenter или аналоги. Комментирование в нажатие двух-трех кнопок. Предварительно они требуют выделить текст, а это уже отдельное действие и в некоторых случаях может быть выполненно и за одно-два нажатия.

A: Этот ответ годится только для однострочных комментариев, но тем не менее.
Для комментирования C++-кода можно так сделать:
^Ctrl+v5jI//
где ^ - Shift+6, 5 - количество строк вниз, I - Shift+i.
Возможны любые перемещения вместо 5j, например, }.
Для другого языка можно заменить // на соответствующий символ комментария (#, -- и т.п.)
Upd: Спасибо @Dofri и @KoVadim за замечания. Dofri более прав оказался относительно Ctrl+v.

A: Для комментирования блока я всегда использовал режим визуального выделения, который вызывается по

ctrl+v

(в gvim для windows по умолчанию ctrl+q).
Нужно поставить курсор, например, в начале строки наверху выделяемого блока, нажать

ctrl+v

, переместить курсор в конец параграфа, нажав

}

, затем нажать

I (shift+i)

, ввести символ комментария (например, #) и нажать ESC.
детальнее:
https://lisakov.com/blog/vim-comment-block/

A: У меня было желание не просто быстро комментировать/раскомментировать кусок текста, но чтобы еще и символ комментария автоматически выбирался верный.
И из любопытства я написал плагин, которым вот уж пару лет как пользуюсь и сильно привык, надо сказать )
Работает оно так: выделяю кусок текста и нажимаю hh. Если выделить закомментированный кусок и нажать hh, то кусок раскомментируется.
.vimrc:
nmap hh :LinesCommentNextState <CR>
vmap hh :LinesCommentNextState <CR>

код плагина:
function! s:LinesCommentNextState() range

    let l:extension = expand('%:e')

    let l:comment_symbol = "#"
    if l:extension == "c"
        let l:comment_symbol = "\/\/"
    elseif l:extension == "cpp"
        let l:comment_symbol = "\/\/"
    elseif l:extension == "h"
        let l:comment_symbol = "\/\/"
    elseif l:extension == "hpp"
        let l:comment_symbol = "\/\/"
    elseif l:extension == "xs"
        let l:comment_symbol = "\/\/"
    elseif l:extension == "vim"
        let l:comment_symbol = "\""
    elseif l:extension == "lua"
        let l:comment_symbol = "--"
    else
        "default '#'
    endif

    let l:first_line = getline(a:firstline)

    let l:need_comment = 1

    " if string already commented, no need comment twice
    if l:first_line =~ '\v^(\s)*' . l:comment_symbol
        let l:need_comment = 0
    endif

    for n in range (a:firstline, a:lastline)
        let l:line = getline (n)

        if len(l:line) == 0
            continue
        endif

        if l:need_comment == 1
            " comment it!
            let l:new_line = l:comment_symbol . l:line

            " but if beginning from space, need save all spaces
            if l:line =~ '\v^\s'
                let l:matches = matchlist(l:line, '\v^(\s+)(.*)')
                let l:new_line = l:matches[1] . l:comment_symbol . l:matches[2]
            endif
        else
            let l:new_line = l:line

            if l:line =~ '\v^(\s*)' . l:comment_symbol
                let l:matches = matchlist(l:line, '\v^(\s*)' . l:comment_symbol . '(.*)')
                let l:new_line = l:matches[1] . l:matches[2]
            endif
        endif

        call setline (n, l:new_line)
    endfor
endfunction

function! SaveCursor()
    let s:cursor = getpos('.')
endfunction

function! RestoreCursor()
    call setpos('.', s:cursor)
    unlet s:cursor
endfunction

command! -range LinesCommentNextState call SaveCursor() | <line1>,<line2>call s:LinesCommentNextState() | call RestoreCursor()


text:
Q: How do you populate complex data models when using Linq Query Syntax? I have a pretty basic query which I've written in method syntax, but I need to convert it to query syntax in order to do some sorting/filtering in an effort to avoid the error from this unresolved question. Here's what I have in method syntax:
    var Projects = _context.Projects
        .Include(p => p.Bids).ThenInclude(b => b.Vendor)
        .Include(p => p.Category)
        .Include(p => p.Location);

This populates a list of Projects for me with all of the information available from the database, and it also populates the linked objects for the Project as well. Here's the class for reference:
public class Project : BaseModel
{
    public int ProjectId { get; set; }
    public string ProjectName { get; set; }
    public int? LocationId { get; set; }
    public int? CategoryId { get; set; }

    public Location Location { get; set; }
    public Category Category { get; set; }
    public IList<Bid> Bids { get; set; }
}

public class Bid : BaseModel
{
    public int BidId { get; set; }
    public string BidName { get; set; }
    public int ProjectId { get; set; }
    public int? VendorId { get; set; }

    public Vendor Vendor { get; set; }
}

In trying to convert this query into 'query syntax' I haven't been able to get it to automatically populate the Location, Category and IList<Bids> properties.
    var Projects =
        from prj in _context.Projects
        join bid in _context.Bids on prj.ProjectId equals bid.ProjectId
        join vnd in _context.Vendors on bid.VendorId equals vnd.VendorId
        join cat in _context.Categories on prj.CategoryId equals cat.CategoryId
        join loc in _context.Vendors on loc.LocationId equals prj.LocationId
        select prj;

Using this syntax it will auto-popualte all the base values of the Project class but does not populate any of the linked classes. Is there a way to get these to populate automatically? I played around with a "select New Project{}" statement but that just allows me to set properties of the project directly and I still can't link other objects

A: I am assuming you are using Entity Framework, and a reminder that you should try to tag as specifically as possible.
If Project has many Bids, you want to have a reference that entity framework can use to identify the link between the two entities. For example:
public class Project : BaseModel
{
    public int ProjectId { get; set; }
    public string ProjectName { get; set; }

    public IList<Bid> Bids { get; set; }
}

public class Bid : BaseModel
{
    public int BidId { get; set; }
    public string BidName { get; set; }

    public int ProjectId { get; set; }
    public Project Project { get; set; }
}

The public Project Project { get; set; } is what you are missing that EF will use to associate the foreign key.
Other ways are via fluent api or data annotations.
https://learn.microsoft.com/en-us/ef/core/modeling/relationships?tabs=fluent-api%2Cfluent-api-simple-key%2Csimple-key

A: From this article, to load the Related Data, we could use the Include method.
Try to change your code as below:
var Projects =
    from prj in _context.Projects.Include(p => p.Bids).ThenInclude(b => b.Vendor).Include(p => p.Category).Include(p => p.Location)
    join bid in _context.Bids on prj.ProjectId equals bid.ProjectId
    join vnd in _context.Vendors on bid.VendorId equals vnd.VendorId
    join cat in _context.Categories on prj.CategoryId equals cat.CategoryId
    join loc in _context.Vendors on loc.LocationId equals prj.LocationId
    select prj;

Or
var Projects =
    (from prj in _context.Projects
    join bid in _context.Bids on prj.ProjectId equals bid.ProjectId
    join vnd in _context.Vendors on bid.VendorId equals vnd.VendorId
    join cat in _context.Categories on prj.CategoryId equals cat.CategoryId
    join loc in _context.Vendors on loc.LocationId equals prj.LocationId
    select prj).Include(p => p.Bids).ThenInclude(b => b.Vendor).Include(p => p.Category).Include(p => p.Location)**strong text**;


text:
Q: Method to check if a test ID has already been used in a test flow? When looking at the test program flow creation guide, I wondered if there was a method to determine if a test ID has already been used.  I am using many enumerators in my flows and get this error when there are duplicate IDs:
[ERROR]      71.979[0.000]   || Test ID scan_delay_testmode1_nclk_1cyc_pmax is defined more than once in flow scan_flow:

Would be nice to be able to trap for this with a method.
thx

A: It's a bit of a mouthful, but you can get the IDs used so far via:
ATP::AST::Extractor.new.process(flow.atp.raw, [:id]).map { |node| node.to_a[0] }

A PR would be accepted to expose something more elegant like:
flow.atp.ids  # => [:id1, :id2]

The ids method would simply contain the above and could be added to here: https://github.com/Origen-SDK/atp/blob/master/lib/atp/flow.rb

Update:
As of this PR, https://github.com/Origen-SDK/atp/pull/9, you can now call:
flow.ids      # => [:id1 ,:id2]


text:
Q: Pointer to two different structures I have three structures header, dataA, and dataB. The header will determine the structure that will be used. The dataA and dataB have almost the same structure (let's say):
struct dataA
{
    int   intValue;
    char  reserved1[8];
    float floatValue;
    char  reserved2[4];
    short shortValue;
};

struct dataA
{
    int   intValue;
    short shortValue;
    char  reserved[2];
    float floatValue;
};

I want to print it like:
sprintf(outStr, "%i, %f, %s", p->intValue, p->floatValue, p->shortValue);

-- OR --
sprintf(outStr, "%i, %f, %s", p.intValue, p.floatValue, p.shortValue);

How do I declare p? (NOTE: Both dataA and dataB have a large structure but almost the same data, except for those that are reserved values.)
I am thinking something like this:
void * p;

if (header->type==1)
   p = (dataA*)(pData);
else if (header->type==2)
   p = (dataB*)(pData);

// print all data here

NOTE: The pData here is a pointer to a (raw) data that I will be read. I only need those non-reserved values and disregard the reserved values.

A: Move the printing logic into a function template:
template <typename T>
int print_data(char* const str, std::size_t const len, T const* const p)
{
    return std::snprintf(
        str, len,
        "%i, %f, %s",
        p->intValue, p->floatValue, p->shortValue);
}

Then call this function from your switching logic:
if (header->type==1)
    print_data(str, len, static_cast<dataA const*>(pData));
else if (header->type==2)
    print_data(str, len, static_cast<dataB const*>(pData));

If you plan on using std::snprintf, it would be a good idea to add static_asserts to the print_data function template to ensure that the types of the data members of T are the types that you expect, just to be sure.
Note that if your platform has strict alignment requirements and the data pointed to by pData is not guaranteed to be correctly aligned for all of your target types, you will need to replace the cast with a copy of bytes into a suitably aligned buffer.


text:
Q: Is there any python function to check for nan values in list comprehension without changing it I am writing code to take values from everyone column of data frame and do some processing on it. I got exception whenever there is a NaN value. I do not want to drop columns with Nan.
Previously I solved the problem by simply catching exception but now I am unable to do same as I am using list comprehensions here.
Can someone suggest a proper way of doing this ?
Previously I solved it like this:
for index, row in df_work.iterrows():
        descrip = row['description']
        try:
            r = Rake()
            r.extract_keywords_from_text(descrip)
            key_words_dict_scores = r.get_word_degrees()
            row['Key_words'] = list(key_words_dict_scores.keys())
        except Exception as e:
            print(e)
            row['Key_words'] = ''

I want to do same here:
df_work['specialties'] = [','.join(x) for x in df_work['specialties'].map(lambda x: x.lower().replace(' ','').split(',')).values]
    df_work['industry'] = [','.join(x) for x in df_work['industry'].map(lambda x: x.lower().replace(' ','').split(',')).values]
    df_work['type'] = [','.join(x) for x in df_work['type'].map(lambda x: x.lower().replace(' ','').split(',')).values]

I get this error in above code:
'float' object has no attribute 'lower'

Specialties column contains data like this:
df_work.loc['TOTAL', 'specialties']

OUTPUT >> 'Oil & Gas - Exploration & Production,Upstream,Refining,Trading,Shipping,Marketing,Energy,Crude Oil,Petroleum,Petrochemicals,Liquified Natural Gas,Renewable Energy,Drilling Engineering,Completion & Intervention Engineering,Geology,Geoscientists,IT'
type(df_work.loc['TOTAL', 'specialties'])

OUTPUT>> str
Expected output after running my above code should be:
OUTPUT>> 'oil&gas-exploration&production,upstream,refining,trading,shipping,marketing,energy,crudeoil,petroleum,petrochemicals,liquifiednaturalgas,renewableenergy,drillingengineering,completion&interventionengineering,geology,geoscientists,it'
type(df_work.loc['TOTAL', 'specialties'])

OUTPUT>> str

A: Here is possible use pandas functions working with NaNs nice:
df_work['specialties'] = df_work['specialties'].str.lower().str.replace(' ','')

If need working with NaNs test it by isinstance() and if-else statement:
df_work['specialties'] = (df_work['specialties']
        .map(lambda x: x.lower().replace(' ','') if isinstance(x, str) else x))

And list comprehension solution:
df_work['specialties'] = [x.lower().replace(' ','')
                          if isinstance(x, str)
                          else x
                          for x in df_work['specialties']]

Sample:
df_work = pd.DataFrame({'specialties':['First spec, Sec spec','A Vb,ds RT', np.nan]})
print (df_work)
            specialties
0  First spec, Sec spec
1            A Vb,ds RT
2                   NaN

df_work['specialties'] = [x.lower().replace(' ','')
                          if isinstance(x, str)
                          else x
                          for x in df_work['specialties']]
print (df_work)
         specialties
0  firstspec,secspec
1           avb,dsrt
2                NaN


text:
Q: How can calling a function with an alias name or attribute name? I have a method like this.
        [CodeName("Bar")]
        public bool IsWidow(Guid applicantId)

And I want to call this method with a code that I have as an attribute above this function.
something like this
bar();
How it is possible to call the IsWidow() method when I call bar() method?

A: Using my powers of deduction I think you might want to call the method based on the CodeName attribute.  In which case you can use reflection to get the attributes.
The method below allows you to call a method that has an attribute that matches the CodeName that you want.  pars is an optional list of parameters that need to be passed to the method, this is a flaw in the plan really because you will need to know the signature of the method to know what parameters to pass in.
 object? CallMethod(object target, string codeName, params object[] pars)
    {
        foreach (var m in target.GetType().GetMethods())
        {
            var att = m.GetCustomAttributes().OfType<CodeNameAttribute>().FirstOrDefault();

            if (att != null)
            {
                if (att.Name == codeName)
                {
                    return m.Invoke(target, pars);
                }
            }
        }

    }

i'm not absolutely sure what you are trying to achieve, so its hard to know whether the above function is really of any use

A: Here a working Example:
Here the example class
public class myClass
{
    [myAtt("Bar")]
    public void Mehtod1(string someText, int ID)
    {
        //Inside method one
    }

    [myAtt("someOtherText")]
    public void Mehtod2()
    {
        //Inside method 2
    }

    public class myAtt : Attribute
    {
        public string Name { get; set; }
        public myAtt(string name)
        {
            Name = name;
        }
    }
}

And here the working example: (Look at example 1. Example one is exactly what you are looking for)

public void DoWork()
    {
        myClass myClassObj = new myClass(); //Create an object of your class

        /*      Main Example    */
        //This is what you are looking for

        var allMethods2 = myClassObj.GetType().GetMethods(); //Get all methods in the class
        foreach (var method in allMethods2) //loop
        {
            var attributes = method.GetCustomAttributes(false); //custom attributes
            if (attributes.Length > 0)
            {
                var attribute =
                    attributes.FirstOrDefault(att => att is myClass.myAtt); //Get the attribute you are looking for
                if (attribute != null && ((myClass.myAtt)attribute).Name == "Bar") //check null & check if the 'inside' of the attribute is correct
                {
                    var parameters = method.GetParameters();
                    var objToPass = new List<object>();
                    foreach (var parameterInfo in parameters) //Loop through method params
                    {
                        var toAdd = new object(); //Object to pass after the loop
                        if (parameterInfo.ParameterType == typeof(string))
                        {
                            //Param is string
                            switch (parameterInfo.Name)
                            {
                                case "someText":
                                    toAdd = "Some text to add";
                                    break;
                                default:
                                    //Log?
                                    toAdd = "Don't know the attribute...";
                                    break;
                            }
                        }
                        else if (parameterInfo.ParameterType == typeof(int))
                        {
                            //Param is int
                            switch (parameterInfo.Name)
                            {
                                case "ID": //Param is an ID
                                    toAdd = 1; //Some ID
                                    break;
                                case "numberFromOneToTen": //Param is a number from 1 - 10
                                    var random = new Random();
                                    toAdd = random.Next(1, 10);
                                    break;
                                default:
                                    //Log?
                                    toAdd = -9999; //e.g an error code
                                    break;
                            }
                        }
                        objToPass.Add(toAdd); //Add object to pass to the list

                    }

                    method.Invoke(myClassObj, objToPass.ToArray()); //Invoke the method

                }
            }
        }

        /*  Second Example  */

        //In this case below you are not looking for the inside of the attribute
        var allMehtods = myClassObj.GetType().GetMethods()
            .Where(m => m.GetCustomAttributes(typeof(myClass.myAtt), false).Length > 0)
            .ToArray(); //Get all methods with the type of attribute you are looking for

        foreach (var method in allMehtods)
        {
            method.Invoke(myClassObj, null); //Invoke method

        }

    }


text:
Q: Unable to retrieve dotenv JWT secret " Error: secretOrPrivateKey must have a value" I am trying to secure my app by hiding the secret JWT key into a dotenv file stored locally at the root of the app, but the documentation isn't clear enough to me, and I keep getting this error when running the tests :
 console.error
    Error: secretOrPrivateKey must have a value
        at Object.module.exports [as sign] (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/node_modules/jsonwebtoken/sign.js:107:20)
        at JwtService.sign (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/node_modules/@nestjs/jwt/dist/jwt.service.js:27:20)
        at AuthService.generateToken (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/src/auth/auth.service.ts:62:37)
        at AuthService.verifySmsCode (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/src/auth/auth.service.ts:49:19)
        at processTicksAndRejections (internal/process/task_queues.js:97:5)
        at Object.<anonymous> (/Users/amehmeto/HeroesJobs/BFF/bff-candidates/src/auth/auth.service.spec.ts:83:30)

      49 |       return this.generateToken(candidateId)
      50 |     } catch (e) {
    > 51 |       console.error(e)
         |               ^
      52 |       throw new HttpException(
      53 |         ResponseMessage.INVALID_CODE,
      54 |         HttpStatus.FORBIDDEN

      at AuthService.verifySmsCode (auth/auth.service.ts:51:15)
      at Object.<anonymous> (auth/auth.service.spec.ts:83:30)

Here is the .env :
JWT_SECRET=secretKey

Here is the src/app.module.ts :
import { Module } from '@nestjs/common'
import { StatusModule } from './status/status.module'
import { CitiesModule } from './cities/cities.module'
import { PopupModule } from './popup/popup.module'
import { CandidateModule } from './candidate/candidate.module'
import { NotificationModule } from './notification/notification.module'
import { ChatModule } from './chat/chat.module'
import { AuthModule } from './auth/auth.module'
import { SkillInviteModule } from './skill-invite/skill-invite.module'
import { ConfigModule } from '@nestjs/config'

@Module({
  imports: [
    ConfigModule.forRoot({
      isGlobal: true,
    }),
    StatusModule,
    CitiesModule,
    PopupModule,
    CandidateModule,
    NotificationModule,
    ChatModule,
    AuthModule,
    SkillInviteModule,
  ],
})
export class AppModule {}

The test file :
describe('AuthService', () => {
  let service: AuthService
  let authRepository: AuthRepository
  let authGateway: AuthGateway
  let jwtService: JwtService

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        JwtModule.register({
          secret: process.env.JWT_SECRET,
        }),
      ],
      providers: [AuthService, AuthRepository, AuthGateway],
    }).compile()

    service = module.get<AuthService>(AuthService)
    authRepository = module.get<AuthRepository>(AuthRepository)
    authGateway = module.get<AuthGateway>(AuthGateway)
    jwtService = module.get<JwtService>(JwtService)
  })

  it('should be defined', () => {
    expect(service).toBeDefined()
  })

[...]

    it('should generate a token that expires within one hour when code is valid', async () => {
      const payload = { candidateId: '1' }

      const verifyResponse = await service.verifySmsCode(phoneNumber, code)
      expect(verifyResponse).toHaveProperty(
        'access_token',
        jwtService.sign(payload)
      )
      expect(verifyResponse).toHaveProperty('expires_in', 1000 * 60 * 60)
    })

and finally the code under test :

  async verifySmsCode(
    phoneNumber: string,
    code: string
  ): Promise<VerifyResponseObject> {
    try {
      const candidateId = await this.authRepository.verifySmsCode(
        phoneNumber,
        code
      )
      return this.generateToken(candidateId)
    } catch (e) {
      console.error(e)
      throw new HttpException(
        ResponseMessage.INVALID_CODE,
        HttpStatus.FORBIDDEN
      )
    }
  }

A: You must import the dotenv library and configure it before being able to use environment variables defined in .env. Adding require('dotenv').config() to main.ts will solve your problem.

A: I think this can be fixed by importing the ConfigModule to the TestingModule in your unit-test:
 const module: TestingModule = await Test.createTestingModule({
      imports: [ConfigModule.forRoot()],
      providers: [AuthService, AuthRepository, AuthGateway],
    }).compile()


text:
Q: Using getseconds() to control rotation of clock images (not animation) I have graphics of a watch, the hour, minute and second hands.  I want to use real-time clock data to control rotation of the images.
I can get all the code components to work separately and can rotate a single image of the second hand.  But when I add the JS and CSS to display and rotate all the images, it displays correctly, but nothing rotates.


text:
Q: How to diagnose erratic disk behavior? I have a web site with users lighttpd and CGI scripts.
After upgrading to Fedora 11 (ext4) the disc access became erratic.
The timing of python -c 'import cgi' varies between 0.1 to almost 10 seconds:

How can I diagnose the problem? (Tools, methods, best practices ...)
Update Jul 30, 2009:
Found out that several CGI process were hogging the drive. After killing them the graph is stable between 0.02 and 0.03. Still didn't get an answer on how to diagnose such problems.

A: If it is fresh install then tools like makewhatis which are used by apropos, whatis might cause disk to be heavily used. Wait for few days for things to get stabilized (updatedb, prelink, makewhatis, etc.) then may be timings will be consistent.
It would also depend on something else you are doing on server and what the cgi script is actually doing, where it is taking input from, size of input, etc.
Also if disk is very old, use diagnostic tools (like seagate seatools) to look for controller / bad sector problems. The tools will also allow you to optionally repair the sector if drive is actually from seagate.

A: Do you really need/want ext4 on a production server? It's a still a mighty bit to green for my taste for a server.

A: The only way to diagnose a problem like this is with lots and lots of data.  Familiarize yourself with vmstat and iostat.  A tool I recently learned about in this thread is dstat which effectively combines the two.
For problems like the one you're describing, this command would likely be useful:
$ dstat -M app -cdnygl

It will report on CPU, IO (disk and net), interrupts, swap, and load average.  As a nice little bonus, it will include the name of whatever process was "most expensive" a the time the snapshot was taken.  Unfortunately that particular command produces output too wide to paste here, so here's a bit more conservative version:

$ dstat -M app -cdn
--most-expensive-- ----total-cpu-usage---- -dsk/total- -net/total-
     process      |usr sys idl wai hiq siq| read  writ| recv  send
bacula-fd        0|  1   0  98   0   0   0| 426k  108k|   0     0
bash             1|  2   2  96   0   0   0|   0    20k|1460B 1804B
apache2          8|  4   2  94   0   0   0|   0     0 |  76k   15k
                  |  1   3  96   0   0   0|   0     0 |1132B 1034B
apache2          1|  2   2  96   0   0   0|   0  8192B|  11k 3895B
                  |  2   1  96   0   0   0|   0    32k|3322B 1338B
kipmi0           1|  2   2  96   0   0   0|   0     0 |1309B 1146B


text:
Q: How do I find out if my request was made over HTTP or HTTPS in Play 2.0? How do I find out if my request was made over HTTP or HTTPS in Play 2.0?
Is there a way to find out from the request?
def myControllerMethod = Action { request =>
  // this is where I would like to know
}

Play 1.X had a solution, it was request.secure. Please let me know if you know.

A: Play! Framework 2.0 doesn't currently support HTTPS (the master branch does seem to have support, but that will probably be rolled into Play 2.1). A great way to deploy Play! (in general, and also to support HTTPS) is to use a front proxy web server, like nginx or lighttpd.
Here's a guide on setting up a front-end web server. Then, you can just add a special header for HTTPS requests. Additionally, you'll be able to deploy several Play! applications at once, and use the front-end web server to load balance and fail over automatically.


text:
Q: PHP - Convert Tab Delimited TXT file to CSV I'm trying to convert a tab delimited .txt file into a .csv file.
I was able to use fgetcsv() to open the txt file and get the data for each line with the following code:
$handle = fopen("fileurl.com", "r");
$row = 1;
if (($handle = fopen("fileurl.com", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
        $num = count($data);
        echo "
 $num fields in line $row:

\n";
        $row++;

        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "
\n";
        }

        print_r($data);

    }
    fclose($handle);
}

Now i just need to create a csv file from the data array. I've tried using fputcsv(), but haven't had any luck. I've tried something like this, but the csv file it creates isn't correct and only has 1 row:
$fp = fopen('file.csv', 'w');

fputcsv($fp, $data, "\t");

fclose($fp);

An example of how to create a .csv file from the $data array would be great. I've spent a lot of time researching and trying to get this figured out, but haven't been able to get it working.

A: fputcsv() only writes one line at a time. Not the whole file. You you need to loop through $data in order to add all of that data into your CSV file.
$fp = fopen('file.csv', 'w');
foreach ($data as $line) {
    fputcsv($fp, $line);
}
fclose($fp);

A full example using your code:
$handle = fopen("fileurl.com", "r");
$lines = [];
if (($handle = fopen("fileurl.com", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, "\t")) !== FALSE) {
        $lines[] = $data;
    }
    fclose($handle);
}
$fp = fopen('file.csv', 'w');
foreach ($lines as $line) {
    fputcsv($fp, $line);
}
fclose($fp);

A: This is the correct way to write data into csv file
    <?php

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);

$fp = fopen('file.csv', 'w');

foreach ($list as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
?>

In fputcsv we use second parameter as an array .

A: along with it $attachment = mb_convert_encoding($attachment, 'UTF-8', $parts[$i]->parameters[0]->value); also needed for tsv to csv. it will change file type to text/plain


text:
Q: C# .net - Images fits differently on win7 than win8 I recently got myself a new laptop with Win8 OS, and started developing on this instead of my old with Win7.
I noticed recently that images fits differently on Windows 7 than it does on Windows 8 for some reason. You can see it in the picture below:

(The below image got pixely when I made it bigger due to screenshot taken by someone else)
But you can clearly see that the images doesn't fit on Windows 7.
How can I solve this?


text:
Q: How to play audio files in xcode Pretty new to xcode and need some help. I want to play audio files one after each other.
Let's say I have these files with the audio:
audio1 = "Hello", audio2 = "how", audio3 = "are", audio4 = "you"
...and when I press the "Play sound" button it should read out "Hello How are you".
Can anyone help me out with this? I have googled this a lot, but there is no easy example for this matter... for newbies ;)

A: You can use AVQueuePlayer's method
+ (AVQueuePlayer *)queuePlayerWithItems:(NSArray *)items

and you can refer to this question
iOS xcode4 AVQueuePlayer not playing sound


text:
Q: How to align 3 different tables evenly to each other that are styled using Bootstrap? I am trying to align all three tables. You can see the 2nd column in the 2nd table isn't aligned with table 1 and 3. I need to fix this. I am developing in ASP.NET Core 2.0 using CSS and Bootstrap for the front-end.
I've tried to look up help on StackOverFlow already. I used this CSS to try and override the behavior.
.table > tbody > tr > td,
.table > tbody > tr > th, .table > tfoot > tr > td,
.table > tfoot > tr > th, .table > thead > tr > td,
.table > thead > tr > th {
    vertical-align: middle;
}

            Size
            Cost

        @foreach (var item in Model.Sizes)
        {

                @item.Type
                $@item.Cost

        }

            Crust
            Cost

        @foreach (var item in Model.Crusts)
        {

                @item.Type
                $@item.Cost

        }

            Topping
            Cost

        @foreach (var item in Model.Toppings)
        {

                @item.Type
                $@item.Cost

        }

I'll try to add an image to this question shortly.
Picture is here

A: Try to use table-fixed to fix the width of columns: