问:
Retrieving address of "inner" classes of a class
I have a virtual base class called ValuationFunction which basically just contains parameters and can output a value based on some calculation. All of the derived classes behave mostly the same way apart from one, which is called FunctionCombiner and looks like this:

```<code>class FunctionCombiner : public valuationFunction
{
public:
    FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>>& Inner_);
    void ValueInstrument();
    void RiskFactorAdd(double increment, RiskFactor simulatedRiskFactor);
    void RiskFactorMultiply(double factor, RiskFactor simulatedRiskFactor);
    virtual valuationFunction* clone() const;
private:
    std::vector<std::shared_ptr<valuationFunction>> Inner;
};
</code>```

The way it works is that it contains a vector of pointers to other valuation function derived classes and for each of it's functions it's basically passing along the instructions to each of the inner classes it contains instead of doing any operation on its own. Now my problem is that I want to compare my valuationFunction classes to see if they are the same at one point, for all the derived classes apart from FunctionCombiner I can just directly compare the pointers, but for the FunctionCombiner I of course need the pointers to the Inner objects and not just the pointer to the FunctionCombiner which is all I seeem to have to work with. What would be a good way to get the addresses for the inner classes?

What I've tried is create a virtual function that returns a vector of the inner pointers (or itself) and then compile all of these vectors together to compare them, but this has mostly not compiled, inadvertently made copies, created lots of code where I repeat myself and have been straight up messy. My next idea (that I don't want to do) is to simply add a parameter to all my classes with a unique identifier that I will then retrieve and use for comparison instead of the addresses pointed to by the smart pointers. This solution definitely doesn't feel very elegant though and I would hope to be able to do it some way else.

EDIT with further explanation: The problem is that if I have a FunctionCombiner that contains Function A and Function B, and I compare it with Function A they will of course not be equal. When I compare Function A to FunctionCombiner I really want to compare Function A to Function A (inside function combiner) and Function A to Function B (inside function combiner). The end goal would be to exclude the duplicates so that after comparing Function A and FunctionCombiner I can remove one of the duplicare Function A.

Don't think it's really needed but valuationFunciton is below:

```<code>class valuationFunction
{
public:
    valuationFunction(double TTM);
    virtual void ValueInstrument() = 0;
    virtual double GetValue() const;
    virtual void RiskFactorAdd(double increment, RiskFactor simulatedRiskFactor) = 0;
    virtual void RiskFactorMultiply(double factor, RiskFactor simulatedRiskFactor) = 0;
    virtual void UpdateTTM(double timeStep);
    virtual valuationFunction* clone() const = 0;
    virtual ~valuationFunction() {}
private:

protected:
    double f;
    double TTM;
};
</code>```

答:
If I understand you correctly, you want to compare shared pointers to see if they contain the same stored pointer? Then it's trivial: just use the == operator.

Internally operator== for std::shared_ptr is implemented as:

```<code>lhs.get() == rhs.get()
</code>```

i.e. it checks the stored pointers are the same.

Demo

What you could do is use std::find() to search for a particular std::shared_ptr<valuationFunction> in your vector of "inner" objects. Also have a end() function in FunctionCombiner that you can compare for past end of vector iterator.

So your class definition will be something like this:

```<code>class FunctionCombiner : public ValuationFunction
{
public:
    typedef std::vector<std::shared_ptr<ValuationFunction>>::iterator iterator;

    FunctionCombiner(std::vector<std::shared_ptr<ValuationFunction>> Inner_) : Inner(std::move(Inner_)) {}
    virtual ~FunctionCombiner() = default;

    iterator FindValuationFunction(const std::shared_ptr<ValuationFunction>& fn) {
        return std::find(Inner.begin(), Inner.end(), fn);
    }

    iterator end() { return Inner.end(); }

private:
    std::vector<std::shared_ptr<ValuationFunction>> Inner;
};
</code>```

Then you just need to call FindValuationFunction() and compare with end(). If FindValuationFunction() doesn't equal end() the shared pointer exists in the vector of inner objects.

I also changed the constructor to take vector by value and move it into Inner. That will be more efficient.

Demo.

Hope this is what you are looking for.

Body:
I have a virtual base class called ValuationFunction which basically just contains parameters and can output a value based on some calculation. All of the derived classes behave mostly the same way apart from one, which is called FunctionCombiner and looks like this:

class FunctionCombiner : public valuationFunction
{
public:
    FunctionCombiner(std::vector<std::shared_ptr<valuationFunction>>& Inner_);
    void ValueInstrument();
    void RiskFactorAdd(double increment, RiskFactor simulatedRiskFactor);
    void RiskFactorMultiply(double factor, RiskFactor simulatedRiskFactor);
    virtual valuationFunction* clone() const;
private:
    std::vector<std::shared_ptr<valuationFunction>> Inner;
};

The way it works is that it contains a vector of pointers to other valuation function derived classes and for each of it's functions it's basically passing along the instructions to each of the inner classes it contains instead of doing any operation on its own. Now my problem is that I want to compare my valuationFunction classes to see if they are the same at one point, for all the derived classes apart from FunctionCombiner I can just directly compare the pointers, but for the FunctionCombiner I of course need the pointers to the Inner objects and not just the pointer to the FunctionCombiner which is all I seeem to have to work with. What would be a good way to get the addresses for the inner classes?

What I've tried is create a virtual function that returns a vector of the inner pointers (or itself) and then compile all of these vectors together to compare them, but this has mostly not compiled, inadvertently made copies, created lots of code where I repeat myself and have been straight up messy. My next idea (that I don't want to do) is to simply add a parameter to all my classes with a unique identifier that I will then retrieve and use for comparison instead of the addresses pointed to by the smart pointers. This solution definitely doesn't feel very elegant though and I would hope to be able to do it some way else.

EDIT with further explanation: The problem is that if I have a FunctionCombiner that contains Function A and Function B, and I compare it with Function A they will of course not be equal. When I compare Function A to FunctionCombiner I really want to compare Function A to Function A (inside function combiner) and Function A to Function B (inside function combiner). The end goal would be to exclude the duplicates so that after comparing Function A and FunctionCombiner I can remove one of the duplicare Function A.

Don't think it's really needed but valuationFunciton is below:

class valuationFunction
{
public:
    valuationFunction(double TTM);
    virtual void ValueInstrument() = 0;
    virtual double GetValue() const;
    virtual void RiskFactorAdd(double increment, RiskFactor simulatedRiskFactor) = 0;
    virtual void RiskFactorMultiply(double factor, RiskFactor simulatedRiskFactor) = 0;
    virtual void UpdateTTM(double timeStep);
    virtual valuationFunction* clone() const = 0;
    virtual ~valuationFunction() {}
private:

protected:
    double f;
    double TTM;
};

Body:
If I understand you correctly, you want to compare shared pointers to see if they contain the same stored pointer? Then it's trivial: just use the == operator.

Internally operator== for std::shared_ptr is implemented as:

lhs.get() == rhs.get()

i.e. it checks the stored pointers are the same.

Demo

What you could do is use std::find() to search for a particular std::shared_ptr<valuationFunction> in your vector of "inner" objects. Also have a end() function in FunctionCombiner that you can compare for past end of vector iterator.

So your class definition will be something like this:

class FunctionCombiner : public ValuationFunction
{
public:
    typedef std::vector<std::shared_ptr<ValuationFunction>>::iterator iterator;

    FunctionCombiner(std::vector<std::shared_ptr<ValuationFunction>> Inner_) : Inner(std::move(Inner_)) {}
    virtual ~FunctionCombiner() = default;

    iterator FindValuationFunction(const std::shared_ptr<ValuationFunction>& fn) {
        return std::find(Inner.begin(), Inner.end(), fn);
    }

    iterator end() { return Inner.end(); }

private:
    std::vector<std::shared_ptr<ValuationFunction>> Inner;
};

Then you just need to call FindValuationFunction() and compare with end(). If FindValuationFunction() doesn't equal end() the shared pointer exists in the vector of inner objects.

I also changed the constructor to take vector by value and move it into Inner. That will be more efficient.

Demo.

Hope this is what you are looking for.


来源: stackexchange

问:
Indexing with pointers - How pointer works with slices?
In the below main() code:

```<code>package main

import (
    "fmt"

    "github.com/myhub/cs61a/poetry"
)

func main() {

    p := poetry.NewPoem([][]string{
        {
            "And from my pillow, looking forth by light",
            "Of moon or favoring stars, I could behold",
            "The antechapel where the statue stood",
            "Of Newton, with his prism and silent face,",
            "The marble index of a mind forever",
            "Voyaging through strange seas of thought, alone.",
        },
        {
            "inducted into Greek and Christian",
            "modes of thinking, must take a longer way around.",
            "Like children born into love, they exult in the here",
            "who have felt separation and grave misgivings, they",
            "and of humanity, and of God. Great literature, like",
            "struggles to reconcile suffering with faith in the ",
        },
    })

    fmt.Printf("%T\n", p[0])

}
</code>```

p[0] works fine by pointing to first stanza using below function constructor:

```<code>package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return poem
}
</code>```

If, NewPoem() returns value of type *Poem, as shown below:

```<code>package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) *Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return &poem
}
</code>```

then, p[0] in main() gives below error:

```<code>     Invalid operation: p[0] (type *poetry.Poem does not support indexing)
</code>```

Why pointer to slice of slice of strings does not support p[0] syntax?

答:
Why pointer to slice of slice of strings does not support p[0] syntax?

Short answer: because the language spec does not allow it.

Longer answer: because pointers to slices are rarely used, and why complicate the language with something that doesn't benefit many? If in the rare case you do need it, just dereference the pointer and index the slice.

Note that indexing or slicing an array pointer is allowed by the spec, because when arrays are used, pointers to arrays are more often and more useful (than pointers to slices). Read more about it here: Slicing a slice pointer passed as argument

ContentLicense: CC BY-SA 4.0

Body:
In the below main() code:

package main

import (
    "fmt"

    "github.com/myhub/cs61a/poetry"
)

