问:
What is the correct way of saving 200 objects in the database using django-rest-framework?
I have a problem to solve this next week in an project. I have a model with 3 fields, 2 of them are foreign key to other models and the other field is a simple string field. In the front-end I'm going to present to the user only a checkbox and a observation field, a string field that can be blank or null. There will be a list of checkbox, around 200. Each one will be a object in the database. I don't want to make a post request for each one of them, would make the user experience really bad, 200 fields are already really bad, but necessary in this case.

So I would like suggestions, code example about the best approach to accomplish this. Here is the model.

```<code>class Person(models.Model):
    observation = models.TextField(blank=True, null=True)
    country = models.ForeignKey(Country, on_delete=models.PROTECT)
    user = models.ForeignKey(User, on_delete=models.PROTECT)
</code>```

I have a serializer and a ModelViewSet working for it with single request, a POST request of 1 object is working.

```<code>class PersonSet(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer
</code>```

I would like the front-end to send to the back-end a big list/array/object, not sure, and the back-end get this whole data in a single POST request and start the process to save it in the database. I was thinking If the best approach would be to iterate over this data and call the serializer on each one inside the view, or If I would implement a new type of serializer to make it.

I have read these two questions question1 and question2 about it, and it was really helpful, but I still have doubts. And also another problem, If a error occurs, like let's say the server goes down in the middle of the process, the connection gets interrupted, something happens, then my data would be saved or would be interrupted in the middle, I'm asking because I can't have this data separated, I need to garantee the whole 200 fields gets saved or 0 field gets saved.

答:
You can pass list of data to serializer and validate all of it at once with passing many argument to serializer

```<code>example_data = [
 {'country': 1, 'user': 1, 'observation': ''},
 {'country': 1, 'user': 2, 'observation': ''},
 {'country': 2, 'user': 1, 'observation': ''},
 {'country': 2, 'user': 2, 'observation': ''},
]

serializer = PersonSerializer(data=example_data, many=True)

if serializer.is_valid():
    serializer.save()
</code>```

It serializer will be valid if and only if all data instances are valid and will create object for each datum in data.

If you are concerned about failure at database level, you can always use atomic transaction in serializer's create method.

```<code>from django.db import transaction

class PersonSerializer(serializer.ModelSerializer):
    ...

    def create(self, validated_data):
        with transaction.atomic():
            return super().create(validated_data)
</code>```

Body:
I have a problem to solve this next week in an project. I have a model with 3 fields, 2 of them are foreign key to other models and the other field is a simple string field. In the front-end I'm going to present to the user only a checkbox and a observation field, a string field that can be blank or null. There will be a list of checkbox, around 200. Each one will be a object in the database. I don't want to make a post request for each one of them, would make the user experience really bad, 200 fields are already really bad, but necessary in this case.

So I would like suggestions, code example about the best approach to accomplish this. Here is the model.

class Person(models.Model):
    observation = models.TextField(blank=True, null=True)
    country = models.ForeignKey(Country, on_delete=models.PROTECT)
    user = models.ForeignKey(User, on_delete=models.PROTECT)

I have a serializer and a ModelViewSet working for it with single request, a POST request of 1 object is working.

class PersonSet(viewsets.ModelViewSet):
    queryset = Person.objects.all()
    serializer_class = PersonSerializer

I would like the front-end to send to the back-end a big list/array/object, not sure, and the back-end get this whole data in a single POST request and start the process to save it in the database. I was thinking If the best approach would be to iterate over this data and call the serializer on each one inside the view, or If I would implement a new type of serializer to make it.

I have read these two questions question1 and question2 about it, and it was really helpful, but I still have doubts. And also another problem, If a error occurs, like let's say the server goes down in the middle of the process, the connection gets interrupted, something happens, then my data would be saved or would be interrupted in the middle, I'm asking because I can't have this data separated, I need to garantee the whole 200 fields gets saved or 0 field gets saved.

Body:
You can pass list of data to serializer and validate all of it at once with passing many argument to serializer

example_data = [
 {'country': 1, 'user': 1, 'observation': ''},
 {'country': 1, 'user': 2, 'observation': ''},
 {'country': 2, 'user': 1, 'observation': ''},
 {'country': 2, 'user': 2, 'observation': ''},
]

serializer = PersonSerializer(data=example_data, many=True)

if serializer.is_valid():
    serializer.save()

It serializer will be valid if and only if all data instances are valid and will create object for each datum in data.

If you are concerned about failure at database level, you can always use atomic transaction in serializer's create method.

from django.db import transaction

class PersonSerializer(serializer.ModelSerializer):
    ...

    def create(self, validated_data):
        with transaction.atomic():
            return super().create(validated_data)


来源: stackexchange

问:
Multi Region not connected everywhere
I would like to be able to use cockroach DB in multiple DC. 20 zones and after that it will increase.

I would like to know if it's possible to have the data everywhere, but i dont want to be connected to every zones. I'm using multiple VPN and i'm limited of the numbers of VPN i can connected to a zone.

I created a multi region cluster. But all my region are connected together.

答:
All nodes in a CockroachDB cluster must be able to talk to each other directly. CockroachDB clusters will not function properly without this.

Please see the production checklist for details on how nodes can be configured in various scenarios.

ContentLicense: CC BY-SA 4.0

Title: Multi Region not connected everywhere


问:
Implementing multiple overloaded interfaces with `by`
I'd like to leverage by to build class APIs in a nice way. Is there any way to do something like the following?

```<code>interface Foo<T> {

    fun foo(t: T)
}

inline fun <reified T> createFoo() = object : Foo<T> {

    override fun foo(t: T) {
        // do stuff
    }
}

// This is an error
class StringIntFoo : Foo<String> by createFoo(), Foo<Int> by createFoo()

fun main(){
    val foo = StringIntFoo()
    foo.foo("")
    foo.foo(2)
}

// Doing it manually obviously isn't an issue
class ManualStringIntFoo {

    fun foo(t: String){

    }

    fun foo(t: Int){

    }
}

</code>```

Link to a playground.

It looks like the generated method end up having the same JVM signature. I was hoping the reified types would get around it. With only a single implementation it works just fine and the types look correct.

Is there some way of actually doing this? Whether or not the StringIntFoo is technically a Foo I suppose isn't important for the problem at hand. It would be cool to be able to construct classes in this way.

答:
Doing it manually doesn't work either if you try to actually implement the interfaces: ManualStringIntFoo : Foo<String>, Foo<Int> gives the same error as StringIntFoo.

So by can't help because it still compiles to class StringIntFoo : Foo<String>, Foo<Int> only setting the implementation of methods.

Body:
I'd like to leverage by to build class APIs in a nice way. Is there any way to do something like the following?

interface Foo<T> {

    fun foo(t: T)
}

inline fun <reified T> createFoo() = object : Foo<T> {

    override fun foo(t: T) {
        // do stuff
    }
}

// This is an error
class StringIntFoo : Foo<String> by createFoo(), Foo<Int> by createFoo()

fun main(){
    val foo = StringIntFoo()
    foo.foo("")
    foo.foo(2)
}

// Doing it manually obviously isn't an issue
class ManualStringIntFoo {

    fun foo(t: String){

    }

    fun foo(t: Int){

    }
}

Link to a <a href="https://play.kotlinlang.org/#eyJ2ZXJzaW9uIjoiMS4zLjMxIiwicGxhdGZvcm0iOiJqYXZhIiwiYXJncyI6IiIsImpzQ29kZSI6IiIsIm5vbmVNYXJrZXJzIjp0cnVlLCJ0aGVtZSI6ImlkZWEiLCJjb2RlIjoiLyoqXG4gKiBZb3UgY2FuIGVkaXQsIHJ1biwgYW5kIHNoYXJlIHRoaXMgY29kZS4gXG4gKiBwbGF5LmtvdGxpbmxhbmcub3JnIFxuICovXG5cbmludGVyZmFjZSBGb288VD4ge1xuXG4gICAgZnVuIGZvbyh0OiBUKVxufVxuXG5pbmxpbmUgZnVuIDxyZWlmaWVkIFQ+IGNyZWF0ZUZvbygpID0gb2JqZWN0IDogRm9vPFQ+IHtcblxuICAgIG92ZXJyaWRlIGZ1biBmb28odDogVCkge1xuICAgICAgICAvLyBkbyBzdHVmZlxuICAgIH1cbn1cblxuXG4vLyBUaGlzIGlzIGFuIGVycm9yXG5jbGFzcyBTdHJpbmdJbnRGb28gOiBGb288U3RyaW5nPiBieSBjcmVhdGVGb28oKSwgRm9vPEludD4gYnkgY3JlYXRlRm9vKClcblxuZnVuIG1haW4oKXtcbiAgICB2YWwgZm9vID0gU3RyaW5nSW50Rm9vKClcbiAgICBmb28uZm9vKFwiXCIpXG4gICAgZm9vLmZvbygyKVxufVxuXG5cbi8vIERvaW5nIGl0IG1hbnVhbGx5IG9idmlvdXNseSBpc24ndCBhbiBpc3N1ZVxuY2xhc3MgTWFudWFsU3RyaW5nSW50Rm9vIHtcbiAgICBcbiAgICBmdW4gZm9vKHQ6IFN0cmluZyl7XG4gICAgICAgIFxuICAgIH1cbiAgICBcbiAgICBmdW4gZm9vKHQ6IEludCl7XG4gICAgICAgIFxuICAgIH1cbn0ifQ==" rel="nofollow noreferrer">playground.

