问:
Using stateful helper classes in stateful stream operator functions in Flink
Can we have helper classes that reference Flink state used inside a Flink operator function.  The documentation examples all show the objects from the Flink state api referenced as fields directly by the opereator.  But I was wondering if fault tolerance is affected if I move the state into another class, for example:

```<code>///Operator function with reference to a stateful helper class
public class SomeStatefulFunction extends RichMapFunction<SomeInput, SomeOutput> {

    private SomeStatefulHelper helperInstance1;
    private SomeStatefulHelper helperInstance2;

    @Override
    public SomeOutput map(SomeInput someInput) throws Exception {
        return combineOutput(helperInstance1.helperMethod(someInput), helperInstance2.helperMethod(someInput));
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        this.helperInstance1 = createHelper("helperConfig1", "someMapState1");
        this.helperInstance2 = createHelper("helperConfig2", "someMapState2");

    }

    private SomeStatefulHelper createHelper(String helperConfig, String stateName) {
        MapStateDescriptor<Integer, Integer> descriptor =
                new MapStateDescriptor<>(stateName, Integer.class, Integer.class);
        MapState<Integer, Integer> mapState = getRuntimeContext().getMapState(descriptor);
        return new SomeStatefulHelper(helperConfig, mapState);
    }

    private SomeOutput combineOutput(SomeOutput output1, SomeOutput output2) {
        //Some way to combine output
    }
}

///Stateful helper class
public class SomeStatefulHelper {
    private MapState<Integer, Integer> state;
    private String helperConfig;

    public SomeStatefulHelper(String helperConfig, MapState<Integer, Integer> state) {
        this.state = state;
        this.helperConfig = helperConfig;
    }

    public SomeOutput helperMethod(SomeInput input) {
        //return something based on input, state, and helperConfig
    }
}
</code>```

I have a job that uses this 'pattern' and it works in terms of processing, but I am not sure whether the state would be recovered in the event of failure?

答: It shouldn't affect the state recovery as it does not matter if the state is created in a separate class or directly in the open method. The operator still will invoke the same methods on state recovery. So, as long as You create the classes inside the open method You should be fine.

Body:
Can we have helper classes that reference Flink state used inside a Flink operator function.  The documentation examples all show the objects from the Flink state api referenced as fields directly by the opereator.  But I was wondering if fault tolerance is affected if I move the state into another class, for example:

///Operator function with reference to a stateful helper class
public class SomeStatefulFunction extends RichMapFunction<SomeInput, SomeOutput> {

    private SomeStatefulHelper helperInstance1;
    private SomeStatefulHelper helperInstance2;

    @Override
    public SomeOutput map(SomeInput someInput) throws Exception {
        return combineOutput(helperInstance1.helperMethod(someInput), helperInstance2.helperMethod(someInput));
    }

    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);

        this.helperInstance1 = createHelper("helperConfig1", "someMapState1");
        this.helperInstance2 = createHelper("helperConfig2", "someMapState2");

    }

    private SomeStatefulHelper createHelper(String helperConfig, String stateName) {
        MapStateDescriptor<Integer, Integer> descriptor =
                new MapStateDescriptor<>(stateName, Integer.class, Integer.class);
        MapState<Integer, Integer> mapState = getRuntimeContext().getMapState(descriptor);
        return new SomeStatefulHelper(helperConfig, mapState);
    }

    private SomeOutput combineOutput(SomeOutput output1, SomeOutput output2) {
        //Some way to combine output
    }
}

///Stateful helper class
public class SomeStatefulHelper {
    private MapState<Integer, Integer> state;
    private String helperConfig;

    public SomeStatefulHelper(String helperConfig, MapState<Integer, Integer> state) {
        this.state = state;
        this.helperConfig = helperConfig;
    }

    public SomeOutput helperMethod(SomeInput input) {
        //return something based on input, state, and helperConfig
    }
}

I have a job that uses this 'pattern' and it works in terms of processing, but I am not sure whether the state would be recovered in the event of failure?


来源: stackexchange

问:
Cache selected elements of an std::array and keep it consistent automatically in c++
I have many instances of classes in an std::array. Based on a criteria I would like to select a few and store pointers to them in a separate array - a cache basically. I plan to use that 'cache' array to quickly iterate through the selection several times (maybe even in a separate thread using lock guards).

I would like to be able to remove and destruct instances from the original array and keep the cache array consistent.

Is there an elegant and automatic way to do this?

答: Make the original array contain pointers to the objects.  Then, re-arranging that array will not change the actual objects.</p>

ContentLicense: CC BY-SA 4.0


问:
How to use helm chart test to do integration tests?
I am trying to use it to run some integration tests, so to verify the service code I am deploying is actually doing the right thing.