func main() {

    p := poetry.NewPoem([][]string{
        {
            "And from my pillow, looking forth by light",
            "Of moon or favoring stars, I could behold",
            "The antechapel where the statue stood",
            "Of Newton, with his prism and silent face,",
            "The marble index of a mind forever",
            "Voyaging through strange seas of thought, alone.",
        },
        {
            "inducted into Greek and Christian",
            "modes of thinking, must take a longer way around.",
            "Like children born into love, they exult in the here",
            "who have felt separation and grave misgivings, they",
            "and of humanity, and of God. Great literature, like",
            "struggles to reconcile suffering with faith in the ",
        },
    })

    fmt.Printf("%T\n", p[0])

}

p[0] works fine by pointing to first stanza using below function constructor:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return poem
}

If, NewPoem() returns value of type *Poem, as shown below:

package poetry

type Line string
type Stanza []Line
type Poem []Stanza

func NewPoem(s [][]string) *Poem {
    var poem Poem
    for _, stanza := range s {
        var newStanza Stanza
        for _, line := range stanza {
            newStanza = append(newStanza, Line(line))
        }
        poem = append(poem, newStanza)
    }

    return &poem
}

then, p[0] in main() gives below error:

     Invalid operation: p[0] (type *poetry.Poem does not support indexing)

Why pointer to slice of slice of strings does not support p[0] syntax?


问:
Django and crispy form, how to add id and name in the crispy Layout
I'm trying to use Crispy Forms in my template, but I can't get name, id and class to render properly in the layout.
In other words I have the following templates:

```<code> <div class="modal-body">
        <label for="conto">Conto</label>
        <input class="form-control" id="form-conto" name="formConto"/>
 </div>
</code>```

So I want to delete the input row and add the crispy field, such that id="form-conto" name="formConto" on the input field.

I know that I have to add the layout in my Model.forms but I do not understand how get it.

This is my form:

```<code>class MaterialeForm(forms.ModelForm):

    class Meta:
        model = Materiale
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
</code>```

And here my models:

```<code>class Materiale(models.Model):
    conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True)
</code>```

答:
At the top of your template, load the crispy tags:

```<code>{% load crispy_forms_tags %}
</code>```

Then, tell Crispy to render your form by using the Crispy tag:

```<code><div class="modal-body">
  {% crispy materialeform materialeform.helper %}
</div>
</code>```

In your forms.py, you'll need to add a Layout:

```<code>from crispy_forms import FormHelper, Layout

...

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.layout = Layout(
            Field('conta', id="form-conto", css_class="form-control", title="Conto")
        )

</code>```

See the docs on Layout: https://django-crispy-forms.readthedocs.io/en/latest/layouts.html

Then, when the GET request is made for the form, it will be rendered (more or less) as you desire. You may have to tweak some things. Follow the layout docs above to get there.

But none of this will work unless you actually pass the form in your template. Perhaps you are already doing this, e.g., with a generic FormView, but in case not, here's what you'll need in the view:

```<code>from .forms import MaterialeForm
from django.template import RequestContext

def materialeview(request, template_name):
    materialeform = MaterialeForm()

    # Form handling logic
    [...]

    return render_to_response(template_name, {'materialeform': materialeform}, context_instance=RequestContext(request))
</code>```

On RequestContext, see https://docs.djangoproject.com/en/3.0/ref/templates/api/#using-requestcontext.

For more on Crispy Forms, see https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html.

Finally, since Crispy Forms does a lot in the background, you could consider removing confusion by telling it to fail loudly. Put this in your settings.py file:

```<code>CRISPY_FAIL_SILENTLY = not DEBUG
</code>```

As an aside, let me say that Crispy Forms will likely cause much confusion if you do not yet understand Django Forms well. I'd say start with Django's built-in Forms first and then get crispy later when you want to do more advanced stuff. The docs here should help: https://docs.djangoproject.com/en/3.0/topics/forms/.

Body:
I'm trying to use Crispy Forms in my template, but I can't get name, id and class to render properly in the layout.
In other words I have the following templates:

        Conto
        <input class="form-control" id="form-conto" name="formConto"/>

So I want to delete the input row and add the crispy field, such that id="form-conto" name="formConto" on the input field.

I know that I have to add the layout in my Model.forms but I do not understand how get it.

This is my form:

class MaterialeForm(forms.ModelForm):

    class Meta:
        model = Materiale
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()

And here my models:

class Materiale(models.Model):
    conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True)

Body:
At the top of your template, load the crispy tags:

{% load crispy_forms_tags %}

Then, tell Crispy to render your form by using the Crispy tag:

<div class="modal-body">
  {% crispy materialeform materialeform.helper %}
</div>

In your forms.py, you'll need to add a Layout:

from crispy_forms import FormHelper, Layout

...

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.layout = Layout(
            Field('conta', id="form-conto", css_class="form-control", title="Conto")
        )

See the docs on Layout: https://django-crispy-forms.readthedocs.io/en/latest/layouts.html

Then, when the GET request is made for the form, it will be rendered (more or less) as you desire. You may have to tweak some things. Follow the layout docs above to get there.

But none of this will work unless you actually pass the form in your template. Perhaps you are already doing this, e.g., with a generic FormView, but in case not, here's what you'll need in the view:

from .forms import MaterialeForm
from django.template import RequestContext

def materialeview(request, template_name):
    materialeform = MaterialeForm()

    # Form handling logic
    [...]

    return render_to_response(template_name, {'materialeform': materialeform}, context_instance=RequestContext(request))

On RequestContext, see https://docs.djangoproject.com/en/3.0/ref/templates/api/#using-requestcontext.

For more on Crispy Forms, see https://django-crispy-forms.readthedocs.io/en/latest/crispy_tag_forms.html.

Finally, since Crispy Forms does a lot in the background, you could consider removing confusion by telling it to fail loudly. Put this in your settings.py file:

CRISPY_FAIL_SILENTLY = not DEBUG

As an aside, let me say that Crispy Forms will likely cause much confusion if you do not yet understand Django Forms well. I'd say start with Django's built-in Forms first and then get crispy later when you want to do more advanced stuff. The docs here should help: https://docs.djangoproject.com/en/3.0/topics/forms/.


问:
Get data from a single row in pandas
Usually when I want to iterate over a csv file like this:

```<code>PRODUCTID|PRODUCTNAME|TYPE|PRODUCTDESCRIPTION
1001|Apple|Fruit|McIntosh apple
1002|Pear|Fruit|Rare name pear
1003|Potato|Root|Common potato
1004|Banana|Fruit|Banana from an island
</code>```

I make this if I want to make a filter:

```<code>import pandas
my_products = pandas.read_csv( ... )
fruits = my_products[ my_products.TYPE=="Fruit" ]

for fruit in fruits.itertuples( ):
  doSomething( fruit.PRODUCTNAME, fruit.PRODUCTDESCRIPTION )

</code>```

But if I can filter just one product like this:

```<code>apple = my_products[ my_products.PRODUCTNAME="Apple" ]
</code>```

How can I get PRODUCTDESCRIPTION without needing to iterate over it as in the previous example?
Because it seems I can't just make something like doSomething( "Apple", apple.PRODUCTDESCRIPTION ) or doSomething( "Apple", apple[0].PRODUCTDESCRIPTION )

Thanks in advance.

答:
Simply uses .loc to specify what you are filtering for, and then add the desired column that you want results for that row for.

```<code>my_products.loc[my_products['PRODUCTNAME'] == 'Apple']['PRODUCTDESCRIPTION']
</code>```

OR

```<code>my_products.loc[my_products['PRODUCTNAME'] == 'Apple', 'PRODUCTDESCRIPTION']
</code>```

Output:

```<code>0    McIntosh apple
Name: PRODUCTDESCRIPTION, dtype: object
</code>```

you can then add [0] to the end to access the string. Keep in mind if there are multiple results, you could add [1], [2], etc.

```<code>my_products.loc[my_products['PRODUCTNAME'] == 'Apple']['PRODUCTDESCRIPTION'][0]
</code>```

OR

```<code>my_products.loc[my_products['PRODUCTNAME'] == 'Apple', 'PRODUCTDESCRIPTION'][0]
</code>```

Ouput:

```<code>'McIntosh apple'
</code>```

Title: Get data from a single row in pandas

Body:
Usually when I want to iterate over a csv file like this:

PRODUCTID|PRODUCTNAME|TYPE|PRODUCTDESCRIPTION
1001|Apple|Fruit|McIntosh apple
1002|Pear|Fruit|Rare name pear
1003|Potato|Root|Common potato
1004|Banana|Fruit|Banana from an island

I make this if I want to make a filter:

import pandas
my_products = pandas.read_csv( ... )
fruits = my_products[ my_products.TYPE=="Fruit" ]

for fruit in fruits.itertuples( ):
  doSomething( fruit.PRODUCTNAME, fruit.PRODUCTDESCRIPTION )

But if I can filter just one product like this:

apple = my_products[ my_products.PRODUCTNAME="Apple" ]

How can I get PRODUCTDESCRIPTION without needing to iterate over it as in the previous example?
Because it seems I can't just make something like doSomething( "Apple", apple.PRODUCTDESCRIPTION ) or doSomething( "Apple", apple[0].PRODUCTDESCRIPTION )

Thanks in advance.

Body:
Simply uses .loc to specify what you are filtering for, and then add the desired column that you want results for that row for.

my_products.loc[my_products['PRODUCTNAME'] == 'Apple']['PRODUCTDESCRIPTION']

OR

my_products.loc[my_products['PRODUCTNAME'] == 'Apple', 'PRODUCTDESCRIPTION']

Output:

0    McIntosh apple
Name: PRODUCTDESCRIPTION, dtype: object

you can then add [0] to the end to access the string. Keep in mind if there are multiple results, you could add [1], [2], etc.

my_products.loc[my_products['PRODUCTNAME'] == 'Apple']['PRODUCTDESCRIPTION'][0]

OR

my_products.loc[my_products['PRODUCTNAME'] == 'Apple', 'PRODUCTDESCRIPTION'][0]

Ouput:

'McIntosh apple'


问:
Execute javascript when another function exists
I'm writing two scripts in an web environment where I don't have control over the order in which they are loaded.  Let's say the two scripts are called MyUtil and DoSomething.