It looks like the generated method end up having the same JVM signature. I was hoping the reified types would get around it. With only a single implementation it works just fine and the types look correct.

Is there some way of actually doing this? Whether or not the StringIntFoo is technically a Foo I suppose isn't important for the problem at hand. It would be cool to be able to construct classes in this way.


问:
How to search for and perform calculations with groups with data.table
I have a column B_S with two values "S2" and "S1". S2 marks the boundary of each group and the original row for each group. S1 marks the possible items that need to be checked in terms of High column.

For example, I need to check if S1 High is greater than S2 High. I need to cycle through all the S1 entries and choose the row where S1 High is higher than S2 High and remove the rows where S1 High is not higher than S2.

I am not experienced enough with data.table to produce such as result.

Here is a sample of the data:

```<code>structure(list(Time = c("16/10/2014 09:19", "16/10/2014 09:20",
"16/10/2014 09:21", "16/10/2014 09:22", "17/12/2014 12:59", "17/12/2014   13:00",
    "17/12/2014 13:01", "17/12/2014 13:02"), High = c(1833.5, 1832.5,
1820.5, 1852.5, 1992, 1991.25, 2001.25, 2002.25), rn = c(77470L,
77469L, 77468L, 77467L, 17758L, 17757L, 17756L, 17755L), B_S = c("S2",
"S1", "S1", "S1", "S2", "S1", "S1", "S1")), row.names = c(NA,
-8L), class = c("data.table", "data.frame")
</code>```

Expected results:
For the 1st group (rows 1-4), row 1 and row 4 would be retained.

```<code> structure(list(Time = c("16/10/2014 09:19", "16/10/2014 09:22"
), High = c(1833.5, 1852.5), rn = c(77470L, 77467L), B_S = c("S2",
"S1")), class = c("data.table", "data.frame"), row.names = c(NA,
-2L)
</code>```

For the second group (rows 5-8) row 5 and row 7 would be retained.

```<code>    structure(list(Time = c("17/12/2014 12:59", "17/12/2014 13:01"
), High = c(1992, 2001.25), rn = c(17758L, 17756L), B_S = c("S2",
"S1")), class = c("data.table", "data.frame"), row.names = c(NA,
-2L)
</code>```

答:
An option would be group by cumulative sum of logical condition where 'B_S' is 'S2', then get the index of 'High' greater than or equal to the first value of 'High', select the first two positions, extract the row index (.I) and subset the rows based on that

```<code>i1 <- df1[,  .I[which((High >= first(High)))[1:2]], .(grp = cumsum(B_S == "S2"))]$V1
df1[i1]
#               Time    High    rn B_S
#1: 16/10/2014 09:19 1833.50 77470  S2
#2: 16/10/2014 09:22 1852.50 77467  S1
#3: 17/12/2014 12:59 1992.00 17758  S2
#4: 17/12/2014 13:01 2001.25 17756  S1
</code>```

Body:
I have a column B_S with two values "S2" and "S1". S2 marks the boundary of each group and the original row for each group. S1 marks the possible items that need to be checked in terms of High column.

For example, I need to check if S1 High is greater than S2 High. I need to cycle through all the S1 entries and choose the row where S1 High is higher than S2 High and remove the rows where S1 High is not higher than S2.

I am not experienced enough with data.table to produce such as result.

Here is a sample of the data:

structure(list(Time = c("16/10/2014 09:19", "16/10/2014 09:20",
"16/10/2014 09:21", "16/10/2014 09:22", "17/12/2014 12:59", "17/12/2014   13:00",
    "17/12/2014 13:01", "17/12/2014 13:02"), High = c(1833.5, 1832.5,
1820.5, 1852.5, 1992, 1991.25, 2001.25, 2002.25), rn = c(77470L,
77469L, 77468L, 77467L, 17758L, 17757L, 17756L, 17755L), B_S = c("S2",
"S1", "S1", "S1", "S2", "S1", "S1", "S1")), row.names = c(NA,
-8L), class = c("data.table", "data.frame")

Expected results:
For the 1st group (rows 1-4), row 1 and row 4 would be retained.

 structure(list(Time = c("16/10/2014 09:19", "16/10/2014 09:22"
), High = c(1833.5, 1852.5), rn = c(77470L, 77467L), B_S = c("S2",
"S1")), class = c("data.table", "data.frame"), row.names = c(NA,
-2L)

For the second group (rows 5-8) row 5 and row 7 would be retained.

    structure(list(Time = c("17/12/2014 12:59", "17/12/2014 13:01"
), High = c(1992, 2001.25), rn = c(17758L, 17756L), B_S = c("S2",
"S1")), class = c("data.table", "data.frame"), row.names = c(NA,
-2L)

Body:
An option would be group by cumulative sum of logical condition where 'B_S' is 'S2', then get the index of 'High' greater than or equal to the first value of 'High', select the first two positions, extract the row index (.I) and subset the rows based on that

i1 <- df1[,  .I[which((High >= first(High)))[1:2]], .(grp = cumsum(B_S == "S2"))]$V1
df1[i1]
#               Time    High    rn B_S
#1: 16/10/2014 09:19 1833.50 77470  S2
#2: 16/10/2014 09:22 1852.50 77467  S1
#3: 17/12/2014 12:59 1992.00 17758  S2
#4: 17/12/2014 13:01 2001.25 17756  S1


问:
How to overload equality operator?
In swift for example, you can overload the equality operator as follows:

Overloading equivalence (==) operator for custom class in Swift

```<code>class CustomClass: Equatable {
    var id = "my id"
}

func ==(left: CustomClass, right: CustomClass) -> Bool {
    return left.id == right.id
}
</code>```

Is there a way to do this in elixir?

What I want to achieve is this:

```<code>defmodule IP do
  @enforce_keys [:host, :port]
  defstruct [:host, :port, failures: 0, timeouts: 0]

  @type t :: %IP{host: String.t(), port: integer, failures: integer, timeouts: integer}

  # I want the == operator compare host and port but not failures and timeouts..
  def compare(l, r) do
    l.host == r.host && l.port == r.port
  end
end
</code>```

答:
While it’s not achievable with MapSet out of the box, one might easily implement this on their own. MapSet is a no-brainer, it’s a simple map under the hood.

```<code>defmodule IPs do
  defstruct m: %{}

  def put_new(%IPs{m: m}, %IP{host: host, port: port} = ip)
    %IPs{m | Map.put_new(m, {host, port}, {host, port}, ip)}
  end

  def values(%IPs{m: m}), do: Map.values(m)
end
</code>```

You can also implement Access behaviour, or delegate all the functions you need to the underlying map, or replicate the whole MapSet behaviour.

Title: How to overload equality operator?

Body:
In swift for example, you can overload the equality operator as follows:

Overloading equivalence (==) operator for custom class in Swift

class CustomClass: Equatable {
    var id = "my id"
}

func ==(left: CustomClass, right: CustomClass) -> Bool {
    return left.id == right.id
}

Is there a way to do this in elixir?

What I want to achieve is this:

defmodule IP do
  @enforce_keys [:host, :port]
  defstruct [:host, :port, failures: 0, timeouts: 0]

  @type t :: %IP{host: String.t(), port: integer, failures: integer, timeouts: integer}

  # I want the == operator compare host and port but not failures and timeouts..
  def compare(l, r) do
    l.host == r.host && l.port == r.port
  end
end

Body:
While it’s not achievable with MapSet out of the box, one might easily implement this on their own. MapSet is a no-brainer, it’s a simple map under the hood.

defmodule IPs do
  defstruct m: %{}

  def put_new(%IPs{m: m}, %IP{host: host, port: port} = ip)
    %IPs{m | Map.put_new(m, {host, port}, {host, port}, ip)}
  end

  def values(%IPs{m: m}), do: Map.values(m)
end

You can also implement Access behaviour, or delegate all the functions you need to the underlying map, or replicate the whole MapSet behaviour.


问:
Admob Integration on iPhone - Memory Leak Problem
I wonder if anyone can help with the following. I have integrated both iAds and AdMob into my app. However a user reported that the app crashes on the iPod Touch. Using Instruments in xCode I have managed to identify that something called "GOOGLE_SHUFFLE_RVS_User_waylonis_Code_afma1_googlmac_iPhone_GoogleAds_Signals_Protected_build_GoogleAdsSignals_build_Release_iphoneos_Google" is causing a memory leak of about 500 bytes everytime it is called.My ad refresh rate is set at 20 seconds so this happens every 20 seconds.

My code is as follows.

```<code>- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
if (self.bannerIsVisible)
{

    [UIView beginAnimations:@"animateAdBannerOff" context:NULL];
    // banner is visible and we move it out of the screen, due to connection issue
    banner.frame = CGRectOffset(banner.frame, 0, -90);
    [UIView commitAnimations];
    self.bannerIsVisible = NO;

}

    [self loadAdMobAd];
}

-(void)loadAdMobAd {

if (!bannerView_) {

CGRect adSize = CGRectMake (0,40,0,0);
adSize.size = GAD_SIZE_320x50;

bannerView_ = [[GADBannerView alloc] initWithFrame:adSize];
bannerView_.rootViewController = self;

bannerView_.adUnitID = MY_BANNER_UNIT_ID;

bannerView_.rootViewController = self;
[self.view addSubview:bannerView_];

// Initiate a generic request to load it with an ad.
[bannerView_ loadRequest:[GADRequest request]];

}
}
</code>```

The idea is that if an iAd is not available an AdMob ad is loaded instead.

Is there anything wrong with my code that could be causing the leak ?

Many thanks,

Martin

答:
You're alloc'ing bannerView_, adding it to the view, but not releasing it.

Try adding [bannerView_ release]; after the loadRequest line.

ContentLicense: CC BY-SA 3.0

Body:
I wonder if anyone can help with the following. I have integrated both iAds and AdMob into my app. However a user reported that the app crashes on the iPod Touch. Using Instruments in xCode I have managed to identify that something called "GOOGLE_SHUFFLE_RVS_User_waylonis_Code_afma1_googlmac_iPhone_GoogleAds_Signals_Protected_build_GoogleAdsSignals_build_Release_iphoneos_Google" is causing a memory leak of about 500 bytes everytime it is called.My ad refresh rate is set at 20 seconds so this happens every 20 seconds.

My code is as follows.

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
if (self.bannerIsVisible)
{

    [UIView beginAnimations:@"animateAdBannerOff" context:NULL];
    // banner is visible and we move it out of the screen, due to connection issue
    banner.frame = CGRectOffset(banner.frame, 0, -90);
    [UIView commitAnimations];
    self.bannerIsVisible = NO;

}

    [self loadAdMobAd];
}

-(void)loadAdMobAd {

if (!bannerView_) {

CGRect adSize = CGRectMake (0,40,0,0);
adSize.size = GAD_SIZE_320x50;

bannerView_ = [[GADBannerView alloc] initWithFrame:adSize];
bannerView_.rootViewController = self;

bannerView_.adUnitID = MY_BANNER_UNIT_ID;

bannerView_.rootViewController = self;
[self.view addSubview:bannerView_];

// Initiate a generic request to load it with an ad.
[bannerView_ loadRequest:[GADRequest request]];

}
}

The idea is that if an iAd is not available an AdMob ad is loaded instead.

Is there anything wrong with my code that could be causing the leak ?

Many thanks,

Martin


问:
Installation failed with message Invalid File

Installation failed with message Invalid File:
  K:\project\app\build\intermediates\split-apk\with_ImageProcessor\debug\slices\slice_0.apk.
  It is possible that this issue is resolved by uninstalling an existing
  version of the apk if it is present, and then re-installing.

WARNING: Uninstalling will remove the application data!

Do you want to uninstall the existing application?

i am running my project in android studio 2.3 beta 3 .

答:
follow some steps:

```<code>Clean Project
Rebuild Project
Invalidate Caches / Restart
</code>```

Now run your project. Hope it will work.

It's work for me.

Body:
follow some steps:

Clean Project
Rebuild Project
Invalidate Caches / Restart

Now run your project. Hope it will work.

It's work for me.


问:
How to render images using  tag in angular 7 project?
I am required to display an image in an angular 7 application using this information:

company {
logo: 'https://static.wixstatic.com / media / dc0d61_854a54df0f1049bcbb20e2f9a64236eb.png / v1 / fill / w_112, h_112, al_c, usm_0.66_1.00_0.01/ dc0d61_854a54df0f1049bcbb20e 2f9a64236eb.png',
}

To my understanding the logo value has to be provided in the src attribute of image tag in the template file as follows:

```<code><img width="300" alt="Company Logo" src="{{company.logo}}"/>
</code>```

First question: is this the rigth way to render an image in angular7 app?

Second question: should i see the image that is required to display when i visit the given http address (which I am not, rather I am getting 404 Not Found error when tried to visit this src adddress)

P.S I am not getting the image displayed when tried above

答:
In order to render the image, the images should be placed in the assets folder of the application. Rest if the image remains the same then yes, it's the correct way to render the images in the Angular7 app.

Try to place the image in the assets folder and update the path. It will work.

Title: How to render images using <img> tag in angular 7 project?

Body:
I am required to display an image in an angular 7 application using this information:

company {
logo: 'https://static.wixstatic.com / media / dc0d61_854a54df0f1049bcbb20e2f9a64236eb.png / v1 / fill / w_112, h_112, al_c, usm_0.66_1.00_0.01/ dc0d61_854a54df0f1049bcbb20e 2f9a64236eb.png',
}

To my understanding the logo value has to be provided in the src attribute of image tag in the template file as follows:

First question: is this the rigth way to render an image in angular7 app?

Second question: should i see the image that is required to display when i visit the given http address (which I am not, rather I am getting 404 Not Found error when tried to visit this src adddress)

P.S I am not getting the image displayed when tried above


问:
Creating vector of vectors (2D array) inside a class - Error:C++ requires a type specifier for all declarations
So I have procedurally programmed a way to integrate equations using the Runge-Kutta 4(RK4) method in C++. I am currently trying to create an RK4 class to add more functionality to my program. However, when I set up my 2D arrays in the class, I receive the "C++ requires a type specifier for all declarations" error, that I didn't receive in the original program.

At first, I was using namespace std;, however I came across an answer that said that that was bad programming practice, so I erased that line and called std::vector instead. I also made sure to include the vector library, to no avail.

```<code>#include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>

class RK4 {
public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i);
    //time-related stuff
    double dt = 0.01;
    int numtimes = 1000;

    int numvar = 3;
    double mu = 398589590898200.0;

    //setting up variables
    std::vector<vector<double> > position(numtimes,vector<double>(numvar));
    std::vector<vector<double> > velocity(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk4(numtimes,vector<double>(numvar));
</code>```

This is how I constructed the code in my original program, with no problem:

```<code>#include <iostream>
#include <ostream>
#include <cmath>
#include <vector>

using namespace std;

int main(){
// time related things
    //double t_i = 0; // initial time
    double dt = 0.01; // time step
    int numtimes = 10000; // how many steps taken

    vector<vector<double> > position(numtimes,vector<double>(numvar));
    vector<vector<double> > velocity(numtimes,vector<double>(numvar));

    vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    vector<vector<double> > vk4(numtimes,vector<double>(numvar));
}

</code>```

I'm not quite sure why this call worked in my original(procedural) program, but not in my current program.

答:
Move those std::vector initializations to the constructor of RK4 and use the member initialization list syntax to initialize them:

```<code>#include <iostream>
#include <vector>

class RK4
{
    double dt = 0.01;
    int numtimes = 1000;
    int numvar = 3;
    double mu = 398589590898200.0;

    //declaring vectors
    std::vector<std::vector<double> > position;
    std::vector<std::vector<double> > velocity;
    std::vector<std::vector<double> > rk1;
    std::vector<std::vector<double> > rk2;
    std::vector<std::vector<double> > rk3;
    std::vector<std::vector<double> > rk4;
    std::vector<std::vector<double> > vk1;
    std::vector<std::vector<double> > vk2;
    std::vector<std::vector<double> > vk3;
    std::vector<std::vector<double> > vk4;

   public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i) :
       position(numtimes, std::vector<double>(numvar)),
       velocity(numtimes, std::vector<double>(numvar)),
       rk1(numtimes, std::vector<double>(numvar)),
       rk2(numtimes, std::vector<double>(numvar)),
       rk3(numtimes, std::vector<double>(numvar)),
       rk4(numtimes, std::vector<double>(numvar)),
       vk1(numtimes, std::vector<double>(numvar)),
       vk2(numtimes, std::vector<double>(numvar)),
       vk3(numtimes, std::vector<double>(numvar)),
       vk4(numtimes, std::vector<double>(numvar))
    {}
};
</code>```

Given the order of the member variables, you can also do this (but this requires that position be declared before any of the other vectors):

```<code>#include <iostream>
#include <vector>

class RK4
{
    double dt = 0.01;
    int numtimes = 1000;
    int numvar = 3;
    double mu = 398589590898200.0;

    //declaring vectors
    std::vector<std::vector<double> > position;
    std::vector<std::vector<double> > velocity;
    std::vector<std::vector<double> > rk1;
    std::vector<std::vector<double> > rk2;
    std::vector<std::vector<double> > rk3;
    std::vector<std::vector<double> > rk4;
    std::vector<std::vector<double> > vk1;
    std::vector<std::vector<double> > vk2;
    std::vector<std::vector<double> > vk3;
    std::vector<std::vector<double> > vk4;

   public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i) :
       position(numtimes, std::vector<double>(numvar)),
       velocity(position),
       rk1(position),
       rk2(position),
       rk3(position),
       rk4(position),
       vk1(position),
       vk2(position),
       vk3(position),
       vk4(position)
    {}
};
</code>```

The reason why this works is that position and all the other vectors are exactly the same size and start out with the same values.  So it becomes a little easier just to initialize the other vectors with position.  But again, this requires position to be declared in the class before the other vectors for this to work.

Body:
So I have procedurally programmed a way to integrate equations using the Runge-Kutta 4(RK4) method in C++. I am currently trying to create an RK4 class to add more functionality to my program. However, when I set up my 2D arrays in the class, I receive the "C++ requires a type specifier for all declarations" error, that I didn't receive in the original program.

At first, I was using namespace std;, however I came across an answer that said that that was bad programming practice, so I erased that line and called std::vector instead. I also made sure to include the vector library, to no avail.

#include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>

class RK4 {
public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i);
    //time-related stuff
    double dt = 0.01;
    int numtimes = 1000;

    int numvar = 3;
    double mu = 398589590898200.0;

    //setting up variables
    std::vector<vector<double> > position(numtimes,vector<double>(numvar));
    std::vector<vector<double> > velocity(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    std::vector<vector<double> > vk4(numtimes,vector<double>(numvar));

This is how I constructed the code in my original program, with no problem:

#include <iostream>
#include <ostream>
#include <cmath>
#include <vector>

using namespace std;

int main(){
// time related things
    //double t_i = 0; // initial time
    double dt = 0.01; // time step
    int numtimes = 10000; // how many steps taken

    vector<vector<double> > position(numtimes,vector<double>(numvar));
    vector<vector<double> > velocity(numtimes,vector<double>(numvar));

    vector<vector<double> > rk1(numtimes,vector<double>(numvar));
    vector<vector<double> > rk2(numtimes,vector<double>(numvar));
    vector<vector<double> > rk3(numtimes,vector<double>(numvar));
    vector<vector<double> > rk4(numtimes,vector<double>(numvar));
    vector<vector<double> > vk1(numtimes,vector<double>(numvar));
    vector<vector<double> > vk2(numtimes,vector<double>(numvar));
    vector<vector<double> > vk3(numtimes,vector<double>(numvar));
    vector<vector<double> > vk4(numtimes,vector<double>(numvar));
}

I'm not quite sure why this call worked in my original(procedural) program, but not in my current program.

Body:
Move those std::vector initializations to the constructor of RK4 and use the member initialization list syntax to initialize them:

#include <iostream>
#include <vector>

class RK4
{
    double dt = 0.01;
    int numtimes = 1000;
    int numvar = 3;
    double mu = 398589590898200.0;

    //declaring vectors
    std::vector<std::vector<double> > position;
    std::vector<std::vector<double> > velocity;
    std::vector<std::vector<double> > rk1;
    std::vector<std::vector<double> > rk2;
    std::vector<std::vector<double> > rk3;
    std::vector<std::vector<double> > rk4;
    std::vector<std::vector<double> > vk1;
    std::vector<std::vector<double> > vk2;
    std::vector<std::vector<double> > vk3;
    std::vector<std::vector<double> > vk4;

   public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i) :
       position(numtimes, std::vector<double>(numvar)),
       velocity(numtimes, std::vector<double>(numvar)),
       rk1(numtimes, std::vector<double>(numvar)),
       rk2(numtimes, std::vector<double>(numvar)),
       rk3(numtimes, std::vector<double>(numvar)),
       rk4(numtimes, std::vector<double>(numvar)),
       vk1(numtimes, std::vector<double>(numvar)),
       vk2(numtimes, std::vector<double>(numvar)),
       vk3(numtimes, std::vector<double>(numvar)),
       vk4(numtimes, std::vector<double>(numvar))
    {}
};

Given the order of the member variables, you can also do this (but this requires that position be declared before any of the other vectors):

#include <iostream>
#include <vector>

class RK4
{
    double dt = 0.01;
    int numtimes = 1000;
    int numvar = 3;
    double mu = 398589590898200.0;

    //declaring vectors
    std::vector<std::vector<double> > position;
    std::vector<std::vector<double> > velocity;
    std::vector<std::vector<double> > rk1;
    std::vector<std::vector<double> > rk2;
    std::vector<std::vector<double> > rk3;
    std::vector<std::vector<double> > rk4;
    std::vector<std::vector<double> > vk1;
    std::vector<std::vector<double> > vk2;
    std::vector<std::vector<double> > vk3;
    std::vector<std::vector<double> > vk4;

   public:
    RK4(double x_i, double y_i, double z_i, double vx_i, double vy_i, double vz_i) :
       position(numtimes, std::vector<double>(numvar)),
       velocity(position),
       rk1(position),
       rk2(position),
       rk3(position),
       rk4(position),
       vk1(position),
       vk2(position),
       vk3(position),
       vk4(position)
    {}
};

The reason why this works is that position and all the other vectors are exactly the same size and start out with the same values.  So it becomes a little easier just to initialize the other vectors with position.  But again, this requires position to be declared in the class before the other vectors for this to work.


问:
SQL INSERT INTO - Duplicates still exist (How to modify insert into?)
I have 3 MariaDB-SQL tables and I want to insert some data:

Restaurant

ID_Restaurant (Primary Key, Auto Increment)

RestaurantName

Location

Restaurant_has_Request

ID_Restaurant(Foreign Key)

ID_Request (Foreign Key)

Request

ID_Request (Primary Key, Auto Increment)

Date

Adults

One Restaurant has 0 or infinity Requests. One Request can have 1 or infinity Restaurants.

I am iterating through a request site for only one Request. That means I want to treat first one Request and then I save the related one or more Restaurants. After I have done this another Request will be treated and so on.

I have the following Python Code for inserting the data:

```<code>cursor.execute('insert into Restaurant(RestaurantName, Location) values(%s, %s)',(RestaurantName, Location))

# ID from last insert
ID_Restaurant_Cache = cursor.lastrowid

cursor.execute('insert into Request(Date, Adults) values(%s, %s)',(Date, Adults))

# ID from last insert
ID_Request_Cache = cursor.lastrowid

cursor.execute('insert into Restaurant_has_Request(ID_Restaurant, ID_Request) values(%s, %s)',(ID_Restaurant_Cache, ID_Request_Cache))
</code>```

The problem is that I have still duplicates... How can I modify the Python code that I use the existing entry from a Restaurant, when it already exists (RestaurantName & Location is already in the database)?
I have also duplicates for the Request. I want to use the same Request ID for one iteration and then I want to use another Request ID.

Thank you :)

答:
Please provide SHOW CREATE TABLE.

Shouldn't Restaurant_has_Request have

```<code>PRIMARY KEY(ID_restaurant, ID_request),
INDEX(ID_request, ID_restaurant)
</code>```

Body:
I have 3 MariaDB-SQL tables and I want to insert some data:

Restaurant

ID_Restaurant (Primary Key, Auto Increment)

RestaurantName

Location

Restaurant_has_Request

ID_Restaurant(Foreign Key)

ID_Request (Foreign Key)

Request

ID_Request (Primary Key, Auto Increment)

Date

Adults

One Restaurant has 0 or infinity Requests. One Request can have 1 or infinity Restaurants.

I am iterating through a request site for only one Request. That means I want to treat first one Request and then I save the related one or more Restaurants. After I have done this another Request will be treated and so on.

I have the following Python Code for inserting the data:

cursor.execute('insert into Restaurant(RestaurantName, Location) values(%s, %s)',(RestaurantName, Location))

# ID from last insert
ID_Restaurant_Cache = cursor.lastrowid

cursor.execute('insert into Request(Date, Adults) values(%s, %s)',(Date, Adults))

# ID from last insert
ID_Request_Cache = cursor.lastrowid

cursor.execute('insert into Restaurant_has_Request(ID_Restaurant, ID_Request) values(%s, %s)',(ID_Restaurant_Cache, ID_Request_Cache))

The problem is that I have still duplicates... How can I modify the Python code that I use the existing entry from a Restaurant, when it already exists (RestaurantName & Location is already in the database)?
I have also duplicates for the Request. I want to use the same Request ID for one iteration and then I want to use another Request ID.

Thank you :)