Basically how I setup is (as described here: https://docs.helm.sh/developing_charts/#chart-tests) creating this templates/tests/integration-test.yaml chart test file, and inside it specify to run a container, which basically is a customized maven image with test code added in and the test container is simply started by command “mvn test”, which does some simple curl check on the kube service this whole helm release deploys.

In this way, the helm test does work.

However, the issue is, during the helm test is running, the new version of the service code is actually already online and being exposed to the outside world/users. I can of course immediately do a roll back if the helm test fails, but this will not stop me hosting the problem-version of the service code for a while to the outside world.

Is there a way, where one can run a service/integration test on a pod, after the pod is started but before it is exposed to the Kubernetes service?

答: Use the readiness and liveness probes in the pod spec to ensure that the deployment won't even roll out if there are probe failures.</p>


问:
Get instance of subtype of a model with Eloquent
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

```<code>class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }
</code>```

Yet, being able to fetch an animal like this :

```<code>$animal = Animal::find($id);
</code>```

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

答:
I think I know what you're looking for. Consider this elegant solution which uses Laravel query scopes, see https://laravel.com/docs/6.x/eloquent#query-scopes for additional information:

Create a parent class that holds shared logic:

class Animal extends \Illuminate\Database\Eloquent\Model
{
    const TYPE_DOG = 'dog';
    const TYPE_CAT = 'cat';
}
```

<h3>Create a child (or multiple) with a global query scope and a <code>saving</code> event handler:</h3>

<pre class="lang-php prettyprint-override"><code>class Dog extends Animal
{
    public static function boot()
    {
        parent::boot();

        static::addGlobalScope('type', function(\Illuminate\Database\Eloquent\Builder $builder) {
            $builder->where('type', self::TYPE_DOG);
        });

        // Add a listener for when saving models of this type, so that the `type`
        // is always set correctly.
        static::saving(function(Dog $model) {
            $model->type = self::TYPE_DOG;
        });
    }
}
</code>```

(same applies to another class Cat, just replace the constant)

The global query scope acts as a default query modification, such that the Dog class will always look for records with type='dog'.

Say we have 3 records:

```<code>- id:1 => Cat
- id:2 => Dog
- id:3 => Mouse
</code>```

Now calling Dog::find(1) would result in null, because the default query scope will not find the id:1 which is a Cat. Calling Animal::find(1) and Cat::find(1) will both work, although only the last one gives you an actual Cat object.

The nice thing of this setup is that you can use the classes above to create relations like:

class Owner
{
    public function dogs()
    {
        return $this->hasMany(Dog::class);
    }
}
```

And this relation will automatically only give you all the animals with the type='dog' (in the form of Dog classes). The query scope is automatically applied.

In addition, calling Dog::create($properties) will automatically set the type to 'dog' due to the saving event hook (see https://laravel.com/docs/6.x/eloquent#events).

Note that calling Animal::create($properties) does not have a default type so here you need to set that manually (which is to be expected).

Body:
I have an Animal model, based on the animal table.

This table contains a type field, that can contain values such as cat or dog.

I would like to be able to create objects such as :

class Animal extends Model { }
class Dog extends Animal { }
class Cat extends Animal { }

Yet, being able to fetch an animal like this :

$animal = Animal::find($id);

But where $animal would be an instance of Dog or Cat depending on the type field, that I can check using instance of or that will work with type hinted methods. The reason is that 90% of the code is shared, but one can bark, and the other can meow.

I know that I can do Dog::find($id), but it's not what I want : I can determine the type of the object only once it was fetched. I could also fetch the Animal, and then run find() on the right object, but this is doing two database calls, which I obviously don't want.

I tried to look for a way to "manually" instantiate an Eloquent model like Dog from Animal, but I could not find any method corresponding. Any idea or method I missed please ?

Body:
I think I know what you're looking for. Consider this elegant solution which uses Laravel query scopes, see https://laravel.com/docs/6.x/eloquent#query-scopes for additional information:

Create a parent class that holds shared logic:

class Animal extends \Illuminate\Database\Eloquent\Model
{
    const TYPE_DOG = 'dog';
    const TYPE_CAT = 'cat';
}

Create a child (or multiple) with a global query scope and a saving event handler:

class Dog extends Animal
{
    public static function boot()
    {
        parent::boot();

        static::addGlobalScope('type', function(\Illuminate\Database\Eloquent\Builder $builder) {
            $builder->where('type', self::TYPE_DOG);
        });

        // Add a listener for when saving models of this type, so that the `type`
        // is always set correctly.
        static::saving(function(Dog $model) {
            $model->type = self::TYPE_DOG;
        });
    }
}

(same applies to another class Cat, just replace the constant)

The global query scope acts as a default query modification, such that the Dog class will always look for records with type='dog'.

Say we have 3 records:

- id:1 => Cat
- id:2 => Dog
- id:3 => Mouse

Now calling Dog::find(1) would result in null, because the default query scope will not find the id:1 which is a Cat. Calling Animal::find(1) and Cat::find(1) will both work, although only the last one gives you an actual Cat object.

The nice thing of this setup is that you can use the classes above to create relations like:

class Owner
{
    public function dogs()
    {
        return $this->hasMany(Dog::class);
    }
}

And this relation will automatically only give you all the animals with the type='dog' (in the form of Dog classes). The query scope is automatically applied.

In addition, calling Dog::create($properties) will automatically set the type to 'dog' due to the saving event hook (see https://laravel.com/docs/6.x/eloquent#events).

Note that calling Animal::create($properties) does not have a default type so here you need to set that manually (which is to be expected).


问:
Replace two input text values with values from each other on button click
I  have an html form with two input fields, in first one user puts name of first town, and in other second town, after form is submitted users gets directions how to go from first town to second town.

I want to enable user to click button "Change directions" and to automatically change first town name into second and second town name into first and vise versa. ( A to B, B to A)

I guess i'm supposed to use javascript, but I'm new at it and can't get a clue anywhere.

Can anyone help me please?

```<code>input type="text" size="25" id="fromAddress" name="from"
 value=""/>
  <input name="submit1" type="submit" value="Change directions" />
<input type="text" size="25" id="toAddress" name="to"
 value="" />
<input name="submit" type="submit" value="OK" />
</code>```

答:
You can create new button <button id="change">Change</button>

And then add onclick event to it.

```<code>document.getElementById('change').onclick = function() {
    var tmp = document.getElementById('fromAddress').value;
    document.getElementById('fromAddress').value = document.getElementById('toAddress').value;
    document.getElementById('toAddress').value = tmp;
};
</code>```

Take a look here: http://jsfiddle.net/xskKn/

ContentLicense: CC BY-SA 3.0

Body:
I  have an html form with two input fields, in first one user puts name of first town, and in other second town, after form is submitted users gets directions how to go from first town to second town.

I want to enable user to click button "Change directions" and to automatically change first town name into second and second town name into first and vise versa. ( A to B, B to A)

I guess i'm supposed to use javascript, but I'm new at it and can't get a clue anywhere.

Can anyone help me please?

input type="text" size="25" id="fromAddress" name="from"
 value=""/>
  <input name="submit1" type="submit" value="Change directions" />
<input type="text" size="25" id="toAddress" name="to"
 value="" />
<input name="submit" type="submit" value="OK" />

Body:
You can create new button <button id="change">Change</button>

And then add onclick event to it.

document.getElementById('change').onclick = function() {
    var tmp = document.getElementById('fromAddress').value;
    document.getElementById('fromAddress').value = document.getElementById('toAddress').value;
    document.getElementById('toAddress').value = tmp;
};

Take a look here: http://jsfiddle.net/xskKn/


问:
Python function overloading
I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way.

I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that creates a bullet travelling from point A to B with a given speed. I would write a function like this:

```<code>def add_bullet(sprite, start, headto, speed):
    # Code ...
</code>```

But I want to write other functions for creating bullets like:

```<code>def add_bullet(sprite, start, direction, speed):
def add_bullet(sprite, start, headto, spead, acceleration):
def add_bullet(sprite, script): # For bullets that are controlled by a script
def add_bullet(sprite, curve, speed): # for bullets with curved paths
# And so on ...
</code>```

And so on with many variations. Is there a better way to do it without using so many keyword arguments cause its getting kinda ugly fast. Renaming each function is pretty bad too because you get either add_bullet1, add_bullet2, or add_bullet_with_really_long_name.

To address some answers:

No I can't create a Bullet class hierarchy because thats too slow. The actual code for managing bullets is in C and my functions are wrappers around C API.

I know about the keyword arguments but checking for all sorts of combinations of parameters is getting annoying, but default arguments help allot like acceleration=0

答:
Python 3.8 added functools.singledispatchmethod

Transform a method into a single-dispatch generic function.

To define a generic method, decorate it with the @singledispatchmethod
  decorator. Note that the dispatch happens on the type of the first
  non-self or non-cls argument, create your function accordingly:

```<code>from functools import singledispatchmethod

class Negator:
    @singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(self, arg: int):
        return -arg

    @neg.register
    def _(self, arg: bool):
        return not arg

negator = Negator()
for v in [42, True, "Overloading"]:
    neg = negator.neg(v)
    print(f"{v=}, {neg=}")
</code>```

Output

```<code>v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
</code>```

@singledispatchmethod supports nesting with other decorators such as
  @classmethod. Note that to allow for dispatcher.register,
  singledispatchmethod must be the outer most decorator. Here is the
  Negator class with the neg methods being class bound:

```<code>from functools import singledispatchmethod

class Negator:
    @singledispatchmethod
    @staticmethod
    def neg(arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(arg: int) -> int:
        return -arg

    @neg.register
    def _(arg: bool) -> bool:
        return not arg

for v in [42, True, "Overloading"]:
    neg = Negator.neg(v)
    print(f"{v=}, {neg=}")
</code>```

Output:

```<code>v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a
</code>```

The same pattern can be used for other similar decorators:
  staticmethod, abstractmethod, and others.

Title: Python function overloading

Body:
I know that Python does not support method overloading, but I've run into a problem that I can't seem to solve in a nice Pythonic way.

I am making a game where a character needs to shoot a variety of bullets, but how do I write different functions for creating these bullets? For example suppose I have a function that creates a bullet travelling from point A to B with a given speed. I would write a function like this:

def add_bullet(sprite, start, headto, speed):
    # Code ...

But I want to write other functions for creating bullets like:

def add_bullet(sprite, start, direction, speed):
def add_bullet(sprite, start, headto, spead, acceleration):
def add_bullet(sprite, script): # For bullets that are controlled by a script
def add_bullet(sprite, curve, speed): # for bullets with curved paths
# And so on ...

And so on with many variations. Is there a better way to do it without using so many keyword arguments cause its getting kinda ugly fast. Renaming each function is pretty bad too because you get either add_bullet1, add_bullet2, or add_bullet_with_really_long_name.

To address some answers:

No I can't create a Bullet class hierarchy because thats too slow. The actual code for managing bullets is in C and my functions are wrappers around C API.

I know about the keyword arguments but checking for all sorts of combinations of parameters is getting annoying, but default arguments help allot like acceleration=0

Body:
Python 3.8 added functools.singledispatchmethod

Transform a method into a single-dispatch generic function.

To define a generic method, decorate it with the @singledispatchmethod
  decorator. Note that the dispatch happens on the type of the first
  non-self or non-cls argument, create your function accordingly:

from functools import singledispatchmethod

class Negator:
    @singledispatchmethod
    def neg(self, arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(self, arg: int):
        return -arg

    @neg.register
    def _(self, arg: bool):
        return not arg

negator = Negator()
for v in [42, True, "Overloading"]:
    neg = negator.neg(v)
    print(f"{v=}, {neg=}")

Output

v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a

@singledispatchmethod supports nesting with other decorators such as
  @classmethod. Note that to allow for dispatcher.register,
  singledispatchmethod must be the outer most decorator. Here is the
  Negator class with the neg methods being class bound:

from functools import singledispatchmethod

class Negator:
    @singledispatchmethod
    @staticmethod
    def neg(arg):
        raise NotImplementedError("Cannot negate a")

    @neg.register
    def _(arg: int) -> int:
        return -arg

    @neg.register
    def _(arg: bool) -> bool:
        return not arg

for v in [42, True, "Overloading"]:
    neg = Negator.neg(v)
    print(f"{v=}, {neg=}")

Output:

v=42, neg=-42
v=True, neg=False
NotImplementedError: Cannot negate a

The same pattern can be used for other similar decorators:
  staticmethod, abstractmethod, and others.


问:
How do you do a Bubble Sort for an Array in C++?
I am given a 4 numbers that I have to input them and use bubble sort to sort them from lowest to highest.
This is what I have currently now for the bubble sorting:

```<code>void bubble_sort()
{
    for (int i=0;i<4;i++)
    {
        if(num[i]>num[i+1])
        {
            float temp;
            temp=num[i+1];
            num[i]=num[i+1];
            num[i+1]=temp;
        }
    }
}
</code>```

When I output the the array with the inputs: 3.72, 3.92, 3.46, and 3.86
I get : 3.72, 3.46, 3.46, 0

答:
Some of the errors presented in the code are the following

Swapping the values in a wrong manner. ( as pointed out in the comments of the question)

Letting the value of j be 3 in which case it will pick up garbage value in index 4 when temp = num[j+1] is run.

Only having one for loop iterating through the loop only once. Kindly read up on the basics of working and Complexity of bubble sort and how it uses at least two loops from here

Now the correct answer will be of the form

```<code>    void bubble_sort(float num[]) {
    for (int i=0;i<4;i++) {
        for(int j=0;j<3;j++){
            if(num[j]>num[j+1])
            {
                float temp;
                temp=num[j+1];
                num[j+1]=num[j];
                num[j]=temp;
            }
        }
      }
    for(int i=0;i<4;i++)
        cout<<num[i];
    }
</code>```

Body:
I am given a 4 numbers that I have to input them and use bubble sort to sort them from lowest to highest.
This is what I have currently now for the bubble sorting:

void bubble_sort()
{
    for (int i=0;i<4;i++)
    {
        if(num[i]>num[i+1])
        {
            float temp;
            temp=num[i+1];
            num[i]=num[i+1];
            num[i+1]=temp;
        }
    }
}

When I output the the array with the inputs: 3.72, 3.92, 3.46, and 3.86
I get : 3.72, 3.46, 3.46, 0

Body:
Some of the errors presented in the code are the following

Swapping the values in a wrong manner. ( as pointed out in the comments of the question)

Letting the value of j be 3 in which case it will pick up garbage value in index 4 when temp = num[j+1] is run.

Only having one for loop iterating through the loop only once. Kindly read up on the basics of working and Complexity of bubble sort and how it uses at least two loops from here

Now the correct answer will be of the form

    void bubble_sort(float num[]) {
    for (int i=0;i<4;i++) {
        for(int j=0;j<3;j++){
            if(num[j]>num[j+1])
            {
                float temp;
                temp=num[j+1];
                num[j+1]=num[j];
                num[j]=temp;
            }
        }
      }
    for(int i=0;i<4;i++)
        cout<<num[i];
    }


问:
Problems with controlling the placement of Dockpanel control in wpf
I have a WPF application with tabs and browser navigation controls. I'd like the tabs to be on top of the navigation display but the navigation is only shown, not the tabs, as show here; only the navigation bar is being displayed:

This is the xaml code:

```<code><Grid>
    <TabControl Name="tabDynamic" ItemsSource="{Binding}" SelectionChanged="tabDynamic_SelectionChanged">
        <TabControl.Resources>
            <DataTemplate x:Key="TabHeader" DataType="TabItem">
                <DockPanel>
                    <DockPanel LastChildFill="True" DockPanel.Dock="Top">
                        <Button Name="btnDelete" DockPanel.Dock="Right" Margin="5,0,0,0" Padding="0" Click="btnDelete_Click" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Name}">
                        </Button>
                    </DockPanel>
                </DockPanel>
            </DataTemplate>
        </TabControl.Resources>
    </TabControl>
    <DockPanel>
        <DockPanel LastChildFill="True" DockPanel.Dock="Top">
            <Button Content="<Back" Name ="backree" Click="backree_Click"> </Button>
            <Button Content="Go" Name ="navixd" Click="navixd_Click"></Button>
            <Button Content="Forward>" Name ="forwardyikes" Click="forwardyikes_Click"></Button>
            <TextBox Name="addbox"></TextBox>
        </DockPanel>
        <cefsharp:ChromiumWebBrowser Address="StackOverflow.com" FrameLoadEnd="ChromiumWebBrowser_OnFrameLoadEnd" Name="Browser"></cefsharp:ChromiumWebBrowser>
    </DockPanel>

</Grid>
</code>```

How would I make the navigation bar be displayed below the tabs, or even better how would I display the tabs in the very top of the window like chrome tabs, (im not sure what this part is called).

答:
You didn't defined the Grid Rows and Columns, add this to the Grid Definition

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <TabControl Grid.Row="0"> [...] </TabControl>
    <DockPanel  Grid.Row="1"> [...] </DockPanel>

</Grid>
</code>```

This will force the controls to order into different rows.

This Height="auto" means that your row will shrink to the minimum height possible. Height="*" instead will use all the space left.

To be able to have the tabs at the top of the window (as in Chrome) you probably need more work, with the help of supplements packets or own implemented windows.

I hope I was helpful.

Body:
I have a WPF application with tabs and browser navigation controls. I'd like the tabs to be on top of the navigation display but the navigation is only shown, not the tabs, as show here; only the navigation bar is being displayed:

This is the xaml code:

<Grid>
    <TabControl Name="tabDynamic" ItemsSource="{Binding}" SelectionChanged="tabDynamic_SelectionChanged">
        <TabControl.Resources>
            <DataTemplate x:Key="TabHeader" DataType="TabItem">
                <DockPanel>
                    <DockPanel LastChildFill="True" DockPanel.Dock="Top">
                        <Button Name="btnDelete" DockPanel.Dock="Right" Margin="5,0,0,0" Padding="0" Click="btnDelete_Click" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType={x:Type TabItem}}, Path=Name}">
                        </Button>
                    </DockPanel>
                </DockPanel>
            </DataTemplate>
        </TabControl.Resources>
    </TabControl>
    <DockPanel>
        <DockPanel LastChildFill="True" DockPanel.Dock="Top">
            <Button Content="<Back" Name ="backree" Click="backree_Click"> </Button>
            <Button Content="Go" Name ="navixd" Click="navixd_Click"></Button>
            <Button Content="Forward>" Name ="forwardyikes" Click="forwardyikes_Click"></Button>
            <TextBox Name="addbox"></TextBox>
        </DockPanel>
        <cefsharp:ChromiumWebBrowser Address="StackOverflow.com" FrameLoadEnd="ChromiumWebBrowser_OnFrameLoadEnd" Name="Browser"></cefsharp:ChromiumWebBrowser>
    </DockPanel>