MyUtil contains utilities that I will bind to the window object using window.myUtil = myUtil.  I'm then going to call methods of myUtil from within DoSomething.

If MyUtil is loaded first, everything will work. If it's loaded second, window.myUtil will be undefined.

How can I modify the code in DoSomething (and/or MyUtil) to wait until window.myUtil exists before DoSomething executes its code?

NB: I'm using jQuery 1.2.3.

答:
You can test for window.myUtil and if it's undefined, deal with it. That might mean using setInterval or setTimeout to poll for its existence and when it's found, proceed.

You can also wait for the load event, but that might be too late.

ContentLicense: CC BY-SA 3.0


问:
RDS Postgres Logical Replication into EC2 - only rds_superusers can query or manipulate replication origins
We try to replicate from AWS RDS pg11 (pglogical 2.2.1) to pg12.
AWS RDS pg12 has only pglogical 2.3.0, which is not compatible to 2.2.1, and there is no way to downgrade (tried already). The replication starts and creates schemas in target, but stops then due to some errors (no need to cover it here).
As a workaround we want to replicate to EC2 instance with pg12 and pglogical 2.3.1 (compatible with 2.2.1 and should work well).

Both users are setup in both databases the same way, the nodes are OK. The replication fails with
ERROR:  only rds_superusers can query or manipulate replication origins.

And no idea how to debug this issue.

答:
As already mentioned by gsteiner: the user was not explicitly granted rds_superuser role. Even though I was using a role which was initially assigned by the AWS engine, looks like it "dropped out" of rds_superuser some time ago and I had to reassign.
While checking for roles, you don't see that you belong to rds_superuser(or not). So if something like this happens one might grant rds_superuser (again) to be sure that this one is resolved.
Best way to ensure that this works how intended is to create a new role right away in role rds_superuser.


问:
apache2.service: Control process exited, code=exited status=139
I install apache2 on ubuntu 18.04. This is fresh install with all default configuration.

I tried to start apache2 but failed. And this is what I see.

```<code># systemctl status apache2.service
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Wed 2020-03-11 23:17:35 WIB; 13s ago
  Process: 9151 ExecStart=/usr/sbin/apachectl start (code=exited, status=139)

Mar 11 23:17:35 xdn.id systemd[1]: Starting The Apache HTTP Server...
Mar 11 23:17:35 xdn.id apachectl[9151]: Segmentation fault
Mar 11 23:17:35 xdn.id apachectl[9151]: Action 'start' failed.
Mar 11 23:17:35 xdn.id apachectl[9151]: The Apache error log may have more information.
Mar 11 23:17:35 xdn.id systemd[1]: apache2.service: Control process exited, code=exited status=139
Mar 11 23:17:35 xdn.id systemd[1]: apache2.service: Failed with result 'exit-code'.
Mar 11 23:17:35 xdn.id systemd[1]: Failed to start The Apache HTTP Server.
</code>```

When I check /var/log/apache2/error.log, there is empty.

What's wrong with this error?

答:
The "status=139" error must have something to do with having multiple, conflicting versions of PHP enabled.

I am running 18.04 and an old PHP site I run only locally ceased to work.  I am guessing aptitude installed and enabled php7.2, possibly when I installed kubuntu-desktop a few weeks back.

Regardless, I had two versions of PHP enabled:

```<code> $ cd /etc/apache2/
 $ l mods-*/php*
-rw-r--r-- 1 root root 867 Jun  9  2017 mods-available/php5.6.conf
-rw-r--r-- 1 root root 102 Jun  9  2017 mods-available/php5.6.load
-rw-r--r-- 1 root root 867 Mar  2  2017 mods-available/php7.0.conf
-rw-r--r-- 1 root root 102 Oct  1  2018 mods-available/php7.0.load
-rw-r--r-- 1 root root 855 Jul  7  2017 mods-available/php7.1.conf
-rw-r--r-- 1 root root 102 Jul  7  2017 mods-available/php7.1.load
-rw-r--r-- 1 root root 855 Feb  8  2019 mods-available/php7.2.conf
-rw-r--r-- 1 root root 102 Feb  8  2019 mods-available/php7.2.load
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.conf -> ../mods-available/php5.6.conf
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.load -> ../mods-available/php5.6.load
lrwxrwxrwx 1 root root  29 May 28 06:05 mods-enabled/php7.2.conf -> ../mods-available/php7.2.conf
lrwxrwxrwx 1 root root  29 May 28 06:05 mods-enabled/php7.2.load -> ../mods-available/php7.2.load
</code>```

In my case, I am fine with using php5.6, because the site is not online and is purely for my local use only.  So disabling 7.2 did the trick:

```<code>sudo a2dismod php7.2
</code>```

Now my php mods-enabled are less confusing to apache3:

```<code> $ l mods-*/php*
-rw-r--r-- 1 root root 867 Jun  9  2017 mods-available/php5.6.conf
-rw-r--r-- 1 root root 102 Jun  9  2017 mods-available/php5.6.load
-rw-r--r-- 1 root root 867 Mar  2  2017 mods-available/php7.0.conf
-rw-r--r-- 1 root root 102 Oct  1  2018 mods-available/php7.0.load
-rw-r--r-- 1 root root 855 Jul  7  2017 mods-available/php7.1.conf
-rw-r--r-- 1 root root 102 Jul  7  2017 mods-available/php7.1.load
-rw-r--r-- 1 root root 855 Feb  8  2019 mods-available/php7.2.conf
-rw-r--r-- 1 root root 102 Feb  8  2019 mods-available/php7.2.load
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.conf -> ../mods-available/php5.6.conf
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.load -> ../mods-available/php5.6.load
</code>```

Naturally for a live site one would want to disable php-5.6 and leave the php7.2 enabled, because you should run the newer version in real life.

```<code>sudo a2dismod php5.6
sudo a2enmod php7.2
</code>```

Then the php mods should look like this:

```<code> $ l mods-*/php*
-rw-r--r-- 1 root root 867 Jun  9  2017 mods-available/php5.6.conf
-rw-r--r-- 1 root root 102 Jun  9  2017 mods-available/php5.6.load
-rw-r--r-- 1 root root 867 Mar  2  2017 mods-available/php7.0.conf
-rw-r--r-- 1 root root 102 Oct  1  2018 mods-available/php7.0.load
-rw-r--r-- 1 root root 855 Jul  7  2017 mods-available/php7.1.conf
-rw-r--r-- 1 root root 102 Jul  7  2017 mods-available/php7.1.load
-rw-r--r-- 1 root root 855 Feb  8  2019 mods-available/php7.2.conf
-rw-r--r-- 1 root root 102 Feb  8  2019 mods-available/php7.2.load
lrwxrwxrwx 1 root root  29 May 29 17:43 mods-enabled/php7.2.conf -> ../mods-available/php7.2.conf
lrwxrwxrwx 1 root root  29 May 29 17:43 mods-enabled/php7.2.load -> ../mods-available/php7.2.load
</code>```

Don't forget to resatart the server!

```<code>systemctl restart apache2
</code>```

Thanks to Pavel's comment for inspiring this line of research!

Body:
I install apache2 on ubuntu 18.04. This is fresh install with all default configuration.

I tried to start apache2 but failed. And this is what I see.

# systemctl status apache2.service
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: failed (Result: exit-code) since Wed 2020-03-11 23:17:35 WIB; 13s ago
  Process: 9151 ExecStart=/usr/sbin/apachectl start (code=exited, status=139)

Mar 11 23:17:35 xdn.id systemd[1]: Starting The Apache HTTP Server...
Mar 11 23:17:35 xdn.id apachectl[9151]: Segmentation fault
Mar 11 23:17:35 xdn.id apachectl[9151]: Action 'start' failed.
Mar 11 23:17:35 xdn.id apachectl[9151]: The Apache error log may have more information.
Mar 11 23:17:35 xdn.id systemd[1]: apache2.service: Control process exited, code=exited status=139
Mar 11 23:17:35 xdn.id systemd[1]: apache2.service: Failed with result 'exit-code'.
Mar 11 23:17:35 xdn.id systemd[1]: Failed to start The Apache HTTP Server.

When I check /var/log/apache2/error.log, there is empty.

What's wrong with this error?

Body:
The "status=139" error must have something to do with having multiple, conflicting versions of PHP enabled.

I am running 18.04 and an old PHP site I run only locally ceased to work.  I am guessing aptitude installed and enabled php7.2, possibly when I installed kubuntu-desktop a few weeks back.

Regardless, I had two versions of PHP enabled:

 $ cd /etc/apache2/
 $ l mods-*/php*
-rw-r--r-- 1 root root 867 Jun  9  2017 mods-available/php5.6.conf
-rw-r--r-- 1 root root 102 Jun  9  2017 mods-available/php5.6.load
-rw-r--r-- 1 root root 867 Mar  2  2017 mods-available/php7.0.conf
-rw-r--r-- 1 root root 102 Oct  1  2018 mods-available/php7.0.load
-rw-r--r-- 1 root root 855 Jul  7  2017 mods-available/php7.1.conf
-rw-r--r-- 1 root root 102 Jul  7  2017 mods-available/php7.1.load
-rw-r--r-- 1 root root 855 Feb  8  2019 mods-available/php7.2.conf
-rw-r--r-- 1 root root 102 Feb  8  2019 mods-available/php7.2.load
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.conf -> ../mods-available/php5.6.conf
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.load -> ../mods-available/php5.6.load
lrwxrwxrwx 1 root root  29 May 28 06:05 mods-enabled/php7.2.conf -> ../mods-available/php7.2.conf
lrwxrwxrwx 1 root root  29 May 28 06:05 mods-enabled/php7.2.load -> ../mods-available/php7.2.load

In my case, I am fine with using php5.6, because the site is not online and is purely for my local use only.  So disabling 7.2 did the trick:

sudo a2dismod php7.2

Now my php mods-enabled are less confusing to apache3:

 $ l mods-*/php*