Body:
Please provide SHOW CREATE TABLE.

Shouldn't Restaurant_has_Request have

PRIMARY KEY(ID_restaurant, ID_request),
INDEX(ID_request, ID_restaurant)


问:
ASP.NET Parser Error only on local machine
I am getting the common ASP.NET YSOD error. Here is the full error page as requested:

```<code>Server Error in '/' Application.
--------------------------------------------------------------------------------

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'WebApplication1.WebForm1'.

Source Error:

Line 1:  <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Source File: /WebForm1.aspx    Line: 1

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
</code>```

But only on my local machine. I tried the option to Use Local IIS Web Server and this gives the same error.

Everything I have read says 'just re-compile' I have done this but it makes no difference.

I am using VS2010.

Does anyone know what the cause of this is?

答: You must have Rebuild Solution before you have to Start Debugging or Browse Application.</p>

Body:
I am getting the common ASP.NET YSOD error. Here is the full error page as requested:

Server Error in '/' Application.
--------------------------------------------------------------------------------

Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Could not load type 'WebApplication1.WebForm1'.

Source Error:

Line 1:  <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication1.WebForm1" %>
Line 2:
Line 3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Source File: /WebForm1.aspx    Line: 1

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272

But only on my local machine. I tried the option to Use Local IIS Web Server and this gives the same error.

Everything I have read says 'just re-compile' I have done this but it makes no difference.

I am using VS2010.

Does anyone know what the cause of this is?


问:
Build trigger in Jenkins when a specific folder changes
Configure Jenkins: Where it should trigger only when a particular folder changes.

For example:
In a file directory: Sample/Folder/ there are 3 sub folders: F1, F2, F3.
The jenkins build should be triggered when F3 is changed and should not include F1, F2 in the build. These 3 folders should be independent in regards to the build but should be in the same file directory.
Also is there a way we can monitor the changes in the folders?

答:
WIth Jenkins pipelines, start your job by querying the build changeset, as in here.