</Grid>

How would I make the navigation bar be displayed below the tabs, or even better how would I display the tabs in the very top of the window like chrome tabs, (im not sure what this part is called).

Body:
You didn't defined the Grid Rows and Columns, add this to the Grid Definition

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <TabControl Grid.Row="0"> [...] </TabControl>
    <DockPanel  Grid.Row="1"> [...] </DockPanel>

</Grid>

This will force the controls to order into different rows.

This Height="auto" means that your row will shrink to the minimum height possible. Height="*" instead will use all the space left.

To be able to have the tabs at the top of the window (as in Chrome) you probably need more work, with the help of supplements packets or own implemented windows.

I hope I was helpful.


问:
Ruby get GET request data
I'm making API endpoints and I'm having trouble getting the body of the request. Here is what I have:

In my routes I have set up an endpoint in my namespace:

```<code>namespace :api, :defaults => {:format => :json}  do
    resources :mainview do
        collection do
            get 'data'
        end
    end
</code>```

In my front end I call the /api/mainview/data endpoint and pass it in a date inside of a json:

```<code>axios.get('/api/mainview/data', {"start_date":"2020-01-01"})
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log("We are getting this error:")
      console.log(error)
    });
</code>```

And then, in my /api/mainview_controller.rb file, I got

```<code>module Api
    class MainviewController < AuthenticatedController
        def data
            puts "We are in the data function"
            #I want to print the body ({"start_date":"2020-01-01"}) of the request here
        end
    end
end
</code>```

So in this case, my API call seems to work as We are in the data function does get printed to the terminal. However, I don't know how to get the body or data from the request. If it's a post request I know I can use request.raw_post but I don't know what to use for GET requests. Most of the answers I found online are in PHP so any help would be great!

答:
You have to render a response through Rails and you have to actually build up the output in the response before Rails packages it up and sends it back.</p>

```<code>def data
  render json: {
      start_date: params[:start_date]
    }
end
</code>```

Title: Ruby get GET request data

Body:
I'm making API endpoints and I'm having trouble getting the body of the request. Here is what I have:

In my routes I have set up an endpoint in my namespace:

namespace :api, :defaults => {:format => :json}  do
    resources :mainview do
        collection do
            get 'data'
        end
    end

In my front end I call the /api/mainview/data endpoint and pass it in a date inside of a json:

axios.get('/api/mainview/data', {"start_date":"2020-01-01"})
    .then(response => {
      console.log(response)
    })
    .catch(error => {
      console.log("We are getting this error:")
      console.log(error)
    });

And then, in my /api/mainview_controller.rb file, I got

module Api
    class MainviewController < AuthenticatedController
        def data
            puts "We are in the data function"
            #I want to print the body ({"start_date":"2020-01-01"}) of the request here
        end
    end
end

So in this case, my API call seems to work as We are in the data function does get printed to the terminal. However, I don't know how to get the body or data from the request. If it's a post request I know I can use request.raw_post but I don't know what to use for GET requests. Most of the answers I found online are in PHP so any help would be great!

Body:
You have to render a response through Rails and you have to actually build up the output in the response before Rails packages it up and sends it back.

def data
  render json: {
      start_date: params[:start_date]
    }
end


问:
appconfig file for connectionstring in class Library project?
I have a class library project that requires a connection string be set: </p>

```<code>        var connectionString = ConfigurationManager.ConnectionStrings["appDatabase"].ConnectionString;
</code>```

<p>If this was any other project then I would have just added an app.config to set this, but what is the code library equivalent? </p>

答:
Your class library must be being consumed by some host I.e. console app, web app, function app etc. All of those projects support app settings of some sort.

Without knowing the architecture of your solution it is very difficult to suggest the best route but generally your class library really should accept its inputs via its constructor either passed directly or managed via dependency injection.

Body:
I have a class library project that requires a connection string be set:

        var connectionString = ConfigurationManager.ConnectionStrings["appDatabase"].ConnectionString;

If this was any other project then I would have just added an app.config to set this, but what is the code library equivalent?


问:
"address of stack memory associated with local variable" error when running user-defined function in C
Recentely I've been taking the CS50 2020 course from Harvard University as an introduction to C programming. I'm not very experienced with the language or with coding as a whole, so I'm struggling a bit to figure out what is wrong with my code.

I wrote this little function which is suposed to take in a string and, by calling another function, encrypt the text using a Caesar cypher, then return it as a string. Problem is, I can't figure out how to return the character array as a string. I tried adding a NUL char at the end of the array after reading a bit about the problem, and it compiled alright, but when I ran the program I got the following error message:

```<code>error: address of stack memory associated with local variable 'result' returned [-Werror,-Wreturn-stack-address]
    return result;
           ^~~~~~
</code>```

My code:

```<code>string encypher(string text)
{
    int length = strlen(text);
    char result[length];
    for(int i = 0; i < length; i++)
    {
        int letter_c = test_char(text[i]);
        result[i] = (char)letter_c;
    }
    result[length + 1] = '\0';
    return result;
}
</code>```

答:
The problem here is that result, being an array, decays to a pointer to its first element when used in an expression, and that is what is being returned from the function.  And because the lifetime of the array ends when the function returns, that pointer now points to an invalid memory location, and attempting to use it invokes undefined behavior.

Instead of creating a local array, use the malloc function to dynamically allocate memory.  That memory is valid for the life of the program, or until the returned pointer is passed to free:

```<code>string result = malloc(length + 1);
</code>```

Also, note that you need to set aside one extra byte for the null byte that is used to terminate a string.

Body:
Recentely I've been taking the CS50 2020 course from Harvard University as an introduction to C programming. I'm not very experienced with the language or with coding as a whole, so I'm struggling a bit to figure out what is wrong with my code.

I wrote this little function which is suposed to take in a string and, by calling another function, encrypt the text using a Caesar cypher, then return it as a string. Problem is, I can't figure out how to return the character array as a string. I tried adding a NUL char at the end of the array after reading a bit about the problem, and it compiled alright, but when I ran the program I got the following error message:

error: address of stack memory associated with local variable 'result' returned [-Werror,-Wreturn-stack-address]
    return result;
           ^~~~~~

My code:

string encypher(string text)
{
    int length = strlen(text);
    char result[length];
    for(int i = 0; i < length; i++)
    {
        int letter_c = test_char(text[i]);
        result[i] = (char)letter_c;
    }
    result[length + 1] = '\0';
    return result;
}

Body:
The problem here is that result, being an array, decays to a pointer to its first element when used in an expression, and that is what is being returned from the function.  And because the lifetime of the array ends when the function returns, that pointer now points to an invalid memory location, and attempting to use it invokes undefined behavior.

Instead of creating a local array, use the malloc function to dynamically allocate memory.  That memory is valid for the life of the program, or until the returned pointer is passed to free:

string result = malloc(length + 1);

Also, note that you need to set aside one extra byte for the null byte that is used to terminate a string.


问:
Typescript - keyof values of array
I have a list

export const list = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];
```

<p>Now I want to create dynamically a union type which describes the following:</p>

<pre class="lang-js prettyprint-override"><code>type Title = 'parentTitle' | 'anotherTitle' | 'whatever';
</code>```

Is there a way to do this?

I tried to adapt the idea here: Keyof nested child objects
But I can't figuring it out

答:
You can make an interface for it and make an array type from it.</p>

```<code>interface Title {
    name: 'parentTitle' | 'anotherTitle' | 'whatever';
}

let list: Title[] = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];
</code>```