-rw-r--r-- 1 root root 867 Jun  9  2017 mods-available/php5.6.conf
-rw-r--r-- 1 root root 102 Jun  9  2017 mods-available/php5.6.load
-rw-r--r-- 1 root root 867 Mar  2  2017 mods-available/php7.0.conf
-rw-r--r-- 1 root root 102 Oct  1  2018 mods-available/php7.0.load
-rw-r--r-- 1 root root 855 Jul  7  2017 mods-available/php7.1.conf
-rw-r--r-- 1 root root 102 Jul  7  2017 mods-available/php7.1.load
-rw-r--r-- 1 root root 855 Feb  8  2019 mods-available/php7.2.conf
-rw-r--r-- 1 root root 102 Feb  8  2019 mods-available/php7.2.load
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.conf -> ../mods-available/php5.6.conf
lrwxrwxrwx 1 root root  29 Jul  1  2017 mods-enabled/php5.6.load -> ../mods-available/php5.6.load

Naturally for a live site one would want to disable php-5.6 and leave the php7.2 enabled, because you should run the newer version in real life.

sudo a2dismod php5.6
sudo a2enmod php7.2

Then the php mods should look like this:

 $ l mods-*/php*
-rw-r--r-- 1 root root 867 Jun  9  2017 mods-available/php5.6.conf
-rw-r--r-- 1 root root 102 Jun  9  2017 mods-available/php5.6.load
-rw-r--r-- 1 root root 867 Mar  2  2017 mods-available/php7.0.conf
-rw-r--r-- 1 root root 102 Oct  1  2018 mods-available/php7.0.load
-rw-r--r-- 1 root root 855 Jul  7  2017 mods-available/php7.1.conf
-rw-r--r-- 1 root root 102 Jul  7  2017 mods-available/php7.1.load
-rw-r--r-- 1 root root 855 Feb  8  2019 mods-available/php7.2.conf
-rw-r--r-- 1 root root 102 Feb  8  2019 mods-available/php7.2.load
lrwxrwxrwx 1 root root  29 May 29 17:43 mods-enabled/php7.2.conf -> ../mods-available/php7.2.conf
lrwxrwxrwx 1 root root  29 May 29 17:43 mods-enabled/php7.2.load -> ../mods-available/php7.2.load

Don't forget to resatart the server!

systemctl restart apache2

Thanks to Pavel's comment for inspiring this line of research!


问:
Doesn't keras.layers.Flatten lose information?
Brand new to keras and ML in general. I'm looking at https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/, and it uses Flatten between Embedding and Dense because Embedding produces a 2D vector but Dense requires a single dimension.

I'm sure I'm missing something obvious here, but why doesn't this lose which words are in which input vectors? How are we able to still know that input #3 was "nice work" and is associated with label #3, 1, for "positive"?

I guess the original dimensions are retained from the original input and then somehow restored for Dense's output? Or am I just totally missing a major conceptual aspect?

```<code>model = Sequential()
model.add(Embedding(vocab_size, 8, input_length=max_length))
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))
</code>```

Thanks for any guidance!

答:
Embedding layer gives you a vector for each word token, so the output is 2-d. We need to use flatten before any classifier block.

There is some information lost, for example when we use Convolutional layers, and then flat the feature maps, the spatial information is lost. But we already extract the most important features using Conv layers and we feed those features to fully connected layers.

In your example, the temporal dimension is no longer maintained, usually, it's desired to pass the output of the embedding matrix to an RNN/Conv layer for further feature extraction.

Flatten only is applied on the non-batch dimension, meaning the examples are still separated (if you mean that).

For each sample, let's say nice work, we get 2 vectors (1 for nice, 1 for work), now we only want to know the overall sentiment from the sentence so, once we extract the features, we can apply flatten.

Body:
Brand new to keras and ML in general. I'm looking at https://machinelearningmastery.com/use-word-embedding-layers-deep-learning-keras/, and it uses Flatten between Embedding and Dense because Embedding produces a 2D vector but Dense requires a single dimension.

I'm sure I'm missing something obvious here, but why doesn't this lose which words are in which input vectors? How are we able to still know that input #3 was "nice work" and is associated with label #3, 1, for "positive"?

I guess the original dimensions are retained from the original input and then somehow restored for Dense's output? Or am I just totally missing a major conceptual aspect?

model = Sequential()
model.add(Embedding(vocab_size, 8, input_length=max_length))
model.add(Flatten())
model.add(Dense(1, activation='sigmoid'))

Thanks for any guidance!


问:
ArgumentNullException when deserializing JSON
I'm trying to deserialize a json like this

```<code>{
"geneslist": [
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "region",
  "start": "1",
  "end": "29903",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=NC_045512.2:1..29903;Dbxref=taxon:2697049;collectiondate=Dec-2019;country=China;gbacronym=SARS-CoV2;gbkey=Src;genome=genomic;isolate=Wuhan-Hu-1;mol_type=genomic RNA;nathost=Homo sapiens;oldname=Wuhan seafood market pneumonia virus",
  "ID": "NC_045512.2:1..29903",
  "Note": null,
  "Dbxref": "taxon:2697049",
  "collectiondate": "Dec-2019",
  "country": "China",
  "gbacronym": "SARS-CoV2",
  "gbkey": "Src",
  "gene": null,
  "inference": null,
  "genome": "genomic",
  "isolate": "Wuhan-Hu-1",
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": "genomic RNA",
  "nathost": "Homo sapiens",
  "oldname": "Wuhan seafood market pneumonia virus"
},
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "five_prime_UTR",
  "start": "1",
  "end": "265",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=id-NC_045512.2:1..265;gbkey=5'UTR",
  "ID": "id-NC_045512.2:1..265",
  "Note": null,
  "function": null,
  "Dbxref": null,
  "collectiondate": null,
  "country;": null,
  "gbkey": "5'UTR",
  "Dbxrref": null,
  "country": null,
  "gbacronym": null,
  "gene": null,
  "inference": null,
  "genome": null,
  "isolate": null,
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": null,
  "nathost": null,
  "oldname": null
},{..} ]
}
</code>```

where some data might be null or existing, I made two objects for this:

```<code>public class GenesList
{

    private string seqid;
    private string source;
    private string type;
    private int start;
    private int end;
    private string score;
    private string strand;
    private string phase;
    private string attributes;
    private string ID;
    private string Note;
    private string function;
    private string Dbxref;
    private string collectiondate;
    private string country;
    private string gbacronym;
    private string gbkey;
    private string gene;
    private string inference;
    private string genome;
    private string isolate;
    private string locus_tag;
    private string gene_biotype;
    private string product;
    private string protein_id;
    private string mol_type;
    private string nathost;
    private string oldname;

    public string Seqid { get => seqid; set => seqid = value; }
    public string Source {get => source; set => source = value; }
    public string Type { get => type; set => type = value; }
    public int Start { get => start; set => start = value; }
    public int End { get => end; set => end = value; }
    public string Score { get => score; set => score = value; }
    public string Strand { get => strand; set => strand = value; }
    public string Phase { get => phase; set => phase = value; }
    public string Attributes { get => attributes; set => attributes = value; }
    public string ID1 { get => ID; set => ID = value; }
    public string Dbxref1 { get => Dbxref; set => Dbxref = value; }
    public string Collectiondate { get => collectiondate; set => collectiondate = value; }
    public string Country { get => country; set => country = value; }
    public string Gbacronym { get => gbacronym; set => gbacronym = value; }
    public string Gbkey { get => gbkey; set => gbkey = value; }
    public string Genome { get => genome; set => genome = value; }
    public string Isolate { get => isolate; set => isolate = value; }
    public string Mol_type { get => mol_type; set => mol_type = value; }
    public string Nathost { get => nathost; set => nathost = value; }
    public string Oldname { get => oldname; set => oldname = value; }
    public string Locus_tag { get => locus_tag; set => locus_tag = value; }
    public string Gene_biotype { get => gene_biotype; set => gene_biotype = value; }
    public string Function { get => function; set => function = value; }
    public string Inference { get => inference; set => inference = value; }
    public string Product { get => product; set => product = value; }
    public string Protein_id { get => protein_id; set => protein_id = value; }

    public string GetGene()
    {
        return gene;
    }

    public void SetGene(string value)
    {
        gene = value;
    }
}
</code>```

and

```<code> public class GenesWrapper
{
    private List<GenesList> geneslist;

    public List<GenesList> Genes { get => geneslist; set => geneslist = value; }
}
</code>```

but when I'm trying to deserialize with

```<code> GenesWrapper genesList = new GenesWrapper();

 genesList = JsonConvert.DeserializeObject<GenesWrapper>(file2);
</code>```

I'm getting an ArgomentNullException because the object is null after deserializing, did I build a bad object? At first I tought it could have had some problems with the null values or maybe the order the json file has been made. I used NullValueHandling.Ignore but the values are still null, how can I solve?
 Sorry for the wall of text, thank you

答:
you can do this instead :

```<code>public class GenesList
{
    [JsonProperty("seqid")]
    public string Seqid { get; set; }

    [JsonProperty("source")]
    public string Source { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("start")]
    [JsonConverter(typeof(ParseStringConverter))]
    public int Start { get; set; }

    [JsonProperty("end")]
    [JsonConverter(typeof(ParseStringConverter))]
    public int End { get; set; }

    [JsonProperty("score")]
    public string Score { get; set; }

    [JsonProperty("strand")]
    public string Strand { get; set; }

    [JsonProperty("phase")]
    public string Phase { get; set; }

    [JsonProperty("attributes")]
    public string Attributes { get; set; }

    [JsonProperty("ID")]
    public string Id { get; set; }

    [JsonProperty("Note")]
    public string Note { get; set; }

    [JsonProperty("Dbxref")]
    public string Dbxref { get; set; }

    [JsonProperty("collectiondate")]
    public string Collectiondate { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("gbacronym")]
    public string Gbacronym { get; set; }

    [JsonProperty("gbkey")]
    public string Gbkey { get; set; }

    [JsonProperty("gene")]
    public string Gene { get; set; }

    [JsonProperty("inference")]
    public string Inference { get; set; }

    [JsonProperty("genome")]
    public string Genome { get; set; }

    [JsonProperty("isolate")]
    public string Isolate { get; set; }

    [JsonProperty("locus_tag")]
    public string LocusTag { get; set; }

    [JsonProperty("gene_biotype")]
    public string GeneBiotype { get; set; }

    [JsonProperty("product")]
    public string Product { get; set; }

    [JsonProperty("protein_id")]
    public string ProteinId { get; set; }

    [JsonProperty("mol_type")]
    public string MolType { get; set; }

    [JsonProperty("nathost")]
    public string Nathost { get; set; }

    [JsonProperty("oldname")]
    public string Oldname { get; set; }

}
</code>```