See if an when { anyOf { changeset directive is enough to build if and only when the changeset includes a specific element.

See the pipeline syntax built-in condition

changeset

Execute the stage if the build’s SCM changeset contains one or more files matching the given string or glob. Example: when { changeset "**/*.js" }

As noted by PFudd in the comments:

WARNING: When you create a new branch, the changeset will be empty on the first build. It's also empty if you click "Rebuild".
See "Jenkins Pipeline how to check for an empty changelog"

The Jenkins team is aware of this, and due to the complexity of Git, they don't intend to fix it, because there is no universally-correct way to determine the right parent to compare with: see issue JENKINS-26354.

Reference: stackoverflow.com/questions/70307972/…


问:
SQL server updating records where they exist
```<code>update [db2].dbo.tblASDF
set deviceID = (select db1.deviceID FROM [database1].[dbo].[device] as db1,[database2].[dbo].[device] as db2 where db1.name = db2.name)
where exists (select * FROM [database1].[dbo].[device] as db1,[database2].[dbo].[device] as db2 where db1.name = db2.name)
</code>```

Question/Statement1: It's not important that I'm selecting * in the "where exists", what's important is that my "where db1.name = db2.name" clause is returning the rows which meet this condition, because these rows hold the unique keys to help my update to operate? IE, whether I've selected one or 20 columns is irrelevant.

Question2: I'm pulling from 2 databases, db1 and db2. Does the "exists" know to use the unique keys from db1/db2 to update db2's tblASDF.deviceID column? ie, it doesn't matter that there are 2 sets of unique keys (the ones for the db1, and the ones for the db2) returned from the "where db1.name = db2.name"?

答:
Q1 Correct.
I always do this:

```<code>if exists (select 1 from attachments WHERE ID<6) ...
</code>```

To the reader, it's clearly not relevant WHAT is being returned. In this case if there are any records with an ID of less than 6, then something exists.

Q2
The WHERE Exists clause will resolve to either zero records or more than zero records.
In the first case, zero records, the UPDATE will do nothing. Because nothing exists.
In the second case, you can replace WHERE EXISTS... with nothing.
Your query resolves to

```<code>update [db2].dbo.tblASDF
set deviceID =  (select db1.deviceID FROM [database1].[dbo].[device] as db1
 ,[database2].[dbo].[device] as db2  where db1.name = db2.name)
</code>```

The inner query will not return two sets of unique keys. It will return one set of db1.deviceID IDs where the name is the same in each table.
The update will only take place where DB2's DeviceID column in its tblASDF table contains an ID that exists in DB1's equivalent table db1.deviceID in db1.tblASDF.

It will ignore the db2.deviceID column so the IDs in that field are irrelevant.

It must be said that duplicating the two identical pieces of T-SQL is unnessary and it makes the code harder to read. Often I come across SQL with a very, very subtle difference between the two pieces of code, (eg a 1 instead of a 2) thereby introducing a bug.

The "join" is being performed by the WHERE db1.name = db2.name clause

Body:
update [db2].dbo.tblASDF
set deviceID = (select db1.deviceID FROM [database1].[dbo].[device] as db1,[database2].[dbo].[device] as db2 where db1.name = db2.name)
where exists (select * FROM [database1].[dbo].[device] as db1,[database2].[dbo].[device] as db2 where db1.name = db2.name)

Question/Statement1: It's not important that I'm selecting * in the "where exists", what's important is that my "where db1.name = db2.name" clause is returning the rows which meet this condition, because these rows hold the unique keys to help my update to operate? IE, whether I've selected one or 20 columns is irrelevant.

Question2: I'm pulling from 2 databases, db1 and db2. Does the "exists" know to use the unique keys from db1/db2 to update db2's tblASDF.deviceID column? ie, it doesn't matter that there are 2 sets of unique keys (the ones for the db1, and the ones for the db2) returned from the "where db1.name = db2.name"?

Body:
Q1 Correct.
I always do this:

if exists (select 1 from attachments WHERE ID<6) ...

To the reader, it's clearly not relevant WHAT is being returned. In this case if there are any records with an ID of less than 6, then something exists.

Q2
The WHERE Exists clause will resolve to either zero records or more than zero records.
In the first case, zero records, the UPDATE will do nothing. Because nothing exists.
In the second case, you can replace WHERE EXISTS... with nothing.
Your query resolves to

update [db2].dbo.tblASDF
set deviceID =  (select db1.deviceID FROM [database1].[dbo].[device] as db1
 ,[database2].[dbo].[device] as db2  where db1.name = db2.name)

The inner query will not return two sets of unique keys. It will return one set of db1.deviceID IDs where the name is the same in each table.
The update will only take place where DB2's DeviceID column in its tblASDF table contains an ID that exists in DB1's equivalent table db1.deviceID in db1.tblASDF.

It will ignore the db2.deviceID column so the IDs in that field are irrelevant.

It must be said that duplicating the two identical pieces of T-SQL is unnessary and it makes the code harder to read. Often I come across SQL with a very, very subtle difference between the two pieces of code, (eg a 1 instead of a 2) thereby introducing a bug.

The "join" is being performed by the WHERE db1.name = db2.name clause


问:
Calling array values based on DOM return
Return a string based on pulled dom elements

I have an object storing months and their index (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc}

The user can type something like jan or jan,feb,march and I want a string returned as 1 or 1,2,3 (which I use for a get call elsewhere) but haven't been able to do this, ive tried using all sorts of crazy loops to no avail, from incorrect reading to always reading last index, if the user inputs 1,2,3 that should also work.

The input values as simply called using ${document.getElementById('monthInput').value}

```<code>User Input Example #1: jan,feb,dec
User Input Output #1: 1,2,12
</code>```

```<code>User Input Example #2: 1,2,5
User Input Output #2: 1,2,5
</code>```

How can I do this?

答:
I admit to not understanding why you would accept user input in such odd formats. The only way to transform user input that matches no specific syntax/format is to use a manually created matrix.

In the inputMap below you would need to list each user input and the string value that it should be translated to:

const inputMap = {
  "jan": "1",
  "feb": "2",
  "march": "3",
  1: "1",
  2: "2",
  3: "3",
  "dec": 12,
  5: "5"
}

const input1 = "jan,feb,dec"
const input2 = "1,2,5"

const mapInput = inputString => inputString.split(",").map(i => inputMap[i]).join(",")

console.log(mapInput(input1))
console.log(mapInput(input2))```

Body:
Return a string based on pulled dom elements

I have an object storing months and their index (not dates) monthList = {"jan" : "1", "feb" : "2". etc: etc}

The user can type something like jan or jan,feb,march and I want a string returned as 1 or 1,2,3 (which I use for a get call elsewhere) but haven't been able to do this, ive tried using all sorts of crazy loops to no avail, from incorrect reading to always reading last index, if the user inputs 1,2,3 that should also work.

The input values as simply called using ${document.getElementById('monthInput').value}

User Input Example #1: jan,feb,dec
User Input Output #1: 1,2,12

User Input Example #2: 1,2,5
User Input Output #2: 1,2,5

How can I do this?


问:
Creating a mock library if an optional library can't be loaded--an acceptable practice?
I want to print in Python 3.6 using colored if that package is available, like so:

print('{}Hello, world!{}'.format(colored.fg(1), colored.attr(0)))
```

<p>However, I want to make <code>colored</code> optional if possible, while still printing any text that would optionally be stylized. Simply creating a wrapper function for printing seems inadequate, due to the multiple ways you can use <code>colored</code>, such as <code>colored.stylize()</code> and adding colors together:</p>

<pre class="lang-py prettyprint-override"><code>cheerful = colored.fg('cyan') + colored.attr('bold')
print(colored.stylize("Hello, world!", cheerful, colored.attr("underlined"))
</code>```

Although mocking is usually used for testing, is it acceptable practice to create a mock library to use if the optional library isn't available? Something like so, in a module called colored_mock (mocking as described in this question):

from unittest.mock import Mock
import sys
import types

module_name = 'mock_colored'
mock_colored = types.ModuleType(module_name)
sys.modules[module_name] = mock_colored

# following the original definition
def stylize(string, styles, reset=True):
    # return the original string so it can be used
    return string

mock_colored.stylize = Mock(name=module_name+'.stylize', side_effect=stylize)

# and so on until most of the module attributes and functions are covered
```

<p>This way I can do:</p>

<pre class="lang-py prettyprint-override"><code>try:
   import colored
except ImportError:
    from .mock_colored import mock_colored as colored
</code>```

答:
Using a Mock suggests you are testing. If this is your own code, it might be better to have a wrapper for stylized plus any other colored methods you are importing:

```<code>colored_imported = False
try:
    import colored
    colored_imported = True
except ImportError:
    pass

def stylized(string, styles, reset=True):
    if colored_imported:
        return colored.stylized(string, styles, reset=reset)
    else:
        return string
</code>```

This will help spot problems caused by misspelt methods (e.g., stylised) or having too few parameters. This approach should also make your code easier to understand and debug.

Body:
I want to print in Python 3.6 using colored if that package is available, like so:

print('{}Hello, world!{}'.format(colored.fg(1), colored.attr(0)))

However, I want to make colored optional if possible, while still printing any text that would optionally be stylized. Simply creating a wrapper function for printing seems inadequate, due to the multiple ways you can use colored, such as colored.stylize() and adding colors together:

cheerful = colored.fg('cyan') + colored.attr('bold')
print(colored.stylize("Hello, world!", cheerful, colored.attr("underlined"))

Although mocking is usually used for testing, is it acceptable practice to create a mock library to use if the optional library isn't available? Something like so, in a module called colored_mock (mocking as described in this question):

from unittest.mock import Mock
import sys
import types

module_name = 'mock_colored'
mock_colored = types.ModuleType(module_name)
sys.modules[module_name] = mock_colored

# following the original definition
def stylize(string, styles, reset=True):
    # return the original string so it can be used
    return string

mock_colored.stylize = Mock(name=module_name+'.stylize', side_effect=stylize)

# and so on until most of the module attributes and functions are covered

This way I can do:

try:
   import colored
except ImportError:
    from .mock_colored import mock_colored as colored

Body:
Using a Mock suggests you are testing. If this is your own code, it might be better to have a wrapper for stylized plus any other colored methods you are importing:

colored_imported = False
try:
    import colored
    colored_imported = True
except ImportError:
    pass

def stylized(string, styles, reset=True):
    if colored_imported:
        return colored.stylized(string, styles, reset=reset)
    else:
        return string

This will help spot problems caused by misspelt methods (e.g., stylised) or having too few parameters. This approach should also make your code easier to understand and debug.


问:
How to deposit ether to an account using solidity and web3?
I am building a sample smart contract . I am trying to deposit ether from 1 account to another but the issue is amount is deducted from the sender's account but not able to deposit to receiver's account.

Here is my contract code :

```<code>pragma solidity ^0.5.0;

 contract ApprovalContract{
address public sender;
address public receiver;

function deposit(address _receiver) external payable {
    require(msg.value > 0);
    sender = msg.sender;
    receiver = _receiver;
     address payable _rec = receiver.make_payable();
     _rec.transfer(address(this).balance);
}

using address_make_payable for address;

}
 library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
  return address(uint160(x));
 }
 }
</code>```

Here is my web3 code :

```<code> let ApprovalContract = new web3.eth.Contract(
    abi,
    "0xABd4495e3afc9E61Bbbf54620587aB4B48CEd7d3" //contract address
  );

ApprovalContract.methods
      .deposit("0xF33ca58CbD25bC0fFe5546Dc494E5c61C8D7fFc3")
      .send(
        {
          from: "0x7186ffcf5ea764257fdbaefccb9472f054495d11",
          gas: 100000,
          value: web3.utils.toWei("1", "ether")
        },
        (err, res) =>
          err
            ? console.log(`error: ${err}`)
            : console.log(`Success: ${res}`)
      );
</code>```

答:
Just add some mapping in your smart contract, like this mapping( address => uint256 ) balance and this is fixed smart contract for you :

```<code>pragma solidity ^0.5.0;
contract ApprovalContract{
    address payable owner = msg.sender;
    mapping(address => uint256) balance;
    function deposit() external payable {
            require(msg.value > 0);
            sender = msg.sender;
            deposited = msg.value;
            receiver = owner;
            balance[sender] = deposited;
            receiver.transfer(deposited);
    }
}
</code>```

Body:
I am building a sample smart contract . I am trying to deposit ether from 1 account to another but the issue is amount is deducted from the sender's account but not able to deposit to receiver's account.

Here is my contract code :

pragma solidity ^0.5.0;

 contract ApprovalContract{
address public sender;
address public receiver;

function deposit(address _receiver) external payable {
    require(msg.value > 0);
    sender = msg.sender;
    receiver = _receiver;
     address payable _rec = receiver.make_payable();
     _rec.transfer(address(this).balance);
}

using address_make_payable for address;

}
 library address_make_payable {
function make_payable(address x) internal pure returns (address payable) {
  return address(uint160(x));
 }
 }

Here is my web3 code :

 let ApprovalContract = new web3.eth.Contract(
    abi,
    "0xABd4495e3afc9E61Bbbf54620587aB4B48CEd7d3" //contract address
  );

ApprovalContract.methods
      .deposit("0xF33ca58CbD25bC0fFe5546Dc494E5c61C8D7fFc3")
      .send(
        {
          from: "0x7186ffcf5ea764257fdbaefccb9472f054495d11",
          gas: 100000,
          value: web3.utils.toWei("1", "ether")
        },
        (err, res) =>
          err
            ? console.log(`error: ${err}`)
            : console.log(`Success: ${res}`)
      );

Body:
Just add some mapping in your smart contract, like this mapping( address => uint256 ) balance and this is fixed smart contract for you :

pragma solidity ^0.5.0;
contract ApprovalContract{
    address payable owner = msg.sender;
    mapping(address => uint256) balance;
    function deposit() external payable {
            require(msg.value > 0);
            sender = msg.sender;
            deposited = msg.value;
            receiver = owner;
            balance[sender] = deposited;
            receiver.transfer(deposited);
    }
}


问:
Readonly PropertyGrid
I'm using a PropertyGrid in an application I am writing to allow users to view and sometimes edit instances of my objects. Sometimes the user may have a file open in read/write mode where they can make changes to the file through the property grid. In other cases they may have a file open in read only mode, and should not be able to make any changes to the objects through the PropetyGrid. My classes also have dynamic properties which are returned by implementing ICustomTypeDescriptor. Which is why I really want to take advantage of the built in flexibility of a PropertyGrid control.

There doesn't seem to be an easy way to set a Property-grid to a read only mode. If I disable a PropertyGrid this also prevents the user from scrolling the list. So I'm thinking the best way to do this is to add ReadOnlyAttributes to the properties at run-time. Is there some other way?

答:
I ran into this one.  I wanted a control that was read only but not grayed out.

Inherit from the property grid control and create your own read only version by adding the following code to override key presses

```<code>#Region "Non-greyed read only support"

Private isReadOnly As Boolean
Public Property [ReadOnly]() As Boolean
    Get
        Return Me.isReadOnly
    End Get
    Set(ByVal value As Boolean)
        Me.isReadOnly = value
    End Set
End Property

Protected Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean
    If Me.isReadOnly Then Return True
    Return MyBase.ProcessDialogKey(keyData)
End Function

Public Function PreFilterMessage(ByRef m As Message) As Boolean
    If m.Msg = &H204 Then 'WM_RBUTTONDOWN
        If Me.isReadOnly Then Return True
    End If
    Return False
End Function
#End Region
</code>```

ContentLicense: CC BY-SA 2.5

Title: Readonly PropertyGrid

Body:
I ran into this one.  I wanted a control that was read only but not grayed out.

Inherit from the property grid control and create your own read only version by adding the following code to override key presses

#Region "Non-greyed read only support"

Private isReadOnly As Boolean
Public Property [ReadOnly]() As Boolean
    Get
        Return Me.isReadOnly
    End Get
    Set(ByVal value As Boolean)
        Me.isReadOnly = value
    End Set
End Property

Protected Overrides Function ProcessDialogKey(ByVal keyData As Keys) As Boolean
    If Me.isReadOnly Then Return True
    Return MyBase.ProcessDialogKey(keyData)
End Function

Public Function PreFilterMessage(ByRef m As Message) As Boolean
    If m.Msg = &H204 Then 'WM_RBUTTONDOWN
        If Me.isReadOnly Then Return True
    End If
    Return False
End Function
#End Region


问:
What's the difference between & and && in JavaScript?
What's the difference between & and && in JavaScript?

Example code:

```<code>var first  = 123;
var second = false;
var third  = 456;
var fourth = "abc";
var fifth  = true;
alert(first & second); // 0
alert(first & third);  // 72
alert(first & fourth); // 0
alert(first & fifth);  // 1

alert(first && second); // false
alert(first && third);  // 456
alert(first && fourth); // abc
alert(first && fifth);  // true
</code>```

It seems like && is a logical and which gives me always the second value if both are true.

But what is &?

(By the way, && seems to be and in Python; & seems to be & in Python)

答:
With all the lofty, detailed insights throughout, they have mostly missed the truth that there is a conditional evaluation where ONLY the single & will work. The practical layman's answer that solved my head beating on an IF statement string of MULTIPLE chained && each !== to a condition was causing FAILURE and needed to legitimately use the single &. I thank Jake Wayne (and Russ) for their unfairly downvoted answer that got it right given that where there is more than one && that !== it has already ceased its evaluation and proceeds no further after the first evaluation is found ==!. With the && it thinks its job is done after the first evaluation shows !== [eg. false]. My failing code was

```<code>IF ((sessionStorage.myLable !== "LableStringA") && (sessionStorage.myLable !== "LableStringB") && (sessionStorage.myLableZ !== "LableStringA") && (sessionStorage.myLableZ !== "LableStringB")) { ...)
</code>```

Here, properly substituting and using a single & for the && it was both practically in the real world and technically the correct answer. Thank you again Jake Wayne (and Russ) for the insight and understanding of code.

Body:
What's the difference between & and && in JavaScript?

Example code:

var first  = 123;
var second = false;
var third  = 456;
var fourth = "abc";
var fifth  = true;
alert(first & second); // 0
alert(first & third);  // 72
alert(first & fourth); // 0
alert(first & fifth);  // 1

alert(first && second); // false
alert(first && third);  // 456
alert(first && fourth); // abc
alert(first && fifth);  // true

It seems like && is a logical and which gives me always the second value if both are true.

But what is &?

(By the way, && seems to be and in Python; & seems to be & in Python)

Body:
With all the lofty, detailed insights throughout, they have mostly missed the truth that there is a conditional evaluation where ONLY the single & will work. The practical layman's answer that solved my head beating on an IF statement string of MULTIPLE chained && each !== to a condition was causing FAILURE and needed to legitimately use the single &. I thank Jake Wayne (and Russ) for their unfairly downvoted answer that got it right given that where there is more than one && that !== it has already ceased its evaluation and proceeds no further after the first evaluation is found ==!. With the && it thinks its job is done after the first evaluation shows !== [eg. false]. My failing code was

IF ((sessionStorage.myLable !== "LableStringA") && (sessionStorage.myLable !== "LableStringB") && (sessionStorage.myLableZ !== "LableStringA") && (sessionStorage.myLableZ !== "LableStringB")) { ...)

Here, properly substituting and using a single & for the && it was both practically in the real world and technically the correct answer. Thank you again Jake Wayne (and Russ) for the insight and understanding of code.


问:
How to map char values to int using enum
I am trying to map some chars in a string to some integer values using enum. Please tell where am I going wrong?</p>

```<code>enum moves{U,R,D,L};
class Solution {
public:
    bool judgeCircle(string moves) {

// moves is a string having values like ULLDDRR, ULRD, UULLDDRR
        int X[] = {0,1,0,-1};
        int Y[] = {1,0,-1,0};

// while iterating the string if I get a 'U' , I want to use it as an index
//with  U representing the 0th index, R as index=1 and so on.. as specified
 //in the enum

        int x=0 , y=0;
        enum moves ind;
        for( int i = 0 ; i < moves.length() ; i++ ) {
            ind = moves[i];  // but this line here gives error
            x += X[ind];
            y += Y[ind];
        }

        if(!x && !y)
            return true;
        else
            return false;
    }
};
</code>```

答:
I would drop the idea with an enum because I feel it has no use for the actual problem – to map characters to navigation moves. For this, I would use a std::map or a std::unordered_map. (Considering, that there are 4 entries only, the performance difference is probably hard to measure.)

While I was preparing a sample code, πάντα ῥεῖ gave a similar hint. Though, I would even recommend to bundle x and y of moves together:

```<code>#include <map>
#include <iomanip>
#include <iostream>

// bundle x and y for a move (which needs both of them)
struct Move {
  int dx, dy;
};

// a type to map chars to moves
using MoveMap = std::map<char, Move>;

// a pre-defined move map
static const MoveMap mapMoves = {
    { 'U', { 0, 1 } },
    { 'R', { 1, 0 } },
    { 'D', { 0, -1 } },
    { 'L', { -1, 0 } }
};

/* a function to use move map
 *
 * id ... one of U R D L
 * x, y ... coordinates (update)
 * return: true if successful, (false e.g. for wrong id)
 */
bool move(char id, int &x, int &y)
{
  const MoveMap::const_iterator iter = mapMoves.find(id);
  return iter != mapMoves.end()
    ? x += iter->second.dx, y += iter->second.dy, true
    : false;
}

// check it out:

int main()
{
  int x = 0, y = 0;
  const char test[] = "ULLDDRR, ULRD, UULLDDRR";
  for (char id : test) {
    std::cout << "(" << x << ", " << y << "): "
      << "Move '" << id << "' -> ";
    if (move(id, x, y)) {
      std::cout << "(" << x << ", " << y << ")\n";
    } else std::cout << "failed\n";
  }
  return 0;
}
</code>```

Output:

(0, 0): Move 'U' -> (0, 1)
(0, 1): Move 'L' -> (-1, 1)
(-1, 1): Move 'L' -> (-2, 1)
(-2, 1): Move 'D' -> (-2, 0)
(-2, 0): Move 'D' -> (-2, -1)
(-2, -1): Move 'R' -> (-1, -1)
(-1, -1): Move 'R' -> (0, -1)
(0, -1): Move ',' -> failed
(0, -1): Move ' ' -> failed
(0, -1): Move 'U' -> (0, 0)
(0, 0): Move 'L' -> (-1, 0)
(-1, 0): Move 'R' -> (0, 0)
(0, 0): Move 'D' -> (0, -1)
(0, -1): Move ',' -> failed
(0, -1): Move ' ' -> failed
(0, -1): Move 'U' -> (0, 0)
(0, 0): Move 'U' -> (0, 1)
(0, 1): Move 'L' -> (-1, 1)
(-1, 1): Move 'L' -> (-2, 1)
(-2, 1): Move 'D' -> (-2, 0)
(-2, 0): Move 'D' -> (-2, -1)
(-2, -1): Move 'R' -> (-1, -1)
(-1, -1): Move 'R' -> (0, -1)
(0, -1): Move '' -> failed
```

Live Demo on coliru

Body:
I am trying to map some chars in a string to some integer values using enum. Please tell where am I going wrong?

enum moves{U,R,D,L};
class Solution {
public:
    bool judgeCircle(string moves) {

// moves is a string having values like ULLDDRR, ULRD, UULLDDRR
        int X[] = {0,1,0,-1};
        int Y[] = {1,0,-1,0};

// while iterating the string if I get a 'U' , I want to use it as an index
//with  U representing the 0th index, R as index=1 and so on.. as specified
 //in the enum

        int x=0 , y=0;
        enum moves ind;
        for( int i = 0 ; i < moves.length() ; i++ ) {
            ind = moves[i];  // but this line here gives error
            x += X[ind];
            y += Y[ind];
        }

        if(!x && !y)
            return true;
        else
            return false;
    }
};

Body:
I would drop the idea with an enum because I feel it has no use for the actual problem – to map characters to navigation moves. For this, I would use a std::map or a std::unordered_map. (Considering, that there are 4 entries only, the performance difference is probably hard to measure.)

While I was preparing a sample code, πάντα ῥεῖ gave a similar hint. Though, I would even recommend to bundle x and y of moves together:

#include <map>
#include <iomanip>
#include <iostream>

// bundle x and y for a move (which needs both of them)
struct Move {
  int dx, dy;
};

// a type to map chars to moves
using MoveMap = std::map<char, Move>;

// a pre-defined move map
static const MoveMap mapMoves = {
    { 'U', { 0, 1 } },
    { 'R', { 1, 0 } },
    { 'D', { 0, -1 } },
    { 'L', { -1, 0 } }
};

/* a function to use move map
 *
 * id ... one of U R D L
 * x, y ... coordinates (update)
 * return: true if successful, (false e.g. for wrong id)
 */
bool move(char id, int &x, int &y)
{
  const MoveMap::const_iterator iter = mapMoves.find(id);
  return iter != mapMoves.end()
    ? x += iter->second.dx, y += iter->second.dy, true
    : false;
}

// check it out:

int main()
{
  int x = 0, y = 0;
  const char test[] = "ULLDDRR, ULRD, UULLDDRR";
  for (char id : test) {
    std::cout << "(" << x << ", " << y << "): "
      << "Move '" << id << "' -> ";
    if (move(id, x, y)) {
      std::cout << "(" << x << ", " << y << ")\n";
    } else std::cout << "failed\n";
  }
  return 0;
}

Output:

(0, 0): Move 'U' -> (0, 1)
(0, 1): Move 'L' -> (-1, 1)
(-1, 1): Move 'L' -> (-2, 1)
(-2, 1): Move 'D' -> (-2, 0)
(-2, 0): Move 'D' -> (-2, -1)
(-2, -1): Move 'R' -> (-1, -1)
(-1, -1): Move 'R' -> (0, -1)
(0, -1): Move ',' -> failed
(0, -1): Move ' ' -> failed
(0, -1): Move 'U' -> (0, 0)
(0, 0): Move 'L' -> (-1, 0)
(-1, 0): Move 'R' -> (0, 0)
(0, 0): Move 'D' -> (0, -1)
(0, -1): Move ',' -> failed
(0, -1): Move ' ' -> failed
(0, -1): Move 'U' -> (0, 0)
(0, 0): Move 'U' -> (0, 1)
(0, 1): Move 'L' -> (-1, 1)
(-1, 1): Move 'L' -> (-2, 1)
(-2, 1): Move 'D' -> (-2, 0)
(-2, 0): Move 'D' -> (-2, -1)
(-2, -1): Move 'R' -> (-1, -1)
(-1, -1): Move 'R' -> (0, -1)
(0, -1): Move '' -> failed

Live Demo on coliru


问:
Android - How to tell when MediaPlayer is buffering
I've got to be missing something obvious here, but I can't seem to find anything to allow me to determine when MediaPlayer is buffering audio.  I'm streaming internet audio and I want to display a buffering indicator, but nothing I've tried allows me to know when MediaPlayer interrupts the audio to buffer, so I can't properly display a buffering indicator.  Any clues?</p>

答:
@Daniel, per your comment on @JRL's answer, you could probably get this working by spinning up a thread and waiting for a timeout.

Something like DetectBufferTimeout.java (untested) would do nicely.

I do, however, agree that spinning up this separate thread is a bit of a hack.  Perhaps OnBufferingUpdateListener could make a guarantee as to how often it calls onBufferingUpdate() regardless of whether a change in the buffering progress has occurred so we can detect if we're getting the same value over and over.


问:
R Custom Max Function
```<code>data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))
</code>```

For each person we track their scores until they reach "proficient" (3) or excellence (4). If a person scores excellence (4) then that value is kept and the persons next score is removed (see person 4; instead of NA would just want to remove that row however). If a person scores proficient (3) that value is carried forward UNLESS they score 4 which would replace the score of 3. Otherwise the values stay how they are. I tried cummax func but not sure how to apply such a rule.

It is my attempt below

```<code>data$want = ave(data$score, data$person, FUN = function(x) cummax(replace(x, is.na(x), -1)))
</code>```

答:
An option with data.table.  Convert the 'data.frame' to 'data.table' (setDT(data)), grouped by 'person', specify the i to select rows where 'score' is greater than or equal to 3, get the cummax of 'score' and assign it to 'WANT2', replace the NA elements with the 'score' value (pmax), set the duplicated '4' values to NA for each 'person'

```<code>library(data.table)
setDT(data)[score >=3,  WANT2 := cummax(score), person
     ][, WANT2 := pmax(score, WANT2, na.rm = TRUE), person]
i1 <- data[WANT2 == 4, .I[duplicated(WANT2)], person]$V1
data[i1, WANT2 := NA]
data
#    person score WANT WANT2
# 1:      1     1    1     1
# 2:      1     2    2     2
# 3:      1     3    3     3
# 4:      1     2    3     2
# 5:      2     2    2     2
# 6:      2     1    1     1
# 7:      2     2    2     2
# 8:      2     3    3     3
# 9:      3     2    2     2
#10:      3     3    3     3
#11:      3     1    3     1
#12:      3     4    4     4
#13:      4     1    1     1
#14:      4     4    4     4
#15:      4     3   NA    NA
</code>```

Or create an index where the value 4 is duplicated

```<code>setDT(data)[, ind := NA^(duplicated(cumsum(score == 4)) &
         shift(score) == 4), person]
</code>```

then get the cumulative max of 'score' by person while specifying the i to select rows where score is greater than or equal to 4

```<code>data[score >=3, WANT2 := cummax(score), person]
</code>```

and replace the NA elements with the 'score' using pmax while making sure that duplicated 4 is NA (using the 'ind')

```<code>data[, WANT2 := pmax(score, WANT2, na.rm = TRUE) * ind]
</code>```

Title: R Custom Max Function

Body:
data=data.frame("person"=c(1,1,1,1,2,2,2,2,3,3,3,3,4,4,4),
                "score"=c(1,2,3,2,2,1,2,3,2,3,1,4,1,4,3),
                "WANT"=c(1,2,3,3,2,1,2,3,2,3,3,4,1,4,NA))

For each person we track their scores until they reach "proficient" (3) or excellence (4). If a person scores excellence (4) then that value is kept and the persons next score is removed (see person 4; instead of NA would just want to remove that row however). If a person scores proficient (3) that value is carried forward UNLESS they score 4 which would replace the score of 3. Otherwise the values stay how they are. I tried cummax func but not sure how to apply such a rule.

It is my attempt below

data$want = ave(data$score, data$person, FUN = function(x) cummax(replace(x, is.na(x), -1)))

Body:
An option with data.table.  Convert the 'data.frame' to 'data.table' (setDT(data)), grouped by 'person', specify the i to select rows where 'score' is greater than or equal to 3, get the cummax of 'score' and assign it to 'WANT2', replace the NA elements with the 'score' value (pmax), set the duplicated '4' values to NA for each 'person'

library(data.table)
setDT(data)[score >=3,  WANT2 := cummax(score), person
     ][, WANT2 := pmax(score, WANT2, na.rm = TRUE), person]
i1 <- data[WANT2 == 4, .I[duplicated(WANT2)], person]$V1
data[i1, WANT2 := NA]
data
#    person score WANT WANT2
# 1:      1     1    1     1
# 2:      1     2    2     2
# 3:      1     3    3     3
# 4:      1     2    3     2
# 5:      2     2    2     2
# 6:      2     1    1     1
# 7:      2     2    2     2
# 8:      2     3    3     3
# 9:      3     2    2     2
#10:      3     3    3     3
#11:      3     1    3     1
#12:      3     4    4     4
#13:      4     1    1     1
#14:      4     4    4     4
#15:      4     3   NA    NA

Or create an index where the value 4 is duplicated

setDT(data)[, ind := NA^(duplicated(cumsum(score == 4)) &
         shift(score) == 4), person]

then get the cumulative max of 'score' by person while specifying the i to select rows where score is greater than or equal to 4

data[score >=3, WANT2 := cummax(score), person]

and replace the NA elements with the 'score' using pmax while making sure that duplicated 4 is NA (using the 'ind')

data[, WANT2 := pmax(score, WANT2, na.rm = TRUE) * ind]


问:
Python age calculator based on DOB
I am practicing by creating an age calculator which calculates age in years based on given date of birth.

However it doesn't work the way I intend it to function. I want to show age in year e.g 19 to the user when their age is 19 and month is less than 6 and if the month is more than 6 then I want to add 1 to the age in this case 19+1.

Can anyone create the same program with the same concept in a better way?  Please add some explanation so that it is easy for me to understand.

I am python beginner, so please excuse my bad code as well as my bad English. Thanks in advance for the help.

from datetime import date

Doby,Dobm,Dobd =input("enter your DOB : i.e year,month,days  1999,02,08   : ").split(",")
born = date(year = int(Doby) , month= int(Dobm) , day= int(Dobd))
today = date.today()
age = today.year - born.year
condition = today.month - born.month
if condition >= 6 :
    age += 1
elif condition <= -6 :
    age -= 1
print(age)
```

答:
I subtracted the int(age) from 'age' to get the decimal port of the age.

```<code>days_in_year = 365.2425
age = (date.today() - born).days / days_in_year
decAge = age - int(age)
</code>```

Then checked to see if the decimal portion is greater than 0.5 and set 'age' accordingly.

```<code>if decAge > 0.5 :
  age = int(age) + 1
else:
  age = int(age)
</code>```

I think that works.

Title: Python age calculator based on DOB

Body:
I subtracted the int(age) from 'age' to get the decimal port of the age.

days_in_year = 365.2425
age = (date.today() - born).days / days_in_year
decAge = age - int(age)

Then checked to see if the decimal portion is greater than 0.5 and set 'age' accordingly.

if decAge > 0.5 :
  age = int(age) + 1
else:
  age = int(age)

I think that works.


问:
Conv2d not accepting tensor as input, saying its not tensor
I want to pass a tensor through a convolutional 2 layer. I am not able to execute it as I am getting a type error even though I have converted my numpy array to a tensor.

I tried using tf.convert_to_tensor() to solve this problem. Didn't work

import numpy as np
import tensorflow as tf

class Generator():

  def __init__(self):

    self.conv1 = nn.Conv2d(1, 28, kernel_size=3, stride=1, padding=1)
    self.pool1 = nn.MaxPool2d(kernel_size=3, stride=0, padding=1)

    self.fc1 = nn.Linear(100, 10)
    self.fc2 = nn.Linear(10, 5)

  def forward_pass(self, x):                                                                       #Why do we pass the object itself in every method?

    x = self.conv1(x)
    print(x)
    x = self.pool1(x)
    print(x)

    x = self.fc1(x)
    print(x)
    x = self.fc2(x)
    print(x)

    return x

arr = tf.convert_to_tensor(np.random.random((3,28,28)))

gen = Generator()
gen.forward_pass(arr)

```

<p>Error message - </p>

<pre class="lang-py prettyprint-override"><code>TypeError                                 Traceback (most recent call last)

<ipython-input-31-9fa8e764dcdb> in <module>()
      1 gen = Generator()
----> 2 gen.forward_pass(arr)

2 frames

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in forward(self, input)
    336                             _pair(0), self.dilation, self.groups)
    337         return F.conv2d(input, self.weight, self.bias, self.stride,
--> 338                         self.padding, self.dilation, self.groups)
    339
    340