Title: Typescript - keyof values of array

Body:
I have a list

export const list = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];

Now I want to create dynamically a union type which describes the following:

type Title = 'parentTitle' | 'anotherTitle' | 'whatever';

Is there a way to do this?

I tried to adapt the idea here: Keyof nested child objects
But I can't figuring it out

Body:
You can make an interface for it and make an array type from it.

interface Title {
    name: 'parentTitle' | 'anotherTitle' | 'whatever';
}

let list: Title[] = [
  {
    name: 'parentTitle',
  },
  {
    name: 'anotherTitle',
  },
  {
    name: 'whatever',
  },
];


问:
Keycloak bulk user import
Does anyone have any thoughts on how one might import a very large number of users into Keycloak.

We are in the process of upgrading from 2.5.5 to 4.0.0 and have had to switch from MongoDB to MySQL. We have been able to export our user base but with 280k+ users to import back into Keycloak. The import process takes 25 mins to import one file of 500 users, which doesnt really seem practical as that would take us approximately 9/10 days to import the user base if we were working 24/7.

Any thoughts or ideas would be appreciated.

答:
I realize I'm a little late to the party here...

Keycloak 8 (and newer) has a mechanism for bulk importing users via a .json file: https://www.keycloak.org/docs/8.0/server_admin/index.html#_export_import

If you have some sort of mechanism for dumping your existing users to a .json file, it makes the import reasonably easy.

Title: Keycloak bulk user import


问:
Error invoking method, failed to launch jvm
I'm developing a desktop application using javafx v8.0.40. I have created an exe file with inno 5. When I run exe file in my computer, it is installed and run without any problem. On the other hand, when I try to install and run it on some other computer, at the end of installation, window dialog pops up: "Error invoking method", I click Ok. Another window pop up saying "Failed to launch jvm". I searched the whole internet, but I couldn't find much about this topic. I hope I will get solution to this problem.
Thank you in advance.</p>

答:
You could experience this error if you didn't include the third-party libraries to the build.

The following can be placed in the build.xml just before the end tag of the project.

```<code><target name="-post-jfx-deploy">
    <fx:deploy width="${javafx.run.width}" height="${javafx.run.height}" nativeBundles="all"
               outdir="${basedir}/${dist.dir}" outfile="${application.title}">
        <fx:application name="${application.title}" mainClass="${javafx.main.class}"/>
        <fx:resources>
            <fx:fileset dir="${basedir}/${dist.dir}" includes="*.jar"/>
            <fx:fileset dir="${basedir}/${dist.dir}" includes="lib/*.jar"/>
        </fx:resources>
        <fx:info title="${application.title}" vendor="${application.vendor}"/>
    </fx:deploy>
</code>```

Body:
You could experience this error if you didn't include the third-party libraries to the build.

The following can be placed in the build.xml just before the end tag of the project.

<target name="-post-jfx-deploy">
    <fx:deploy width="${javafx.run.width}" height="${javafx.run.height}" nativeBundles="all"
               outdir="${basedir}/${dist.dir}" outfile="${application.title}">
        <fx:application name="${application.title}" mainClass="${javafx.main.class}"/>
        <fx:resources>
            <fx:fileset dir="${basedir}/${dist.dir}" includes="*.jar"/>
            <fx:fileset dir="${basedir}/${dist.dir}" includes="lib/*.jar"/>
        </fx:resources>
        <fx:info title="${application.title}" vendor="${application.vendor}"/>
    </fx:deploy>


问:
JSTL foreach var sending to jsp/servlet
I want to know a method how can I send 1 specified item for JSTL's foreach to other JSP or servlet, to print detailed info about that item.

Giving followin code:

```<code>    <c:forEach var="note" items="${notes}">
        <tr>
            <td>${note.getTitle()}</td>
            <td>${note.getRealDate()}</td>
            <td>${note.getUserDate()}</td>
            <td>
                <form action="showdetails.jsp">
                    <input type="submit" value="show details" name="details" />
                </form>
            </td>
        </tr>
    </c:forEach>
</code>```

I need to replace my form, or remake it, to get something that does the job, and I'm out of ideas...

ah, btw. Note has method shown above + showDetails() with String return. And I want to display them all, or just do String all = note.toString(); in jsp/servlet

答:
Just pass an identifier as request parameter and change the URL to be a servlet one. If you insist to use a submit button, pass the identifier as a hidden input field:

<form action="showdetails">
    <input type="hidden" name="id" value="${note.id}" />
    <input type="submit" name="details" value="show details" />
</form>
```

<p>In the servlet which is mapped on an URL pattern of <code>/showdetails</code> just do the following job in <code>doGet()</code> method:</p>

<pre class="lang-java prettyprint-override"><code>String id = request.getParameter("id");
Note note = noteService.find(id);
request.setAttribute("note", note);
request.getRequestDispatcher("/WEB-INF/showdetails.jsp").forward(request, response);
</code>```

In the showdetails.jsp you can then use ${note} to access the selected Note.

Exactly the above servlet is also useable when you use a link instead as Bozho suggests, with only one little difference, in the servlet you're able to preprocess the request (to find and prepare the right Note object for display).

show details
```

See also:

Our servlets wiki page

Title: JSTL foreach var sending to jsp/servlet

Body:
I want to know a method how can I send 1 specified item for JSTL's foreach to other JSP or servlet, to print detailed info about that item.

Giving followin code:

    <c:forEach var="note" items="${notes}">

            ${note.getTitle()}
            ${note.getRealDate()}
            ${note.getUserDate()}

                <form action="showdetails.jsp">
                    <input type="submit" value="show details" name="details" />
                </form>

    </c:forEach>

I need to replace my form, or remake it, to get something that does the job, and I'm out of ideas...

ah, btw. Note has method shown above + showDetails() with String return. And I want to display them all, or just do String all = note.toString(); in jsp/servlet

Body:
Just pass an identifier as request parameter and change the URL to be a servlet one. If you insist to use a submit button, pass the identifier as a hidden input field:

<form action="showdetails">
    <input type="hidden" name="id" value="${note.id}" />
    <input type="submit" name="details" value="show details" />
</form>

In the servlet which is mapped on an URL pattern of /showdetails just do the following job in doGet() method:

String id = request.getParameter("id");
Note note = noteService.find(id);
request.setAttribute("note", note);
request.getRequestDispatcher("/WEB-INF/showdetails.jsp").forward(request, response);

In the showdetails.jsp you can then use ${note} to access the selected Note.

Exactly the above servlet is also useable when you use a link instead as Bozho suggests, with only one little difference, in the servlet you're able to preprocess the request (to find and prepare the right Note object for display).

<a href="showdetails?id=${note.id}">show details</a>

See also:

Our servlets wiki page


问:
Fast word count function in Vim
I am trying to display a live word count in the vim statusline. I do this by setting my status line in my .vimrc and inserting a function into it. The idea of this function is to return the number of words in the current buffer. This number is then displayed on the status line. This should work nicely as the statusline is updated at just about every possible opportunity so the count will always remain 'live'.

The problem is that the function I have currently defined is slow and so vim is obviously sluggish when it is used for all but the smallest files; due to this function being executed so frequently.

In summary, does anyone have a clever trick for producing a function that is blazingly fast at calculating the number of words in the current buffer and returning the result?

答:
Since vim version 7.4.1042

Since vim version 7.4.1042, one can simply alter the statusline as follows:

```<code>set statusline+=%{wordcount().words}\ words
set laststatus=2    " enables the statusline.
</code>```

Word count in vim-airline

Word count is provided standard by vim-airline for a number of file types, being at the time of writing:
asciidoc, help, mail, markdown, org, rst, tex ,text

If word count is not shown in the vim-airline, more often this is due to an unrecognised file type. For example, at least for now, the compound file type markdown.pandoc is not being recognised by vim-airline for word count. This can easily be remedied by amending the .vimrc as follows:

```<code>let g:airline#extensions#wordcount#filetypes = '\vasciidoc|help|mail|markdown|markdown.pandoc|org|rst|tex|text'
set laststatus=2    " enables vim-airline.
</code>```

The \v statement overrides the default g:airline#extensions#wordcount#filetypes variable. The last line ensures vim-airline is enabled.

In case of doubt, the &filetype of an opened file is returned upon issuing the following command:

```<code>:echo &filetype
</code>```

Here is a meta-example:

ContentLicense: CC BY-SA 2.5

Title: Fast word count function in Vim

Body:
Since vim version 7.4.1042

Since vim version 7.4.1042, one can simply alter the statusline as follows:

set statusline+=%{wordcount().words}\ words
set laststatus=2    " enables the statusline.

Word count in vim-airline

Word count is provided standard by vim-airline for a number of file types, being at the time of writing:
asciidoc, help, mail, markdown, org, rst, tex ,text

If word count is not shown in the vim-airline, more often this is due to an unrecognised file type. For example, at least for now, the compound file type markdown.pandoc is not being recognised by vim-airline for word count. This can easily be remedied by amending the .vimrc as follows:

let g:airline#extensions#wordcount#filetypes = '\vasciidoc|help|mail|markdown|markdown.pandoc|org|rst|tex|text'
set laststatus=2    " enables vim-airline.

The \v statement overrides the default g:airline#extensions#wordcount#filetypes variable. The last line ensures vim-airline is enabled.

In case of doubt, the &filetype of an opened file is returned upon issuing the following command:

:echo &filetype

Here is a meta-example:


问:
How to create a proper merge commit in git which is also squashed
I'm trying to solve a problem with my git history.

I have two branches, lets call them a and b, a is the source branch for my repository, and b was branched off it. Many merged pull requests (a mix of merge commits, and squashed commits) happen to a, and b is not rebased, neither are these PRs re-opened against b. In order to update b, I (naively) resort to cherry-picking the merge commits from a that are applicable to b.

Over time as the code is tested and approved in a, b is now equal to a, with an empty diff, but the history shows, (as expected) a divergence in commits. (b is seen as many commits ahead of a in Github).

I would like to eliminate this divergence, if I perform merge commits from either one into the other, I get a long string of commits with no changes (except in some cases on Github where it gets confused), which would pollute the history of either branch if allowed onto them.

e.g. git merge a from b or git merge b from a shows a long string of commits in the log. (Edit: this is with --no-ff).

If I perform a squash, I get a nice message listing those commits with no changes.

e.g. git merge a --squash from b or git merge b --squash from a requires git commit --allow-empty.

But that does not prevent the "this branch is ahead/behind" situation.

So my question is how do I produce a single commit (can be in either or both branches) to prevent the "ahead/behind" situation.

Edit: This is mainly for ease of tracing whats happened on Github, I know how git works and know how to do this by destroying the history of one or the other branches by force pushing, but I'm trying to preserve both in a way that is easily introspectable.

答:
resort to cherry-picking […] Over time as the code is tested and approved in a, b is now equal to a, with an empty diff, but the history shows, (as expected) a divergence in commits. I would like to eliminate this divergence, if I perform merge commits from either one into the other, I get a long string of commits […], which would pollute the history

You either have different commits in the histories, or the same ones.  You can't have it both ways.

But you can easily not list the merged commits.  git log --first-parent shows you only the commits on your main ancestry, without listing any merged-in history details. This is probably what you want.  Folding a long string of commits into a single summary-merge commit, which can then be listed alone with --first-parent, is a useful trick.  Hunt up --no-ff merges, they're how you do recorded summary merges, putting the merged history on a second-parent branch, rather than simply fast-forwarding over the whole list, keeping it as part of the main line.


问:
Display data of class from list in c#
I was trying to display data of class from list in C#.

Here is my class definition:

```<code>    class Vehicle
    {
        public string brand;
        public string model;
    }

    class Car : Vehicle
    {
        double trunk_capacity;
        int doors_number;
        int vmax;
    }