Then use JObject to navigate to the geneslist, and then just get the string to deserilize it. Something like this :

```<code>var jObj = JObject.Parse(json);
var genes = jObj["geneslist"].ToString();
var genesList = JsonConvert.DeserializeObject<List<GenesList>>(genes);
</code>```

That's if you need to only deserilize geneslist and ignore the rest of the json. If you want to deserilize the whole json keys, you'll need a wrapper class that would define each property in the json root. Something like this :

```<code>public class JsonWrapper
{
    [JsonProperty("geneslist")]
    public IEnumerable<GenesList> Genes { get; set; }

    // ... other json keys..
}
</code>```

Then, you can do this directly :

```<code>var genes = JsonConvert.DeserializeObject<JsonWrapper>(json);
</code>```

Body:
I'm trying to deserialize a json like this

{
"geneslist": [
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "region",
  "start": "1",
  "end": "29903",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=NC_045512.2:1..29903;Dbxref=taxon:2697049;collectiondate=Dec-2019;country=China;gbacronym=SARS-CoV2;gbkey=Src;genome=genomic;isolate=Wuhan-Hu-1;mol_type=genomic RNA;nathost=Homo sapiens;oldname=Wuhan seafood market pneumonia virus",
  "ID": "NC_045512.2:1..29903",
  "Note": null,
  "Dbxref": "taxon:2697049",
  "collectiondate": "Dec-2019",
  "country": "China",
  "gbacronym": "SARS-CoV2",
  "gbkey": "Src",
  "gene": null,
  "inference": null,
  "genome": "genomic",
  "isolate": "Wuhan-Hu-1",
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": "genomic RNA",
  "nathost": "Homo sapiens",
  "oldname": "Wuhan seafood market pneumonia virus"
},
{
  "seqid": "NC_045512.2",
  "source": "RefSeq",
  "type": "five_prime_UTR",
  "start": "1",
  "end": "265",
  "score": ".",
  "strand": "+",
  "phase": ".",
  "attributes": "ID=id-NC_045512.2:1..265;gbkey=5'UTR",
  "ID": "id-NC_045512.2:1..265",
  "Note": null,
  "function": null,
  "Dbxref": null,
  "collectiondate": null,
  "country;": null,
  "gbkey": "5'UTR",
  "Dbxrref": null,
  "country": null,
  "gbacronym": null,
  "gene": null,
  "inference": null,
  "genome": null,
  "isolate": null,
  "locus_tag": null,
  "gene_biotype": null,
  "product": null,
  "protein_id": null,
  "mol_type": null,
  "nathost": null,
  "oldname": null
},{..} ]
}

where some data might be null or existing, I made two objects for this:

public class GenesList
{

    private string seqid;
    private string source;
    private string type;
    private int start;
    private int end;
    private string score;
    private string strand;
    private string phase;
    private string attributes;
    private string ID;
    private string Note;
    private string function;
    private string Dbxref;
    private string collectiondate;
    private string country;
    private string gbacronym;
    private string gbkey;
    private string gene;
    private string inference;
    private string genome;
    private string isolate;
    private string locus_tag;
    private string gene_biotype;
    private string product;
    private string protein_id;
    private string mol_type;
    private string nathost;
    private string oldname;

    public string Seqid { get => seqid; set => seqid = value; }
    public string Source {get => source; set => source = value; }
    public string Type { get => type; set => type = value; }
    public int Start { get => start; set => start = value; }
    public int End { get => end; set => end = value; }
    public string Score { get => score; set => score = value; }
    public string Strand { get => strand; set => strand = value; }
    public string Phase { get => phase; set => phase = value; }
    public string Attributes { get => attributes; set => attributes = value; }
    public string ID1 { get => ID; set => ID = value; }
    public string Dbxref1 { get => Dbxref; set => Dbxref = value; }
    public string Collectiondate { get => collectiondate; set => collectiondate = value; }
    public string Country { get => country; set => country = value; }
    public string Gbacronym { get => gbacronym; set => gbacronym = value; }
    public string Gbkey { get => gbkey; set => gbkey = value; }
    public string Genome { get => genome; set => genome = value; }
    public string Isolate { get => isolate; set => isolate = value; }
    public string Mol_type { get => mol_type; set => mol_type = value; }
    public string Nathost { get => nathost; set => nathost = value; }
    public string Oldname { get => oldname; set => oldname = value; }
    public string Locus_tag { get => locus_tag; set => locus_tag = value; }
    public string Gene_biotype { get => gene_biotype; set => gene_biotype = value; }
    public string Function { get => function; set => function = value; }
    public string Inference { get => inference; set => inference = value; }
    public string Product { get => product; set => product = value; }
    public string Protein_id { get => protein_id; set => protein_id = value; }

    public string GetGene()
    {
        return gene;
    }

    public void SetGene(string value)
    {
        gene = value;
    }
}

and

 public class GenesWrapper
{
    private List<GenesList> geneslist;

    public List<GenesList> Genes { get => geneslist; set => geneslist = value; }
}

but when I'm trying to deserialize with

 GenesWrapper genesList = new GenesWrapper();

 genesList = JsonConvert.DeserializeObject<GenesWrapper>(file2);

I'm getting an ArgomentNullException because the object is null after deserializing, did I build a bad object? At first I tought it could have had some problems with the null values or maybe the order the json file has been made. I used NullValueHandling.Ignore but the values are still null, how can I solve?
 Sorry for the wall of text, thank you

Body:
you can do this instead :

public class GenesList
{
    [JsonProperty("seqid")]
    public string Seqid { get; set; }

    [JsonProperty("source")]
    public string Source { get; set; }

    [JsonProperty("type")]
    public string Type { get; set; }

    [JsonProperty("start")]
    [JsonConverter(typeof(ParseStringConverter))]
    public int Start { get; set; }

    [JsonProperty("end")]
    [JsonConverter(typeof(ParseStringConverter))]
    public int End { get; set; }

    [JsonProperty("score")]
    public string Score { get; set; }

    [JsonProperty("strand")]
    public string Strand { get; set; }

    [JsonProperty("phase")]
    public string Phase { get; set; }

    [JsonProperty("attributes")]
    public string Attributes { get; set; }

    [JsonProperty("ID")]
    public string Id { get; set; }

    [JsonProperty("Note")]
    public string Note { get; set; }

    [JsonProperty("Dbxref")]
    public string Dbxref { get; set; }

    [JsonProperty("collectiondate")]
    public string Collectiondate { get; set; }

    [JsonProperty("country")]
    public string Country { get; set; }

    [JsonProperty("gbacronym")]
    public string Gbacronym { get; set; }

    [JsonProperty("gbkey")]
    public string Gbkey { get; set; }

    [JsonProperty("gene")]
    public string Gene { get; set; }

    [JsonProperty("inference")]
    public string Inference { get; set; }

    [JsonProperty("genome")]
    public string Genome { get; set; }

    [JsonProperty("isolate")]
    public string Isolate { get; set; }

    [JsonProperty("locus_tag")]
    public string LocusTag { get; set; }

    [JsonProperty("gene_biotype")]
    public string GeneBiotype { get; set; }

    [JsonProperty("product")]
    public string Product { get; set; }

    [JsonProperty("protein_id")]
    public string ProteinId { get; set; }

    [JsonProperty("mol_type")]
    public string MolType { get; set; }

    [JsonProperty("nathost")]
    public string Nathost { get; set; }

    [JsonProperty("oldname")]
    public string Oldname { get; set; }

}

Then use JObject to navigate to the geneslist, and then just get the string to deserilize it. Something like this :

var jObj = JObject.Parse(json);
var genes = jObj["geneslist"].ToString();
var genesList = JsonConvert.DeserializeObject<List<GenesList>>(genes);

That's if you need to only deserilize geneslist and ignore the rest of the json. If you want to deserilize the whole json keys, you'll need a wrapper class that would define each property in the json root. Something like this :

public class JsonWrapper
{
    [JsonProperty("geneslist")]
    public IEnumerable<GenesList> Genes { get; set; }

    // ... other json keys..
}

Then, you can do this directly :

var genes = JsonConvert.DeserializeObject<JsonWrapper>(json);


问:
WPF app builds in vs2k8, but not on command line w/ msbuild
I have a fairly small solution that includes a WPF windows application. It builds perfectly fine when built from the solution. I recently integrated the projects contained within the solution into an existing, much larger command line build that uses MSBuild. When built from the command line, however, I get the following errors:

```<code>MainWindow.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\EngineMonitorView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\HostingEngineView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\MainView.xaml.cs(13,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\MainView.xaml.cs(17,52): error CS0103: The name 'gView' does not exist in the current context
View\PerformanceCounterView.xaml.cs(22,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\PerformanceCounterView.xaml.cs(117,22): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(118,20): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(127,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(138,5): error CS0103: The name 'txtScale' does not exist in the current context
View\PerformanceCounterView.xaml.cs(179,5): error CS0103: The name 'txtLast' does not exist in the current context
View\PerformanceCounterView.xaml.cs(180,5): error CS0103: The name 'txtMin' does not exist in the current context
View\PerformanceCounterView.xaml.cs(181,5): error CS0103: The name 'txtMax' does not exist in the current context
View\PerformanceCounterView.xaml.cs(189,5): error CS0103: The name 'txtAverage' does not exist in the current context
View\PerformanceCounterView.xaml.cs(250,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(251,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(253,27): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(255,27): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(264,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(269,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(274,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(279,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(293,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(303,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(318,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(325,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(342,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\ServerMonitorView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\ServerTreeView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\ServiceDetailView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\ServiceMonitorView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
</code>```

I included the WinFX targets file from .NET 3.5 in our root MSBuild .proj file, as it did not appear to be included anywhere else:

```<code><Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />
</code>```