TypeError: conv2d(): argument 'input' (position 1) must be Tensor, not Tensor
</code>```

答:
You are trying to pass a TensorFlow tensor to a PyTorch function. TensorFlow and PyTorch are separate projects with different data structures which, in general, cannot be used interchangeably in this way.

To convert a NumPy array to a PyTorch tensor, you can use:

import torch
arr = torch.from_numpy(np.random.random((3,28,28)))
```

Body:
I want to pass a tensor through a convolutional 2 layer. I am not able to execute it as I am getting a type error even though I have converted my numpy array to a tensor.

I tried using tf.convert_to_tensor() to solve this problem. Didn't work

import numpy as np
import tensorflow as tf

class Generator():

  def __init__(self):

    self.conv1 = nn.Conv2d(1, 28, kernel_size=3, stride=1, padding=1)
    self.pool1 = nn.MaxPool2d(kernel_size=3, stride=0, padding=1)

    self.fc1 = nn.Linear(100, 10)
    self.fc2 = nn.Linear(10, 5)

  def forward_pass(self, x):                                                                       #Why do we pass the object itself in every method?

    x = self.conv1(x)
    print(x)
    x = self.pool1(x)
    print(x)

    x = self.fc1(x)
    print(x)
    x = self.fc2(x)
    print(x)

    return x