</code>```

Here is my code in which i'm adding car element:

```<code>    public static void AddCar(List<object> avaliable_cars)
    {
        int x = 0;

        Console.WriteLine("Adding new car:");
        Console.WriteLine("1 - Car");
        Console.WriteLine("2 - Sport Car");
        Console.WriteLine("3 - Truck");

        x = int.Parse(Console.ReadLine());

        switch (x)
        {
            case 1:
            {
                Console.WriteLine("Adding new Car.");

                avaliable_cars.Add(new Car());
                Console.WriteLine("Brand");
                string brand_tmp = Console.ReadLine();
                Console.WriteLine("Model");
                string model_tmp = Console.ReadLine();
                avaliable_cars.Add(new Car()
                {
                    brand = brand_tmp,
                    model = model_tmp
                });

            } break;
        }

   }
</code>```

I don't have idea how can i display data from this list.

I was trying to do this

```<code>foreach (object car in avaliable_cars)
{
  Console.WriteLine(car);
}
</code>```

I doesn't works. Also i want to access one element at one time - for example i want to display brand of first car on the list. How can i do this?

PS Im beginner in C#, so im sorry for any stupid elements in my code.

答:
We can simply use String.Join or foreach. </p>

```<code>       List<string> numbers = new List<string>
                    { "One", "Two", "Three","Four","Five"};

        Console.WriteLine(String.Join(", ", numbers));

List<string> strings = new List<string> { "a", "b", "c" };

strings.ForEach(Console.WriteLine);
</code>```

Title: Display data of class from list in c#

Body:
I was trying to display data of class from list in C#.

Here is my class definition:

    class Vehicle
    {
        public string brand;
        public string model;
    }

    class Car : Vehicle
    {
        double trunk_capacity;
        int doors_number;
        int vmax;
    }

Here is my code in which i'm adding car element:

    public static void AddCar(List<object> avaliable_cars)
    {
        int x = 0;

        Console.WriteLine("Adding new car:");
        Console.WriteLine("1 - Car");
        Console.WriteLine("2 - Sport Car");
        Console.WriteLine("3 - Truck");

        x = int.Parse(Console.ReadLine());

        switch (x)
        {
            case 1:
            {
                Console.WriteLine("Adding new Car.");

                avaliable_cars.Add(new Car());
                Console.WriteLine("Brand");
                string brand_tmp = Console.ReadLine();
                Console.WriteLine("Model");
                string model_tmp = Console.ReadLine();
                avaliable_cars.Add(new Car()
                {
                    brand = brand_tmp,
                    model = model_tmp
                });

            } break;
        }

   }

I don't have idea how can i display data from this list.

I was trying to do this

foreach (object car in avaliable_cars)
{
  Console.WriteLine(car);
}

I doesn't works. Also i want to access one element at one time - for example i want to display brand of first car on the list. How can i do this?

PS Im beginner in C#, so im sorry for any stupid elements in my code.

Body:
We can simply use String.Join or foreach.

       List<string> numbers = new List<string>
                    { "One", "Two", "Three","Four","Five"};

        Console.WriteLine(String.Join(", ", numbers));

List<string> strings = new List<string> { "a", "b", "c" };

strings.ForEach(Console.WriteLine);


问:
Why is Graph.copy() slower than copy.deepcopy(Graph) in NetworkX?
I've been using NetworkX extensively for my research, but I've come across something that's a bit puzzling (and concerning) to me. I've been using copy.deepcopy() to copy graphs, but just realized that the Graph class has its own .copy() method which generates a deep copy.

I decided to use %timeit to see if I was handicapping myself and ended up with the following results for a graph G with 25 nodes and 66 edges:

```<code>%timeit for x in range(100): copy.deepcopy(G)
80.5 ms ± 1.26 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit for x in range(100): G.copy()
93.4 ms ± 1.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code>```

What is NetworkX doing differently that takes longer? This makes me concerned that I'm not doing this properly, but I haven't run into any serious issues so far that would indicate that using copy.deepcopy() is the wrong choice here.

答:
You can look at the source code yourself: [GitHub]: networkx/networkx - (master) networkx/networkx/classes/graph.py.

According to [GitHub.NetworkX]: networkx.Graph.copy (the same info is also present in the 1st URL) (emphasis is mine):

The copy method by default returns an independent shallow copy of the graph and attributes. That is, if an attribute is a container, that container is shared by the original an the copy. Use Python’s copy.deepcopy for new containers.

...

Deepcopy – A “deepcopy” copies the graph structure as well as all data attributes and any objects they might contain. The entire graph object is new so that changes in the copy do not affect the original object. (see Python’s copy.deepcopy)

...

Independent Shallow – This copy creates new independent attribute dicts and then does a shallow copy of the attributes. That is, any attributes that are containers are shared between the new graph and the original. This is exactly what dict.copy() provides.

What Graph.copy (probably) does, is additional computations in order to preserve memory.

So, if you want 2 completely independent graphs, you could use copy.deepcopy without any problems.

Body:
I've been using NetworkX extensively for my research, but I've come across something that's a bit puzzling (and concerning) to me. I've been using copy.deepcopy() to copy graphs, but just realized that the Graph class has its own .copy() method which generates a deep copy.

I decided to use %timeit to see if I was handicapping myself and ended up with the following results for a graph G with 25 nodes and 66 edges:

%timeit for x in range(100): copy.deepcopy(G)
80.5 ms ± 1.26 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit for x in range(100): G.copy()
93.4 ms ± 1.06 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

What is NetworkX doing differently that takes longer? This makes me concerned that I'm not doing this properly, but I haven't run into any serious issues so far that would indicate that using copy.deepcopy() is the wrong choice here.


问:
Vector capacity and reserve
Consider the following code snippet:

```<code>std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;
</code>```

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?

答:
You are looking for the (in)famous swap trick:

```<code>vector<T>().swap(myVector);
</code>```

See here for backgrounder

How to downsize std::vector?

Title: Vector capacity and reserve

Body:
Consider the following code snippet:

std::vector<int> v;
v.reserve(100);
v.insert(v.end(), 100, 5);

v.erase(v.begin(), v.end());

std::cout << v.capacity << std::endl;

This prints out 100. Does it mean that vector still holds the 100 memory locations? Is it required to call reserve(0) after calling erase(begin,end) on a vector, to relinquish all space held by the vector?

Body:
You are looking for the (in)famous swap trick:

vector<T>().swap(myVector);

See here for backgrounder

How to downsize std::vector?


问:
Preprocessing frames before passing to the model for object detection
I am working on a project to detect objects from video using tensorflow API.
I am new to video analytics and so I would like to know what are the common practices while making the inference.
Do you run the model on every frame or skip frames?
when do you perform background subtraction?
Once you detected the object,how do you stop the model from detecting the same object again.

Thanks.

答:
Do you run the model on every frame or skip frames?

Depends how long your processing time is. If you can process each frame efficiently enough that you don't start lagging behind on your frame queue, then why not process each frame? This entirely comes down to your application and level of optimization.  I've certainly written both types of vision applications; ones where each frame needs processing, and others where you only process every 1/X frames.

When do you perform background subtraction?

Once you have enough data to accurately classify the "background". For example I've had applications where I control the lighting and background and I know that anything that is black is deemed "background". Then I look for the regions that actually have non black pixels. This happens in the first frame. If the objects are stationary it only needs to happen once.. but if the objects are in motion it may need to happen periodically.

If the background isn't a known color/pattern/etc, you'll have to find objects and deem "foreground" vs "background", which would likely happen in the first ~3-5 frames.

Once you detected the object,how do you stop the model from detecting the same object again?

Depends. Will there be motion? If everything is stationary, you want "mask" over the region that the object resides in the image. You're ignoring this specific area and only processing around it.  If the objects are in motion / non-stationary, you need to classify every object every frame and track each object frame by frame.


问:
Why does having a large array cause NoMethodError to take longer to be raised
I have the following Ruby code where each instance of BigClass creates a array with instances of BigClass (up until a maximum depth).

```<code>class BigClass
  # Increase this depending on your computer performance
  MAX_DEPTH = 8

  def initialize(depth = 0)
    @my_arr = []

    5.times do |i|
      unless depth > MAX_DEPTH
        @my_arr << BigClass.new(depth+1)
      end
    end
  end
end

big_class = BigClass.new

puts "Reaches here"

# This line should throw an error but instead freezes
big_class.blah