That did not seem to affect anything, though, and I am still encountering the errors. As far as I can tell, it appears that the custom WPF build tasks that precompile the .xaml files into .cs files, embeds and wires up resources, etc. are not running, which is why InitializeComponent and any controls defined in my views are not found. I am at a loss as to why, though...and trying to wade through the zillions of search results related to WPF and MSBuild is not getting me anywhere.

UPDATE:

Adding the Microsoft.WinFX.targets to the .csproj file seems like it would work. However, doing so causes the project to fail to build within Visual Studio 2008. Somehow, VS is including those targets for you...but I am unsure how. Does anyone know more about how VS builds WPF projects? Is there a master build file hiding somewhere that imports the appropriate targets?

答:
If you're asking, if visual studio works why doesn't msbuild?

Then the answer is most likely that you're using the wrong version of msbuild.
You'll need msbuild 4 to build .net 4 projects.

Also see the following link http://blogs.digitaldeposit.net/saravana/post/2011/02/08/CS0103-The-name-e28098InitializeComponente28099-does-not-exist-in-the-current-context.aspx

ContentLicense: CC BY-SA 2.5

Body:
I have a fairly small solution that includes a WPF windows application. It builds perfectly fine when built from the solution. I recently integrated the projects contained within the solution into an existing, much larger command line build that uses MSBuild. When built from the command line, however, I get the following errors:

MainWindow.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\EngineMonitorView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\HostingEngineView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\MainView.xaml.cs(13,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\MainView.xaml.cs(17,52): error CS0103: The name 'gView' does not exist in the current context
View\PerformanceCounterView.xaml.cs(22,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\PerformanceCounterView.xaml.cs(117,22): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(118,20): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(127,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(138,5): error CS0103: The name 'txtScale' does not exist in the current context
View\PerformanceCounterView.xaml.cs(179,5): error CS0103: The name 'txtLast' does not exist in the current context
View\PerformanceCounterView.xaml.cs(180,5): error CS0103: The name 'txtMin' does not exist in the current context
View\PerformanceCounterView.xaml.cs(181,5): error CS0103: The name 'txtMax' does not exist in the current context
View\PerformanceCounterView.xaml.cs(189,5): error CS0103: The name 'txtAverage' does not exist in the current context
View\PerformanceCounterView.xaml.cs(250,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(251,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(253,27): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(255,27): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(264,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(269,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(274,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(279,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(293,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(303,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(318,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(325,5): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\PerformanceCounterView.xaml.cs(342,4): error CS0103: The name 'cnvsCounterGrid' does not exist in the current context
View\ServerMonitorView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\ServerTreeView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\ServiceDetailView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context
View\ServiceMonitorView.xaml.cs(12,4): error CS0103: The name 'InitializeComponent' does not exist in the current context

I included the WinFX targets file from .NET 3.5 in our root MSBuild .proj file, as it did not appear to be included anywhere else:

<Import Project="$(MSBuildBinPath)\Microsoft.WinFX.targets" />

That did not seem to affect anything, though, and I am still encountering the errors. As far as I can tell, it appears that the custom WPF build tasks that precompile the .xaml files into .cs files, embeds and wires up resources, etc. are not running, which is why InitializeComponent and any controls defined in my views are not found. I am at a loss as to why, though...and trying to wade through the zillions of search results related to WPF and MSBuild is not getting me anywhere.

UPDATE:

Adding the Microsoft.WinFX.targets to the .csproj file seems like it would work. However, doing so causes the project to fail to build within Visual Studio 2008. Somehow, VS is including those targets for you...but I am unsure how. Does anyone know more about how VS builds WPF projects? Is there a master build file hiding somewhere that imports the appropriate targets?


问:
Odoo Error to render compiling AST, UndefinedTable
I already had an database A (with Web, Sales, Invoices,...) on Odoo.com
But now I want to use that database on local computer. So I made a backup of database A, and then restore it on localhost:8069
The restoration was successful however when I can't connect to it.

```<code>Error to render compiling AST
UndefinedTable: relation "ir_attachment_id_seq" does not exist
LINE 1: ...ore_fname", "type", "website_id") VALUES (nextval('ir_attach...
                                                             ^

Template: web.frontend_layout
Path: /t/html/head/t[10]
Node: <t t-call-assets="web.assets_common_minimal_js" t-css="false" defer_load="True"/>
</code>```

And its traceback:

```<code>Traceback (most recent call last):
  File "Q:\odoo-13.0\odoo\tools\cache.py", line 85, in lookup
    r = d[key]
  File "Q:\odoo-13.0\odoo\tools\func.py", line 69, in wrapper
    return func(self, *args, **kwargs)
  File "Q:\odoo-13.0\odoo\tools\lru.py", line 44, in __getitem__
    a = self.d[obj].me
KeyError: ('ir.qweb', <function IrQWeb._get_asset_nodes at 0x0586C4F8>, 'web.assets_common_minimal_js', 'vi_VN', False, True, '', False, True, False, (1,))

During handling of the above exception, another exception occurred:
</code>```

...

Could you guys please help me. Thanks in advance.

答: Your database is not loading well so these models are not loaded in registry, just restore it again!</p>

Body:
I already had an database A (with Web, Sales, Invoices,...) on Odoo.com
But now I want to use that database on local computer. So I made a backup of database A, and then restore it on localhost:8069
The restoration was successful however when I can't connect to it.

Error to render compiling AST
UndefinedTable: relation "ir_attachment_id_seq" does not exist
LINE 1: ...ore_fname", "type", "website_id") VALUES (nextval('ir_attach...
                                                             ^

Template: web.frontend_layout
Path: /t/html/head/t[10]
Node: <t t-call-assets="web.assets_common_minimal_js" t-css="false" defer_load="True"/>

And its traceback:

Traceback (most recent call last):
  File "Q:\odoo-13.0\odoo\tools\cache.py", line 85, in lookup
    r = d[key]
  File "Q:\odoo-13.0\odoo\tools\func.py", line 69, in wrapper
    return func(self, *args, **kwargs)
  File "Q:\odoo-13.0\odoo\tools\lru.py", line 44, in __getitem__
    a = self.d[obj].me
KeyError: ('ir.qweb', <function IrQWeb._get_asset_nodes at 0x0586C4F8>, 'web.assets_common_minimal_js', 'vi_VN', False, True, '', False, True, False, (1,))

During handling of the above exception, another exception occurred:

...

Could you guys please help me. Thanks in advance.


问:
Looping through array and removing items, without breaking for loop
I have the following for loop, and when I use splice() to remove an item, I then get that 'seconds' is undefined.  I could check if it's undefined, but I feel there's probably a more elegant way to do this.  The desire is to simply delete an item and keep on going.

```<code>for (i = 0, len = Auction.auctions.length; i < len; i++) {
    auction = Auction.auctions[i];
    Auction.auctions[i]['seconds'] --;
    if (auction.seconds < 0) {
        Auction.auctions.splice(i, 1);
    }
}
</code>```

答:
Give this a try

RemoveItems.forEach((i, j) => {
    OriginalItems.splice((i - j), 1);
});
```

Body:
I have the following for loop, and when I use splice() to remove an item, I then get that 'seconds' is undefined.  I could check if it's undefined, but I feel there's probably a more elegant way to do this.  The desire is to simply delete an item and keep on going.

for (i = 0, len = Auction.auctions.length; i < len; i++) {
    auction = Auction.auctions[i];
    Auction.auctions[i]['seconds'] --;
    if (auction.seconds < 0) {
        Auction.auctions.splice(i, 1);
    }
}


问:
WebRTC: onicecandidate function not been called, hence remote video is not showing
I am trying to create web RTC peer connection on react native. I am using the react-native-webrtc module. When using two emulators and passing the same room id the video connection is not been created. While debugging I found the onIceCandidate funciton is not been called. I am using socket.io to create the room. Please help me with this.

Git: https://github.com/developerajendra/react-native-webrtc-demo

```<code>import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Button, StyleSheet, Text} from 'react-native';
import {RTCPeerConnection, RTCView, mediaDevices} from 'react-native-webrtc';
import io from "socket.io-client";

export default function WEBRtc({roomNumber}) {
  const [localStream, setLocalStream] = useState();
  const [remoteStream, setRemoteStream] = useState();

  let isCaller, localST, peerConnection;
  const socket = io("http://192.168.0.102:3000", {transports: ['websocket']});

  const constraints = {
    audio: true,
    video:false
  };

/**
 * Getting ready for local stream
 */
  const startLocalStream = () => {
      socket.emit('joinTheRoom', roomNumber);
  };

  socket.on('roomCreated', room=>{
    console.log('room created');

    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        localST = stream;
        isCaller = true;
      })
  });

  socket.on('roomJoined', room=>{
    console.log('room joined');
    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        socket.emit('ready', roomNumber)
      });
  });

  const configuration = {iceServers: [
    {'urls':'stun:stun.services.mozilla.com'},
    {'urls':'stun:stun.l.google.com:19302'}
  ]};

  // const localPC = new RTCPeerConnection(configuration);
  // const remotePC = new RTCPeerConnection(configuration);

  // const peerConnection = new RTCPeerConnection(configuration);

    socket.on('ready', room=>{
      if(isCaller){
        console.log('ready');
        peerConnection = new RTCPeerConnection(configuration);
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;
        peerConnection.createOffer()
        .then(offer=>{
          return peerConnection.setLocalDescription(offer)
          .then(()=>{
            console.log('emit offer');
              socket.emit('offer',{
                type:'offer',
                sdp:offer,
                room: roomNumber
              });
            })
          })
      }
    });

    socket.on("offer",e=>{

      if(!isCaller){
        peerConnection = new RTCPeerConnection(configuration);
        console.log('offer');
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;

        console.log('about to create answer', e);

        //accept offer from here(ready)
        peerConnection.setRemoteDescription(e)
        .then(()=>{
          return peerConnection.createAnswer()
          .then(answer=>{
            return peerConnection.setLocalDescription(answer)
            .then(()=>{
              console.log('emit answer');
                socket.emit('answer',{
                  type:'answer',
                  sdp: answer,
                  room: roomNumber
              });
            })
          })
        });
      }

    });

    function onAddStream(e){
      console.log('remote stream', e);
      if (e.stream && remoteStream !== e.stream) {
        console.log('remote stream', e.stream);

        setRemoteStream(e.stream);
      }
  };

    function onIceCandidate(event){
      console.log('ice candidate');

      if(event.candidate){
          console.log('sending ice candidate', event.candidate);

          socket.emit('candidate',{
              type: 'candidate',
              label: event.candidate.sdpMLineIndex,
              id: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              room: roomNumber
          });
      }
  }

    socket.on('candidate', e=>{
      console.log('candidate', isCaller);
      peerConnection.addIceCandidate(e);
      peerConnection.addStream(localStream);
    });

    socket.on('answer', e=>{
      console.log('answer');
      peerConnection.setRemoteDescription(e);
    });

  return (
    <SafeAreaView style={styles.container}>
    <View style={styles.streamContainer}>
      <View style={styles.streamWrapper}>
          <View style={styles.localStream}>
            {localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
            {!localStream && <Button title="Tap to start" onPress={startLocalStream} />}
          </View>
          <View style={styles.rtcview}>
            {remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
          </View>
        </View>
        {/* {!!remoteStream ? <Button style={styles.toggleButtons} title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} /> : localStream && <Button title="Click to start call" onPress={startCall}  />} */}
    </View>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#313131',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: '100%',
    width:'100%'
  },
  streamContainer:{
    backgroundColor: 'grey',
    // justifyContent: 'space-around',
    alignItems: 'center',
    height: '50%',
    width: '100%',
    flexDirection:'column'
  },
  streamWrapper:{
    backgroundColor: 'grey',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: '100%',
    width: '100%',
    flexDirection:'row'
  },
  roomTitle:{
    fontSize:20,
    paddingTop:20
  },
  rtcview: {
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,

  },
  rtc: {
    width: '100%',
    height: '100%',
  },
  localStream:{
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,
    display:'flex',
    alignItems:'center',
    flexDirection:'row',
    justifyContent:'space-around',

  }
});
</code>```

答:
Your code has a lot of fundamental issues and I am sure that it isn't just ice candidate issue. For instance, you are creating a new socket every time the Components rerenders(since you're using a ). I'd recommend you using a class Component instead and handling events properly. Also, you're calling addStream every time you get a new ice candidate. It should be added only once(i.e preferably before you create an offer or answer). I think you should check WebRTC basics. Please try the below link.

https://webrtc.github.io/samples/src/content/peerconnection/pc1/

Body:
I am trying to create web RTC peer connection on react native. I am using the react-native-webrtc module. When using two emulators and passing the same room id the video connection is not been created. While debugging I found the onIceCandidate funciton is not been called. I am using socket.io to create the room. Please help me with this.

Git: https://github.com/developerajendra/react-native-webrtc-demo

import React, {useState, useEffect} from 'react';
import {View, SafeAreaView, Button, StyleSheet, Text} from 'react-native';
import {RTCPeerConnection, RTCView, mediaDevices} from 'react-native-webrtc';
import io from "socket.io-client";

export default function WEBRtc({roomNumber}) {
  const [localStream, setLocalStream] = useState();
  const [remoteStream, setRemoteStream] = useState();

  let isCaller, localST, peerConnection;
  const socket = io("http://192.168.0.102:3000", {transports: ['websocket']});

  const constraints = {
    audio: true,
    video:false
  };

/**
 * Getting ready for local stream
 */
  const startLocalStream = () => {
      socket.emit('joinTheRoom', roomNumber);
  };

  socket.on('roomCreated', room=>{
    console.log('room created');

    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        localST = stream;
        isCaller = true;
      })
  });

  socket.on('roomJoined', room=>{
    console.log('room joined');
    mediaDevices.getUserMedia(constraints)
      .then(stream=>{
        setLocalStream(stream);
        socket.emit('ready', roomNumber)
      });
  });

  const configuration = {iceServers: [
    {'urls':'stun:stun.services.mozilla.com'},
    {'urls':'stun:stun.l.google.com:19302'}
  ]};

  // const localPC = new RTCPeerConnection(configuration);
  // const remotePC = new RTCPeerConnection(configuration);

  // const peerConnection = new RTCPeerConnection(configuration);

    socket.on('ready', room=>{
      if(isCaller){
        console.log('ready');
        peerConnection = new RTCPeerConnection(configuration);
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;
        peerConnection.createOffer()
        .then(offer=>{
          return peerConnection.setLocalDescription(offer)
          .then(()=>{
            console.log('emit offer');
              socket.emit('offer',{
                type:'offer',
                sdp:offer,
                room: roomNumber
              });
            })
          })
      }
    });

    socket.on("offer",e=>{

      if(!isCaller){
        peerConnection = new RTCPeerConnection(configuration);
        console.log('offer');
        peerConnection.onicecandidate = onIceCandidate;
        peerConnection.onaddstream = onAddStream;

        console.log('about to create answer', e);

        //accept offer from here(ready)
        peerConnection.setRemoteDescription(e)
        .then(()=>{
          return peerConnection.createAnswer()
          .then(answer=>{
            return peerConnection.setLocalDescription(answer)
            .then(()=>{
              console.log('emit answer');
                socket.emit('answer',{
                  type:'answer',
                  sdp: answer,
                  room: roomNumber
              });
            })
          })
        });
      }

    });

    function onAddStream(e){
      console.log('remote stream', e);
      if (e.stream && remoteStream !== e.stream) {
        console.log('remote stream', e.stream);

        setRemoteStream(e.stream);
      }
  };

    function onIceCandidate(event){
      console.log('ice candidate');

      if(event.candidate){
          console.log('sending ice candidate', event.candidate);

          socket.emit('candidate',{
              type: 'candidate',
              label: event.candidate.sdpMLineIndex,
              id: event.candidate.sdpMid,
              candidate: event.candidate.candidate,
              room: roomNumber
          });
      }
  }

    socket.on('candidate', e=>{
      console.log('candidate', isCaller);
      peerConnection.addIceCandidate(e);
      peerConnection.addStream(localStream);
    });

    socket.on('answer', e=>{
      console.log('answer');
      peerConnection.setRemoteDescription(e);
    });

  return (
    <SafeAreaView style={styles.container}>
    <View style={styles.streamContainer}>
      <View style={styles.streamWrapper}>
          <View style={styles.localStream}>
            {localStream && <RTCView style={styles.rtc} streamURL={localStream.toURL()} />}
            {!localStream && <Button title="Tap to start" onPress={startLocalStream} />}
          </View>
          <View style={styles.rtcview}>
            {remoteStream && <RTCView style={styles.rtc} streamURL={remoteStream.toURL()} />}
          </View>
        </View>
        {/* {!!remoteStream ? <Button style={styles.toggleButtons} title="Click to stop call" onPress={closeStreams} disabled={!remoteStream} /> : localStream && <Button title="Click to start call" onPress={startCall}  />} */}
    </View>
</SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    backgroundColor: '#313131',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: '100%',
    width:'100%'
  },
  streamContainer:{
    backgroundColor: 'grey',
    // justifyContent: 'space-around',
    alignItems: 'center',
    height: '50%',
    width: '100%',
    flexDirection:'column'
  },
  streamWrapper:{
    backgroundColor: 'grey',
    justifyContent: 'space-around',
    alignItems: 'center',
    height: '100%',
    width: '100%',
    flexDirection:'row'
  },
  roomTitle:{
    fontSize:20,
    paddingTop:20
  },
  rtcview: {
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,

  },
  rtc: {
    width: '100%',
    height: '100%',
  },
  localStream:{
    width: '45%',
    height: '60%',
    borderColor:'#ccc',
    borderWidth:3,
    display:'flex',
    alignItems:'center',
    flexDirection:'row',
    justifyContent:'space-around',

  }
});


问:
Homework-C Programming- Recursive Program
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

```<code>f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise
</code>```

My program:

```<code>#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}
</code>```

答:
You have define factorial  function within main which is not possible.Separate its definition from main() and call it from main().

Hope this works.First correct this then only something can be done.

Body:
Hey guys! I was assigned this program which was pretty simple and didn't take long to code, yet I can't get it to run. Nothing prints and I think it's because it goes into an endless loop. Just looking for a fix on this.

Assignment:

Write and test a recursive function
  that returns the value of the
  following recursive definition:

f(x) = 0        if x <= 0
f(x- 1) + 2       otherwise

My program:

#include <stdio.h>
int main(void)
{
    int n, x;

    int factorial(int n) {

        if (x <= 0) {
            printf("x equals: ");
            return 1;
        } else {
            return n * factorial(n - 1); //error here
        }
        f(x) = f(x - 1) + 2;
    }
    return 0;
}


问:
Android activity crushes when the finish() is called after custom dialog dismiss()
With Kotlin, I'm using a custom dialog class. The activity need to be closed to return the previous activity with calling finish() of the activity on the onClick() of the dialog.

The simplified custom dialog

class TestDialog (context: Context) : Dialog(context),
    View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        setContentView(R.layout.dialog_result_screen)

        var yesButton=  findViewById(R.id.buttonControl);

        yesButton.setOnClickListener(this);
    }

    override fun onClick(v: View) {
        dismiss()
        (context as AppCompatActivity).finish()
    }
}
```

<p>The activity call this dialog as</p>

<pre class="lang-kotlin prettyprint-override"><code>
 val testDialog = TestDialog(this@TheDialogDisplayerActivity)
 testDialog.show()
 //used to dislay in full size of the secreen.
 val window: Window? = testDialog.window
 window?.setLayout(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT)
</code>```

The activity is extending the AppCompatActivity

When the finish() is called, the following error is occurred that I've couldn't find a solution.

```<code>java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to androidx.appcompat.app.AppCompatActivity
        at com.xyz.widget.TestResultDialog.onClick(TestResultDialog.kt:67)
</code>```

I've tried casting into activity class, too. This didn't work, either.

I've looked at these Q/As 1, 2, and some other questions, too, but failed to resolve.

How can I solve this issue?

答:
if you look in the parent class Dialog then the context becomes : mContext = new ContextThemeWrapper(context, themeResId); - which is exactly the error it is giving you when you try and cast it back to an Activity later.

You should do :

```<code>class TestDialog (private val activity: Activity) : Dialog(activity),
    View.OnClickListener {

  ...

  override fun onClick(v: View) {
        dismiss()
        activity.finish()
    }
}
</code>```

Body:
With Kotlin, I'm using a custom dialog class. The activity need to be closed to return the previous activity with calling finish() of the activity on the onClick() of the dialog.

The simplified custom dialog

class TestDialog (context: Context) : Dialog(context),
    View.OnClickListener {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        setContentView(R.layout.dialog_result_screen)

        var yesButton=  findViewById(R.id.buttonControl);

        yesButton.setOnClickListener(this);
    }

    override fun onClick(v: View) {
        dismiss()
        (context as AppCompatActivity).finish()
    }
}

The activity call this dialog as

 val testDialog = TestDialog(this@TheDialogDisplayerActivity)
 testDialog.show()
 //used to dislay in full size of the secreen.
 val window: Window? = testDialog.window
 window?.setLayout(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT)

The activity is extending the AppCompatActivity

When the finish() is called, the following error is occurred that I've couldn't find a solution.

java.lang.ClassCastException: android.view.ContextThemeWrapper cannot be cast to androidx.appcompat.app.AppCompatActivity
        at com.xyz.widget.TestResultDialog.onClick(TestResultDialog.kt:67)

I've tried casting into activity class, too. This didn't work, either.

I've looked at these Q/As 1, 2, and some other questions, too, but failed to resolve.

How can I solve this issue?

Body:
if you look in the parent class Dialog then the context becomes : mContext = new ContextThemeWrapper(context, themeResId); - which is exactly the error it is giving you when you try and cast it back to an Activity later.

You should do :

class TestDialog (private val activity: Activity) : Dialog(activity),
    View.OnClickListener {

  ...

  override fun onClick(v: View) {
        dismiss()
        activity.finish()
    }
}


问:
Autoencoders to crypt any type of data and Dimensionality reduction method through autoencoders
We need to implement a new approach  using a generative deep learning model based on autoencoders to crypt any type of data And the idea is to use autoencoders to reduce dimensions of data so is it possible and how??? </p>

答:
Is it possible? Yes! Autoencoders can be a solution for representing one information into another representation.

Autoencoders are a unsupervised learning technique where the goal is to make the input and output have the same value. So what is the use of autoencoders? They have hidden layers, usually with a smaller number of dimensions and the data is cloudy during this phase. You can still reconstruct the original data using the second part of the ANN, the decoder.

The ideia is:
original data > input layer > hidden layer (different number of nodes) > output layer > original data

The input and hidden layer: encoder
The hidden layer and output layer: decoder

Here you can find more information:
https://towardsdatascience.com/applied-deep-learning-part-3-autoencoders-1c083af4d798

One way would be to use a big hidden layer, higher than the data dimension in order to create an "encrypted" version, but I really don't see the point if you can use classical cryptography.


问:
Programatically pause timeline mission after DJIGimbalAttitudeAction
I have created a timeline mission to run a set of actions so the drone flies in a straight line capturing photos at 2 second intervals while the camera points straight down. I want the mission to pause just after the gimbal action completes. Here are the scheduled actions:

DJITakeOffAction

DJIGoToAction (coordinate with altitude)

DJIGimbalAttitudeAction (pitch -90)

DJIShootPhotoAction
(initWithPhotoCount 20, interval 2 seconds, wait NO)

DJIGoToAction
(coordinate with altitude)

The mission runs fine but I want to pause the timeline programatically after a DJIGimbalAttitudeAction completes so I can adjust the camera settings before the last two actions are run.

Is this possible? I tried to execute this if the indexOfScheduledElement matched the index of the DJIGimbalAttitudeAction timeline element in the addListener:(id)listener toTimelineProgressWithBlock of DJIMissionControl but I got a DJISDKMissionErrorDomain error 10007

On playing around with this, pausing programmatically seems to work fine if the timeline is in the middle of something like a DJIGoToAction but anything else seems to cause an error. Is there a better way to execute pauseTimeline cleanly?

答:
After a lot of testing I found that if I trigger pauseTimeline when the currently running timeline element is at the DJIMissionControlTimelineEventStarted event in the timeline listener it will pause just fine as long as the action/element running is NOT a DJIShootPhotoAction - any pause on a DJIShootPhotoAction results in a camera busy error.

If the same actions (e.g. DJIGoToAction, DJIAircraftYawAction, DJIGimbalAttitudeAction) are at the DJIMissionControlTimelineEventProgressed stage they fails with DJISDKMissionErrorDomain error 10007

```<code>[DJISDKManager.missionControl addListener:self toTimelineProgressWithBlock:^(DJIMissionControlTimelineEvent event, id<DJIMissionControlTimelineElement>  _Nullable element, NSError * _Nullable error, id  _Nullable info) {
    if (event == DJIMissionControlTimelineEventStarted) {
      [DJISDKManager.missionControl pauseTimeline];
    }
  }];
</code>```

Body:
After a lot of testing I found that if I trigger pauseTimeline when the currently running timeline element is at the DJIMissionControlTimelineEventStarted event in the timeline listener it will pause just fine as long as the action/element running is NOT a DJIShootPhotoAction - any pause on a DJIShootPhotoAction results in a camera busy error.

If the same actions (e.g. DJIGoToAction, DJIAircraftYawAction, DJIGimbalAttitudeAction) are at the DJIMissionControlTimelineEventProgressed stage they fails with DJISDKMissionErrorDomain error 10007

[DJISDKManager.missionControl addListener:self toTimelineProgressWithBlock:^(DJIMissionControlTimelineEvent event, id<DJIMissionControlTimelineElement>  _Nullable element, NSError * _Nullable error, id  _Nullable info) {
    if (event == DJIMissionControlTimelineEventStarted) {
      [DJISDKManager.missionControl pauseTimeline];
    }
  }];


问:
CSV Filtering a column with mixed data types
I have a CSV with many columns and rows.  Column 4 has some strings and some not.  When I attempt to filter out duplicates it removes ones I want to keep.

When I run:

```<code>awk -F ',' '!seen[$4]++' oldfile.csv > newfile.csv
</code>```

on

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO
</code>```

it returns what I want:

```<code>71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
</code>```

But, when I run that line of code on

```<code>71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
</code>```

it deletes all those entries.

What to do? Thanks

FOLLOW UP

Using perl seems to work, but gives me a small error.  Is this an issue?

```$ perl -w -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < combined4.csv > combined6.csv
Name "main::seen" used only once: possible typo at -e line 1.```

答:
If your CSV data is non-trivial, with things like commas inside quoted fields, a tool that's aware of the format is a better option than trying to use awk or the like on it.

Example perl one-liner using the Text::CSV_XS module (Install via your OS package manager or favorite CPAN client):

```<code>$ perl -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < input.csv
71508050,"HUNT,  RICHARD F"," ","1009 # B FATHOM DR"
</code>```

Body:
I have a CSV with many columns and rows.  Column 4 has some strings and some not.  When I attempt to filter out duplicates it removes ones I want to keep.

When I run:

awk -F ',' '!seen[$4]++' oldfile.csv > newfile.csv

on

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO
71523190,PRASAD  SHAKUNPALA, ,#3 ALEX BOYD LINK HILLSBORO
71523200,PRASAD  BOBBY UMENDRA, ,#3 ALEX BOYD LINK HILLSBORO

it returns what I want:

71523180,PRASAD  JAMES ANAND, ,#3 ALEX BOYD LINK HILLSBORO

But, when I run that line of code on

71508050,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71508060,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71561950,"HUNT,  RICHARD F", ,1009 # B FATHOM DR
71562840,"HUNT,  RICHARD F", ,1009 # B FATHOM DR

it deletes all those entries.

What to do? Thanks

FOLLOW UP

Using perl seems to work, but gives me a small error.  Is this an issue?

$ perl -w -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < combined4.csv > combined6.csv
Name "main::seen" used only once: possible typo at -e line 1.

Body:
If your CSV data is non-trivial, with things like commas inside quoted fields, a tool that's aware of the format is a better option than trying to use awk or the like on it.

Example perl one-liner using the Text::CSV_XS module (Install via your OS package manager or favorite CPAN client):

$ perl -MText::CSV_XS=csv -e 'csv(in => \*STDIN, filter => { 4 => sub { ! $seen{$_}++ }})' < input.csv
71508050,"HUNT,  RICHARD F"," ","1009 # B FATHOM DR"


答:
You could use the load event</p>

```<code>$('body').load(function() {
    window.myUtil.utility();
});
</code>```

Title: Execute javascript when another function exists

Body:
I'm writing two scripts in an web environment where I don't have control over the order in which they are loaded.  Let's say the two scripts are called MyUtil and DoSomething.

MyUtil contains utilities that I will bind to the window object using window.myUtil = myUtil.  I'm then going to call methods of myUtil from within DoSomething.

If MyUtil is loaded first, everything will work. If it's loaded second, window.myUtil will be undefined.

How can I modify the code in DoSomething (and/or MyUtil) to wait until window.myUtil exists before DoSomething executes its code?

NB: I'm using jQuery 1.2.3.

Body:
You could use the load event

$('body').load(function() {
    window.myUtil.utility();
});


问:
How to import binary files into DolphinDB?
I have a binary file and I want to import it into DolphinDB. But the function readRecord! does not support importing a table with a field in type of STRING:

```<code>f.readRecord!(tb)

ERROR MESSAGE:
Read only object or object without ownership can't be applied to mutable function readRecord!
</code>```

I wonder if DolphinDB provides a function which supports importing a binary file containing a STRING type field?

答: DolphinDB does provide a function loadRecord to import a table from a binary file containing string fields. The string field must have fixed length. If the actual length of a string is shorter than the fixed length, it must be padded with ascii zero.

Body:
I have a binary file and I want to import it into DolphinDB. But the function readRecord! does not support importing a table with a field in type of STRING:

f.readRecord!(tb)

ERROR MESSAGE:
Read only object or object without ownership can't be applied to mutable function readRecord!

I wonder if DolphinDB provides a function which supports importing a binary file containing a STRING type field?