arr = tf.convert_to_tensor(np.random.random((3,28,28)))

gen = Generator()
gen.forward_pass(arr)

Error message -

TypeError                                 Traceback (most recent call last)

<ipython-input-31-9fa8e764dcdb> in <module>()
      1 gen = Generator()
----> 2 gen.forward_pass(arr)

2 frames

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in forward(self, input)
    336                             _pair(0), self.dilation, self.groups)
    337         return F.conv2d(input, self.weight, self.bias, self.stride,
--> 338                         self.padding, self.dilation, self.groups)
    339
    340

TypeError: conv2d(): argument 'input' (position 1) must be Tensor, not Tensor


问:
Loop through all controls of a Form, even those in GroupBoxes
I'd like to add an event to all TextBoxes on my Form:

```<code>foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms.TextBox))
    {
        C.TextChanged += new EventHandler(C_TextChanged);
    }
}
</code>```

The problem is that they are stored in several GroupBoxes and my loop doesn't see them. I could loop through controls of each GroupBox individually but is it possible to do it all  in a simple way  in one loop?

答:
Updated answer:

I needed to disable all the controls in a form, including groupboxes. This code worked:

```<code>    private void AlterControlsEnable(bool ControlEnabled)
    {
        foreach (Control i in Controls)
            i.Enabled = ControlEnabled;
    }
</code>```

Body:
I'd like to add an event to all TextBoxes on my Form:

foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms.TextBox))
    {
        C.TextChanged += new EventHandler(C_TextChanged);
    }
}

The problem is that they are stored in several GroupBoxes and my loop doesn't see them. I could loop through controls of each GroupBox individually but is it possible to do it all  in a simple way  in one loop?

Body:
Updated answer:

I needed to disable all the controls in a form, including groupboxes. This code worked:

    private void AlterControlsEnable(bool ControlEnabled)
    {
        foreach (Control i in Controls)
            i.Enabled = ControlEnabled;
    }