puts "Doesn't reach here"
</code>```

When calling a method which doesn't exist, I expect to receive a NoMethodError pretty much instantly, however, it seems that the larger the contents of the array in big_class the longer it takes for the error to be produced.

Why is this?

A few options I considered:

Maybe Ruby does some kind of cleanup or calls some hooks for all created instances before throwing an error. But if I make the error happen from a different object or inside an existing method, it instantly raises the error.

Maybe the Ruby method lookup for some reason includes instance variables lookup, but after reading this GitHub Gist I can't find anything to indicate that that would be the cause

Something I have noticed is that when it prints "Reached here" if I quit (CTRL-C) it will immediately print out the NoMethodError. So it doesn't seem to be an issue with finding whether or not the method exists, otherwise it wouldn't know that that is the error when I quit.

答:
I think I worked it out.

If I override the #inspect method of BigClass it no longer causes an issue. This makes me think that something internally is calling #inspect when handling the error. Since the default inspect will include the instance variables, and call inspect on them as well, if there are many instance variables and they all have many instance variables, then it could take a very long time to process.

The below code shows a version which runs as I would expect:

```<code>class BigClass
  # Increase this depending on your computer performance
  MAX_DEPTH = 8

  def initialize(depth = 0)
    @my_arr = []

    5.times do |i|
      unless depth > MAX_DEPTH
        @my_arr << BigClass.new(depth+1)
      end
    end
  end

  def inspect
    "now it works"
  end
end

big_class = BigClass.new

puts "Reaches here"

# Correctly raises an error now
big_class.blah_blah_blah

puts "Doesn't reach here"
</code>```

Body:
I have the following Ruby code where each instance of BigClass creates a array with instances of BigClass (up until a maximum depth).

class BigClass
  # Increase this depending on your computer performance
  MAX_DEPTH = 8

  def initialize(depth = 0)
    @my_arr = []

    5.times do |i|
      unless depth > MAX_DEPTH
        @my_arr << BigClass.new(depth+1)
      end
    end
  end
end

big_class = BigClass.new

puts "Reaches here"

# This line should throw an error but instead freezes
big_class.blah

puts "Doesn't reach here"

When calling a method which doesn't exist, I expect to receive a NoMethodError pretty much instantly, however, it seems that the larger the contents of the array in big_class the longer it takes for the error to be produced.

Why is this?

A few options I considered:

Maybe Ruby does some kind of cleanup or calls some hooks for all created instances before throwing an error. But if I make the error happen from a different object or inside an existing method, it instantly raises the error.

Maybe the Ruby method lookup for some reason includes instance variables lookup, but after reading this GitHub Gist I can't find anything to indicate that that would be the cause

Something I have noticed is that when it prints "Reached here" if I quit (CTRL-C) it will immediately print out the NoMethodError. So it doesn't seem to be an issue with finding whether or not the method exists, otherwise it wouldn't know that that is the error when I quit.

Body:
I think I worked it out.

If I override the #inspect method of BigClass it no longer causes an issue. This makes me think that something internally is calling #inspect when handling the error. Since the default inspect will include the instance variables, and call inspect on them as well, if there are many instance variables and they all have many instance variables, then it could take a very long time to process.

The below code shows a version which runs as I would expect:

class BigClass
  # Increase this depending on your computer performance
  MAX_DEPTH = 8

  def initialize(depth = 0)
    @my_arr = []

    5.times do |i|
      unless depth > MAX_DEPTH
        @my_arr << BigClass.new(depth+1)
      end
    end
  end

  def inspect
    "now it works"
  end
end

big_class = BigClass.new

puts "Reaches here"

# Correctly raises an error now
big_class.blah_blah_blah

puts "Doesn't reach here"


问:
Output is NaN , how?
I am trying to code Taylor series but I am getting 'nan' as output in case of large value of n(=100).
Where am I doing things wrong?</p>

```<code>#include<iostream>
#include<cmath>
using namespace std;

 int main(){

    int n;
    double x;

    cin >> n;
    cin >> x;

    long double temp_val = 1;
    int sign = 1;
    int power = 1;
    long long int factorial = 1;

    for(int i = 1 ; i < n ; i++){

        sign = sign* -1 ;
        power =  2*i;
        factorial  = factorial*(2*i)*(2*i-1);

        temp_val += sign*pow(x,power)/factorial;
    }
    cout<<temp_val;

}
</code>```

答:
For large n your program has undefined behavior.

You are calculating the factorial of 2n (so 200) in factorial. 200! is, according to Wolfram Alpha:

788657867364790503552363213932185062295135977687173263294742533244359449963403342920304284011984623904177212138919638830257642790242637105061926624952829931113462857270763317237396988943922445621451664240254033291864131227428294853277524242407573903240321257405579568660226031904170324062351700858796178922222789623703897374720000000000000000000000000000000000000000000000000

For comparison, the typical largest value that a long long int can hold is

9223372036854775807

(which is assuming it is 64-bit)

Clearly you will not be able to fit 200! into that. When you overflow a signed integer variable your program will have undefined behavior. That means that there will be no guarantee how it will behave.

But even if you change the variable type to be unsigned, not much will change. The program won't have undefined behavior anymore, but the factorial will not actually hold the correct value. Instead it will keep wrapping around back to zero.

Even if you change factorial to be type double, this will probably not be enough with at typical double implementation to hold this value. Your platform might have a long double type that is larger than double and able to hold this value.

You will have similar problems with pow(x, power) if x is not close to 1.

As mentioned in the answer by @idclev463035818 the Taylor series, if evaluated straightforwardly, is numerically very ill-behaved and can not really be used practically in this form for large n.

Title: Output is NaN , how?

Body:
I am trying to code Taylor series but I am getting 'nan' as output in case of large value of n(=100).
Where am I doing things wrong?

#include<iostream>
#include<cmath>
using namespace std;

 int main(){

    int n;
    double x;

    cin >> n;
    cin >> x;

    long double temp_val = 1;
    int sign = 1;
    int power = 1;
    long long int factorial = 1;

    for(int i = 1 ; i < n ; i++){

        sign = sign* -1 ;
        power =  2*i;
        factorial  = factorial*(2*i)*(2*i-1);

        temp_val += sign*pow(x,power)/factorial;
    }
    cout<<temp_val;

}


问:
How to access Activity UI from my class?
I have an activity which creates an object instance of my class:

```<code>file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------
</code>```

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?

答: You should do everything and pass back the value to the activity to handle UI instead of doing any UI related stuff in the point stuff.</p>

Body:
I have an activity which creates an object instance of my class:

file MyActivity.java:
public class MyActivity extends Activity {
    TextView myView = (TextView)findViewById(R.id.myView);
    ...
    Points myPoints new Points();
    ...
}
--------------------------------------------------------------

file Points.java:
private class Points {
    ...
    HOW TO USE myView HERE ???
    ...
}
--------------------------------------------------------------

How do I use the UI objects in my class (which does not extend an
Activity)? Should I pass some context to my Points class? How do I do, exactly?


问:
Sorting Array in nodejs by date order (recent to oldest)
I'm trying to sort the following array so that the most recent event_end is first

```<code>{
   "results":[
      {
         "event_start":"2017-11-27T09:00:00Z",
         "event_end":"2017-11-27T09:00:00Z",
         "attendance":0,
         "title":"Administrate Training Session",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-01T09:00:00Z",
         "event_end":"2018-02-01T09:00:00Z",
         "attendance":0,
         "title":"Health and Safety Awareness (HSA)",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-19T09:00:00Z",
         "event_end":"2018-04-30T09:00:00Z",
         "attendance":0,
         "title":"SMSTS",
         "type":"delegate"
      }
   ]
}
</code>```

My current code (and this is after trying almost all the different ways to do this is):

```<code>Array.from(outcome).sort(sortFunction);
      function sortFunction(a, b){
        if(b[3] === a[3]){
          return 0;
        } else {
          return (b[3] < a[3]) ? -1 : 1;
        }
      }
</code>```

And just to give clarity to how the array is being created:

```<code>var history = JSON.parse(body);
      var outcome = {};
      var key = 'results';
      outcome[key] = [];
      history.forEach(delegate => {
          var data = null;
          var sessionKey;
          var attendanceCount = 0;
          var sessionCount = 0;
          var attended = 0;
          Array.from(delegate['session_attendance']).forEach(function(val){
            if(!val.__proto__.__proto__){
              sessionCount++;
            }
          });
          var type;
          for(var k in delegate['session_attendance']){
            sessionKey = k;
            if(k['status'] == true){
              attendanceCount++;
            }
          }
          if(attendanceCount == 0){
            attended = attendanceCount;
          } else {
            (attendanceCount / sessionCount) * 100
          }
          if(delegate['registration']['booking_contact'] !== null){
            if(delegate['registration']['booking_contact']['id'] == delegate['contact']['id']){
              type = 'booking_contact';
            }
          } else{
            type = 'delegate';
          }
          data = {
            'objectId': delegate['id'],
            'title': delegate['event']['title'],
            'event_start': delegate['event']['start'],
            'event_end': delegate['session_attendance'][sessionKey]['start'],
            'attendance': attended,
            'type': type
          }
          outcome[key].push(data);
        })
</code>```

I'm sure its obvious but can anyone point me in the direction of where I am going wrong and how to sort it appropriately?

答:
The function that sort receives get 2 params, each param is an obj, so you can access its properties.

Something like this should work:

```<code>arr.sort((a, b) => {
    return a.event_end > b.event_end ? -1 : 1;
})

</code>```

Body:
I'm trying to sort the following array so that the most recent event_end is first

{
   "results":[
      {
         "event_start":"2017-11-27T09:00:00Z",
         "event_end":"2017-11-27T09:00:00Z",
         "attendance":0,
         "title":"Administrate Training Session",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-01T09:00:00Z",
         "event_end":"2018-02-01T09:00:00Z",
         "attendance":0,
         "title":"Health and Safety Awareness (HSA)",
         "type":"delegate"
      },
      {
         "event_start":"2018-02-19T09:00:00Z",
         "event_end":"2018-04-30T09:00:00Z",
         "attendance":0,
         "title":"SMSTS",
         "type":"delegate"
      }
   ]
}

My current code (and this is after trying almost all the different ways to do this is):

Array.from(outcome).sort(sortFunction);
      function sortFunction(a, b){
        if(b[3] === a[3]){
          return 0;
        } else {
          return (b[3] < a[3]) ? -1 : 1;
        }
      }

And just to give clarity to how the array is being created:

var history = JSON.parse(body);
      var outcome = {};
      var key = 'results';
      outcome[key] = [];
      history.forEach(delegate => {
          var data = null;
          var sessionKey;
          var attendanceCount = 0;
          var sessionCount = 0;
          var attended = 0;
          Array.from(delegate['session_attendance']).forEach(function(val){
            if(!val.__proto__.__proto__){
              sessionCount++;
            }
          });
          var type;
          for(var k in delegate['session_attendance']){
            sessionKey = k;
            if(k['status'] == true){
              attendanceCount++;
            }
          }
          if(attendanceCount == 0){
            attended = attendanceCount;
          } else {
            (attendanceCount / sessionCount) * 100
          }
          if(delegate['registration']['booking_contact'] !== null){
            if(delegate['registration']['booking_contact']['id'] == delegate['contact']['id']){
              type = 'booking_contact';
            }
          } else{
            type = 'delegate';
          }
          data = {
            'objectId': delegate['id'],
            'title': delegate['event']['title'],
            'event_start': delegate['event']['start'],
            'event_end': delegate['session_attendance'][sessionKey]['start'],
            'attendance': attended,
            'type': type
          }
          outcome[key].push(data);
        })

I'm sure its obvious but can anyone point me in the direction of where I am going wrong and how to sort it appropriately?

Body:
The function that sort receives get 2 params, each param is an obj, so you can access its properties.

Something like this should work:

arr.sort((a, b) => {
    return a.event_end > b.event_end ? -1 : 1;
})


问:
Using @covers for a class
I am using php for testing my code. Here is an example:

```<code>/**
 * @covers Calculator::
 */
class CalculatorTest extends PHPUnit_Framework_TestCase {
    protected function setUp() { /* ... */ }
    /**
     * @covers Calculator::add
     */
    public function testAddTwoIntegers() { /* ... */ }
    /**
     * @covers Calculator::multiply
     */
    public function testMultiplyTwoIntegers() { /* ... */ }
}
</code>```

However, my code is complicated and I want to get rid of @covers over individual test methods. How does php treat the following class when generating coverage reports:

```<code>/**
 * @covers Calculator
 */
class CalculatorTest extends PHPUnit_Framework_TestCase {
    protected function setUp() { /* ... */ }

    public function testAddTwoIntegers() { /* ... */ }

    public function testMultiplyTwoIntegers() { /* ... */ }
}
</code>```

Notice that the @covers annotation over a class is still there but I have removed it from every method.

I am able to get coverage reports using this approach too but I have not seen an example of it anywhere, so I want to know if this is not a correct use.

```<code>Code Coverage Report:
  2016-01-18 08:57:50

 Summary:
  Classes: 17.67% (56/317)
  Methods:  0.33% (5/1520)
  Lines:    0.60% (109/18094)

Class1:
  Methods:  66.67% ( 2/ 3)   Lines:  95.45% ( 21/ 22)
Class2:
  Methods:  50.00% ( 3/ 6)   Lines:  96.70% ( 88/ 91)
</code>```

答:
Indeed, setting the classname without the method name is the recommended @covers syntax.

Documentation here:

https://phpunit.readthedocs.io/en/8.5/annotations.html#covers

```<code>Annotation
@covers ClassName::methodName (not recommended)
@covers ClassName (recommended)
@covers ClassName<extended> (not recommended)
@covers ClassName::<public> (not recommended)
@covers ClassName::<protected> (not recommended)
@covers ClassName::<private> (not recommended)
@covers ClassName::<!public> (not recommended)
@covers ClassName::<!protected> (not recommended)
@covers ClassName::<!private> (not recommended)
@covers ::functionName (recommended)
</code>```

When you ask:

How does php treat the following class when generating coverage reports

The answer is: Every line of the class mentioned in @covers executed during "any" of the tests in that TestCase will compute a +1 in the execution.

If you do real TDD and start first by writing the test, then writing the class, this is a perfect approach. Some of your lines in your public methods with branches will count 2 or more executions, and probably the lines inside each of the branches will count 1 execution.

Private methods will also count +n executions, while you won't write named tests for those methods, they will be called as a result of being helpers to the public methods.

When you say:

but I have not seen an example of it anywhere

I can tell that 90% of our tests use a @covers MyNiceClass annotation without specifying any method.

If you start by the test first, you normally won't mess up things. If you "need" that "MyNiceClass" is able to get something, you start by doing testGetSomething() in the test and set a basic expectation, then you write the public function getSomething() in the class and you end up having a one-to-one test for each method in 80% of the cases. The rest of the cases normally are multiple tests for the same method like for example testGetSomething() (happy path) and testGetSomethingThrowsExceptionWithInvalidParameter() (sad path).

In short

Yes, what you propose is correct, normal, usual and it is the recommended way to go according to the documentation.

Title: Using @covers for a class

Body:
I am using php for testing my code. Here is an example:

/**
 * @covers Calculator::
 */
class CalculatorTest extends PHPUnit_Framework_TestCase {
    protected function setUp() { /* ... */ }
    /**
     * @covers Calculator::add
     */
    public function testAddTwoIntegers() { /* ... */ }
    /**
     * @covers Calculator::multiply
     */
    public function testMultiplyTwoIntegers() { /* ... */ }
}

However, my code is complicated and I want to get rid of @covers over individual test methods. How does php treat the following class when generating coverage reports:

/**
 * @covers Calculator
 */
class CalculatorTest extends PHPUnit_Framework_TestCase {
    protected function setUp() { /* ... */ }

    public function testAddTwoIntegers() { /* ... */ }

    public function testMultiplyTwoIntegers() { /* ... */ }
}

Notice that the @covers annotation over a class is still there but I have removed it from every method.

I am able to get coverage reports using this approach too but I have not seen an example of it anywhere, so I want to know if this is not a correct use.

Code Coverage Report:
  2016-01-18 08:57:50

 Summary:
  Classes: 17.67% (56/317)
  Methods:  0.33% (5/1520)
  Lines:    0.60% (109/18094)

Class1:
  Methods:  66.67% ( 2/ 3)   Lines:  95.45% ( 21/ 22)
Class2:
  Methods:  50.00% ( 3/ 6)   Lines:  96.70% ( 88/ 91)

Body:
Indeed, setting the classname without the method name is the recommended @covers syntax.

Documentation here:

https://phpunit.readthedocs.io/en/8.5/annotations.html#covers

Annotation
@covers ClassName::methodName (not recommended)
@covers ClassName (recommended)
@covers ClassName<extended> (not recommended)
@covers ClassName::<public> (not recommended)
@covers ClassName::<protected> (not recommended)
@covers ClassName::<private> (not recommended)
@covers ClassName::<!public> (not recommended)
@covers ClassName::<!protected> (not recommended)
@covers ClassName::<!private> (not recommended)
@covers ::functionName (recommended)

When you ask:

How does php treat the following class when generating coverage reports

The answer is: Every line of the class mentioned in @covers executed during "any" of the tests in that TestCase will compute a +1 in the execution.

If you do real TDD and start first by writing the test, then writing the class, this is a perfect approach. Some of your lines in your public methods with branches will count 2 or more executions, and probably the lines inside each of the branches will count 1 execution.

Private methods will also count +n executions, while you won't write named tests for those methods, they will be called as a result of being helpers to the public methods.

When you say:

but I have not seen an example of it anywhere

I can tell that 90% of our tests use a @covers MyNiceClass annotation without specifying any method.

If you start by the test first, you normally won't mess up things. If you "need" that "MyNiceClass" is able to get something, you start by doing testGetSomething() in the test and set a basic expectation, then you write the public function getSomething() in the class and you end up having a one-to-one test for each method in 80% of the cases. The rest of the cases normally are multiple tests for the same method like for example testGetSomething() (happy path) and testGetSomethingThrowsExceptionWithInvalidParameter() (sad path).

In short

Yes, what you propose is correct, normal, usual and it is the recommended way to go according to the documentation.


问:
how to pass encrypted query string in asp.net
I need to pass values between asp.net pages. How do i encrypt those values in the URL?
Example : Response.Redirect("customerAdd.aspx?customerId=" + custId);</p>

答:
You can encrypt the string with the built-in .NET encryption tools.  You'll need to use Server.HtmlEncode/Server.HtmlDecode on the string to ensure that the encrypted string is HTTP compliant.

Here is an article on encryption in .NET.

OwnerDisplayName: Ksmps

OwnerDisplayName: Dave


问:
Passing a struct through cgo
I am using cgo to call c from go. I want to pass a struct through the function.
In my c file it looks like this:

```<code>#include <stdio.h>

void test(TestStruct val) {
  printf(val);
}
</code>```

In my go file i am doing this:

```<code>package main

// #cgo CXXFLAGS: -I/usr/lib/
// #cgo LDFLAGS: -L/usr/lib/ -lstdc++
//#include <file.c>
import "C"

type TestStruct struct {
  val  string
  type string
}

func main() {
  var value = TestStruct{ "foo", "bar" }

  C.test(value);
}
</code>```

but this doesn't work. It throws this error:

could not determine kind of name for C.test

答:
TestStruct is not defined in the C code. Try adding a definition.

You'll also need to use cgo's C strings rather than Go's built-in string in the struct.

As an aside: There's two more mistakes in your C code. printf(val) does not work because printf can not be used to directly print a struct. Also, you should never use use anything but a string literal for printf's first argument for safety reasons. Replace that line by something like puts(val.val) or printf("%s", val.val).

Title: Passing a struct through cgo

Body:
I am using cgo to call c from go. I want to pass a struct through the function.
In my c file it looks like this:

#include <stdio.h>

void test(TestStruct val) {
  printf(val);
}

In my go file i am doing this:

package main

// #cgo CXXFLAGS: -I/usr/lib/
// #cgo LDFLAGS: -L/usr/lib/ -lstdc++
//#include <file.c>
import "C"

type TestStruct struct {
  val  string
  type string
}

func main() {
  var value = TestStruct{ "foo", "bar" }

  C.test(value);
}

but this doesn't work. It throws this error:

could not determine kind of name for C.test


问:
Finding the render route if validation fails in Rails
I am trying to create a basic survey tool as my first Rails project.
At the moment I am working on the validation for submitting a new answer to a survey question. The following is my answer model.

```<code>class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :text, presence: true,
            length: { minimum: 5, maximum: 100 }
end

</code>```

I have set up an if statement that takes you to the next question if passes validation. My problem is I'm not sure what to render inside the else for this statement.

For similar validation in other controllers I have written the render statement to be the pages URL. For example: View all questions + add new question are rendered on the studies/id page. So if question validation fails then render will be 'studies/show'.

The URL to add a new answer looks like this.
http://localhost:3000/studies/20/questions/47/answers/new

For more context here is some of my code:

```<code>*Answers Controller*

class AnswersController < ApplicationController
  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end

  def create
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @answer = @question.answers.build(answer_params)

    if @answer.save
      next_question = @question.next_question
      redirect_to next_question_path(next_question, @answer) if next_question.present?

    else
      #I want to render the current page the participant is on to display errors here.
    end
  end

  ***some private functions here***

end

</code>```

```<code>* New Answer View *
<div class="wrap">
  <h1 class="med-header"><%= @question.question %></h1>

  <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    <%= form.hidden_field :participant_id %>

    <% @question.answers.each do |answer| %>
        <% if answer.errors.any? %>
          <div id="error_explanation">
            <h2>
              <%= pluralize(answer.errors.count, "error") %> prohibited
              this answer from being saved:
            </h2>
            <ul>
              <% answer.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
              <% end %>
            </ul>
          </div>
        <% end %>
      <% end %>

    <%= form.text_area :text %><br>
    <%= form.submit %>
  <% end %>
</div>
</code>```

What do I render in the else?

答:
create generates the object and saves. new only generates the object.
If @answer.save fails in this situation,

we need to show the form back to the user. format.html { render :new }

If use JSON you need show errors  format.json { render json: @anwser.errors, status: :unprocessable_entity }

Reference : How CURD Work

Body:
I am trying to create a basic survey tool as my first Rails project.
At the moment I am working on the validation for submitting a new answer to a survey question. The following is my answer model.

class Answer < ApplicationRecord
  belongs_to :question
  belongs_to :participant
  validates :text, presence: true,
            length: { minimum: 5, maximum: 100 }
end

I have set up an if statement that takes you to the next question if passes validation. My problem is I'm not sure what to render inside the else for this statement.

For similar validation in other controllers I have written the render statement to be the pages URL. For example: View all questions + add new question are rendered on the studies/id page. So if question validation fails then render will be 'studies/show'.

The URL to add a new answer looks like this.
http://localhost:3000/studies/20/questions/47/answers/new

For more context here is some of my code:

*Answers Controller*

class AnswersController < ApplicationController
  def new
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @participant = find_participant
    @answer = @question.answers.build(participant: @participant)
  end

  def create
    @study = Study.find(params[:study_id])
    @question = @study.questions.find(params[:question_id])
    @answer = @question.answers.build(answer_params)

    if @answer.save
      next_question = @question.next_question
      redirect_to next_question_path(next_question, @answer) if next_question.present?

    else
      #I want to render the current page the participant is on to display errors here.
    end
  end

  ***some private functions here***

end

* New Answer View *

<%= @question.question %>

  <%= form_with model: @answer, url: study_question_answers_path(@study, @question), local: true do |form| %>
    <%= form.hidden_field :participant_id %>

    <% @question.answers.each do |answer| %>
        <% if answer.errors.any? %>

              <%= pluralize(answer.errors.count, "error") %> prohibited
              this answer from being saved:

              <% answer.errors.full_messages.each do |msg| %>

<%= msg %>

              <% end %>

        <% end %>
      <% end %>

    <%= form.text_area :text %>

    <%= form.submit %>
  <% end %>

What do I render in the else?


问:
JDBC connection to SQL Server 2005 Instance running on remote machine
I am trying to connect to sql server 2005 instance running on a remote machine from my spring web application. This web application is running in tomcat server. Earlier When I connected to sql server 2000, it worked fine. I used msbase.jar, mssqlserver.jar, msutil.jar to connect to sql server 2000. My connection String was

```<code>jdbc:microsoft:sqlserver://192.168.0.38:1433;DatabaseName=AndroidPOC
</code>```

But now when I try to connect to sql server 2005. Iam getting all sorts of problems. I tried out various things but of no use.

My connection string for sql server 2005 was

```<code>jdbc:sqlserver://192.168.0.202;instanceName=INSTANCE_NAME;DatabaseName=MYDATABASE
</code>```

Please help me with the steps to connect to 2005 sql server.

What are all the jars required.

Do i need to update sql server jdbc driver, if yes how.

The driver class name to be used.

If possible please provide some sample code using spring jdbc and normal jdbc as well.

答: MSSQLSERVER-JDBC and Working With Connection will address all your questions.</p>

Body:
I am trying to connect to sql server 2005 instance running on a remote machine from my spring web application. This web application is running in tomcat server. Earlier When I connected to sql server 2000, it worked fine. I used msbase.jar, mssqlserver.jar, msutil.jar to connect to sql server 2000. My connection String was

jdbc:microsoft:sqlserver://192.168.0.38:1433;DatabaseName=AndroidPOC

But now when I try to connect to sql server 2005. Iam getting all sorts of problems. I tried out various things but of no use.

My connection string for sql server 2005 was

jdbc:sqlserver://192.168.0.202;instanceName=INSTANCE_NAME;DatabaseName=MYDATABASE

Please help me with the steps to connect to 2005 sql server.

What are all the jars required.

Do i need to update sql server jdbc driver, if yes how.

The driver class name to be used.

If possible please provide some sample code using spring jdbc and normal jdbc as well.


问:
How can I convert a list of dictionaries into a list of rows moving column-by-column?
I want to convert a list of dictionaries into a list of rows that contain the columns for those rows. I also want the order to start at column 1 and move down to the bottom of the column, then start on the next column, etc., until the list has been completed.

I also know that my max_items_per_column = 25

Let's say I have a list like this my_list = [1,2,3,...89,90] but with simple dictionaries like below:

```<code>my_list = [dict1, dict2, ... dict90]
</code>```

And I want to convert it to look like this:

```<code> 1  26  51   76
 2  27  52   77
 3  28  53   78
 4  29  54   79
 5  30  55   80
 6  31  56   81
 7  32  57   82
 8  33  58   83
 9  34  59   84
10  35  60   85
11  36  61   86
12  37  62   87
13  38  63   88
14  39  64   89
15  40  65   90
16  41  66
17  42  67
18  43  68
19  44  69
20  45  70
21  46  71
22  47  72
23  48  73
24  49  74
25  50  75
</code>```

So the converted list could be declared like this:

```<code>converted_list = [
    [dict1, dict26, dict51, dict76],
    [dict2, dict27, dict52, dict77],
    [dict3, dict28, dict53, dict78],
    .
    .
    .
    [dict25, dict50, dict75,None]
]
</code>```

I'm not sure how to do this, and I'm also not sure if this would be best done using Pandas or not.

Body:
I want to convert a list of dictionaries into a list of rows that contain the columns for those rows. I also want the order to start at column 1 and move down to the bottom of the column, then start on the next column, etc., until the list has been completed.

I also know that my max_items_per_column = 25

Let's say I have a list like this my_list = [1,2,3,...89,90] but with simple dictionaries like below:

my_list = [dict1, dict2, ... dict90]

And I want to convert it to look like this:

 1  26  51   76
 2  27  52   77
 3  28  53   78
 4  29  54   79
 5  30  55   80
 6  31  56   81
 7  32  57   82
 8  33  58   83
 9  34  59   84
10  35  60   85
11  36  61   86
12  37  62   87
13  38  63   88
14  39  64   89
15  40  65   90
16  41  66
17  42  67
18  43  68
19  44  69
20  45  70
21  46  71
22  47  72
23  48  73
24  49  74
25  50  75

So the converted list could be declared like this:

converted_list = [
    [dict1, dict26, dict51, dict76],
    [dict2, dict27, dict52, dict77],
    [dict3, dict28, dict53, dict78],
    .
    .
    .
    [dict25, dict50, dict75,None]
]

I'm not sure how to do this, and I'm also not sure if this would be best done using Pandas or not.

Body:
If you want it as a dataframe in your final format, you can do it like this:

my_list = [i for i in range(1, 91)] # setting up an example
next_list = [my_list[x:x+25] for x in range(0, len(my_list), 25)] # groups into a list of lists of len 25 each
df = pd.DataFrame.from_records(next_list).T

df looks like:

>>> df
       0     1     2     3
0    1.0  26.0  51.0  76.0
1    2.0  27.0  52.0  77.0
2    3.0  28.0  53.0  78.0
3    4.0  29.0  54.0  79.0
4    5.0  30.0  55.0  80.0
5    6.0  31.0  56.0  81.0
6    7.0  32.0  57.0  82.0
7    8.0  33.0  58.0  83.0
8    9.0  34.0  59.0  84.0
9   10.0  35.0  60.0  85.0
10  11.0  36.0  61.0  86.0
11  12.0  37.0  62.0  87.0
12  13.0  38.0  63.0  88.0
13  14.0  39.0  64.0  89.0
14  15.0  40.0  65.0  90.0
15  16.0  41.0  66.0   NaN
16  17.0  42.0  67.0   NaN
17  18.0  43.0  68.0   NaN
18  19.0  44.0  69.0   NaN
19  20.0  45.0  70.0   NaN
20  21.0  46.0  71.0   NaN
21  22.0  47.0  72.0   NaN
22  23.0  48.0  73.0   NaN
23  24.0  49.0  74.0   NaN
24  25.0  50.0  75.0   NaN

If you want to convert that back to a list of lists you can do something like this:

converted_list = []
for index, rows in df.iterrows():
    my_list = [rows[0], rows[1], rows[2], rows[3]]
    converted_list.append(my_list)

converted_list:

[[1.0, 26.0, 51.0, 76.0], [2.0, 27.0, 52.0, 77.0], [3.0, 28.0, 53.0, 78.0], [4.0, 29.0, 54.0, 79.0], [5.0, 30.0, 55.0, 80.0], [6.0, 31.0, 56.0, 81.0], [7.0, 32.0, 57.0, 82.0], [8.0, 33.0, 58.0, 83.0], [9.0, 34.0, 59.0, 84.0], [10.0, 35.0, 60.0, 85.0], [11.0, 36.0, 61.0, 86.0], [12.0, 37.0, 62.0, 87.0], [13.0, 38.0, 63.0, 88.0], [14.0, 39.0, 64.0, 89.0], [15.0, 40.0, 65.0, 90.0], [16.0, 41.0, 66.0, nan], [17.0, 42.0, 67.0, nan], [18.0, 43.0, 68.0, nan], [19.0, 44.0, 69.0, nan], [20.0, 45.0, 70.0, nan], [21.0, 46.0, 71.0, nan], [22.0, 47.0, 72.0, nan], [23.0, 48.0, 73.0, nan], [24.0, 49.0, 74.0, nan], [25.0, 50.0, 75.0, nan]]