问:
Tkinter Error: self.tk.call( _tkinter.TclError: cannot use geometry manager grid inside . which already has slaves managed by pack
Below is my draw function written in python using tkinter library:

```<code>def draw():
global canvas
root.geometry('1080x720')
root.state('zoomed')

# UI_frame1 = Frame(root, width=1000, height=150, bg = 'Blue')
# UI_frame1.grid(row=0,column=0)
canvas = Canvas(root,bg='black',highlightthickness=0)
canvas.pack(fill=tkinter.BOTH, expand=True)

# print(root.winfo_screenwidth(),root.winfo_screenheight())

canvas.create_line(int(root.winfo_screenwidth()*0),int(root.winfo_screenheight()*0.1736),int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0.1736),fill='white')
canvas.create_line(int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0),int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*1),fill='white')
canvas.create_line(int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0.1157),int(root.winfo_screenwidth()*1),int(root.winfo_screenheight()*0.1157),fill='white')
canvas.create_line(int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0.8101),int(root.winfo_screenwidth()*1),int(root.winfo_screenheight()*0.8101),fill='white')
# canvas.create_line(0,150,1000,150,fill='white')
# canvas.create_line(1000,0,1000,1080,fill='white')
# canvas.create_line(1001,100,1920,100,fill='white')
# canvas.create_line(1001,700,1920,700,fill='white')
UI_frame1 = Frame(canvas,bg='white',width=int(root.winfo_screenwidth()*0.6510),height=int(root.winfo_screenheight()*0.1580)).place(x=int(root.winfo_screenwidth()*0),y=int(root.winfo_screenheight()*0))
N = Label(UI_frame1,text='N',bg ='black',fg='white',font=(12))
N.grid(row=0,column=0)
weights = Label(UI_frame1,text='Weights',bg ='black',fg='white',font=(12))
weights.grid(row=0,column=1)
val = Label(UI_frame1,text='Values',bg ='black',fg='white',font=(12))
val.grid(row=0,column=2)
# N = Label(UI_frame1,text='N',fg='white',bg='black',font=(12)).place(x=int(root.winfo_screenwidth()*0.1067),y=int(root.winfo_screenheight()*0.0289))
# weights = Label(UI_frame1,text='Weights',fg='white',bg='black',font=(12)).place(x=int(root.winfo_screenwidth()*0.2700),y=int(root.winfo_screenheight()*0.0289))
# val = Label(UI_frame1,text='Values',fg='white',bg='black',font=(12)).place(x=int(root.winfo_screenwidth()*0.5000),y=int(root.winfo_screenheight()*0.0289))
</code>```

I am getting the error of 'cannot use geometry manager grid inside . which already has slaves managed by pack'. I am using pack method to my canvas so that canvas is placed over my entire window. On that canvas I have placed frame using place method. I would like to place my N label to top left side of Frame using grid, but I'm getting the error. I would be grateful if someone could tell me what is wrong with the code.
Thankyou.

答:
Your code is quite a mess... try to remove the unnecessary stuff to help you visualize what you are creating...

A couple of pointers for your consideration:

Less can be good. It helps you visualise what you are trying to do.

tk.Canvas has a create_window method to let you position other widgets inside it. Here, I am showing you how to position a tk.Frame inside the tk.Canvas and then use grid method to control the position of the tk.Label inside the tk.Frame using the grid method. So, you do not need to use the place method to position widgets inside a tk.Canvas.

Sample script:

```<code>import tkinter as tk

root = tk.Tk()
root.geometry('1080x720')
canvas = tk.Canvas(root,bg='black',highlightthickness=0)
canvas.pack(fill=tk.BOTH, expand=True)

def draw():
    # 1. Create variable for screenwidth and screenheight
    sw = root.winfo_screenwidth()
    sh = root.winfo_screenheight()
    print(sw,sh)

    # 2. Create line borders
    canvas.create_line(int(sw*0),int(sh*0.1736),int(sw*0.6510),int(sh*0.1736),fill='white')
    canvas.create_line(int(sw*0.6510),int(sh*0),int(sw*0.6510),int(sh*1),fill='white')
    canvas.create_line(int(sw*0.6510),int(sh*0.1157),int(sw*1),int(sh*0.1157),fill='white')
    canvas.create_line(int(sw*0.6510),int(sh*0.8101),int(sw*1),int(sh*0.8101),fill='white')

    # 3. Create Frame widget
    UI_frame1 = tk.Frame(canvas, bg='white', width=int(sw*0.6510), height=int(sh*0.1580))
    # Put Frame inside of canvas using the Canvas's create_window method
    # You can learn more about this method from
    # https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/create_window.html
    canvas.create_window(0, 0, anchor=tk.NW, window=UI_frame1)

    # 3. Create Labels and position them inside the Frame widget using the grid method
    N = tk.Label(UI_frame1, text='N', bg ='black', fg='white', font=(12))
    weights = tk.Label(UI_frame1, text='Weights', bg ='black', fg='white', font=(12))
    val = tk.Label(UI_frame1, text='Values', bg ='black', fg='white', font=(12))
    N.grid(row=0,column=0)
    weights.grid(row=0,column=1)
    val.grid(row=0,column=2)

draw()
</code>```

Body:
Below is my draw function written in python using tkinter library:

def draw():
global canvas
root.geometry('1080x720')
root.state('zoomed')

# UI_frame1 = Frame(root, width=1000, height=150, bg = 'Blue')
# UI_frame1.grid(row=0,column=0)
canvas = Canvas(root,bg='black',highlightthickness=0)
canvas.pack(fill=tkinter.BOTH, expand=True)

# print(root.winfo_screenwidth(),root.winfo_screenheight())

canvas.create_line(int(root.winfo_screenwidth()*0),int(root.winfo_screenheight()*0.1736),int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0.1736),fill='white')
canvas.create_line(int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0),int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*1),fill='white')
canvas.create_line(int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0.1157),int(root.winfo_screenwidth()*1),int(root.winfo_screenheight()*0.1157),fill='white')
canvas.create_line(int(root.winfo_screenwidth()*0.6510),int(root.winfo_screenheight()*0.8101),int(root.winfo_screenwidth()*1),int(root.winfo_screenheight()*0.8101),fill='white')
# canvas.create_line(0,150,1000,150,fill='white')
# canvas.create_line(1000,0,1000,1080,fill='white')
# canvas.create_line(1001,100,1920,100,fill='white')
# canvas.create_line(1001,700,1920,700,fill='white')
UI_frame1 = Frame(canvas,bg='white',width=int(root.winfo_screenwidth()*0.6510),height=int(root.winfo_screenheight()*0.1580)).place(x=int(root.winfo_screenwidth()*0),y=int(root.winfo_screenheight()*0))
N = Label(UI_frame1,text='N',bg ='black',fg='white',font=(12))
N.grid(row=0,column=0)
weights = Label(UI_frame1,text='Weights',bg ='black',fg='white',font=(12))
weights.grid(row=0,column=1)
val = Label(UI_frame1,text='Values',bg ='black',fg='white',font=(12))
val.grid(row=0,column=2)
# N = Label(UI_frame1,text='N',fg='white',bg='black',font=(12)).place(x=int(root.winfo_screenwidth()*0.1067),y=int(root.winfo_screenheight()*0.0289))
# weights = Label(UI_frame1,text='Weights',fg='white',bg='black',font=(12)).place(x=int(root.winfo_screenwidth()*0.2700),y=int(root.winfo_screenheight()*0.0289))
# val = Label(UI_frame1,text='Values',fg='white',bg='black',font=(12)).place(x=int(root.winfo_screenwidth()*0.5000),y=int(root.winfo_screenheight()*0.0289))

I am getting the error of 'cannot use geometry manager grid inside . which already has slaves managed by pack'. I am using pack method to my canvas so that canvas is placed over my entire window. On that canvas I have placed frame using place method. I would like to place my N label to top left side of Frame using grid, but I'm getting the error. I would be grateful if someone could tell me what is wrong with the code.
Thankyou.

Body:
Your code is quite a mess... try to remove the unnecessary stuff to help you visualize what you are creating...

A couple of pointers for your consideration:

Less can be good. It helps you visualise what you are trying to do.

tk.Canvas has a create_window method to let you position other widgets inside it. Here, I am showing you how to position a tk.Frame inside the tk.Canvas and then use grid method to control the position of the tk.Label inside the tk.Frame using the grid method. So, you do not need to use the place method to position widgets inside a tk.Canvas.

Sample script:

import tkinter as tk

root = tk.Tk()
root.geometry('1080x720')
canvas = tk.Canvas(root,bg='black',highlightthickness=0)
canvas.pack(fill=tk.BOTH, expand=True)

def draw():
    # 1. Create variable for screenwidth and screenheight
    sw = root.winfo_screenwidth()
    sh = root.winfo_screenheight()
    print(sw,sh)

    # 2. Create line borders
    canvas.create_line(int(sw*0),int(sh*0.1736),int(sw*0.6510),int(sh*0.1736),fill='white')
    canvas.create_line(int(sw*0.6510),int(sh*0),int(sw*0.6510),int(sh*1),fill='white')
    canvas.create_line(int(sw*0.6510),int(sh*0.1157),int(sw*1),int(sh*0.1157),fill='white')
    canvas.create_line(int(sw*0.6510),int(sh*0.8101),int(sw*1),int(sh*0.8101),fill='white')

    # 3. Create Frame widget
    UI_frame1 = tk.Frame(canvas, bg='white', width=int(sw*0.6510), height=int(sh*0.1580))
    # Put Frame inside of canvas using the Canvas's create_window method
    # You can learn more about this method from
    # https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/create_window.html
    canvas.create_window(0, 0, anchor=tk.NW, window=UI_frame1)

    # 3. Create Labels and position them inside the Frame widget using the grid method
    N = tk.Label(UI_frame1, text='N', bg ='black', fg='white', font=(12))
    weights = tk.Label(UI_frame1, text='Weights', bg ='black', fg='white', font=(12))
    val = tk.Label(UI_frame1, text='Values', bg ='black', fg='white', font=(12))
    N.grid(row=0,column=0)
    weights.grid(row=0,column=1)
    val.grid(row=0,column=2)

draw()


来源: stackexchange

问:
How to add data to a ManyToMany field model?
I have model Department:

```<code>class Department(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name')
    superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.DO_NOTHING)
    manager = models.ForeignKey(Manager, on_delete = models.DO_NOTHING)
    history = HistoricalRecords()

def get_subsidiary(self):
        return "\n".join([p.title for p in self.subsidiary.all()])

def __str__(self):
    return self.title
</code>```

In Department model I have 2 instance of the same model: subsidiary and superior departments. The rules are simple: one department can have only one superior department, and many subsidiary.
I want to implement next logic:

I am creating new department SLF, and f.e. I choose SID department as superior department for SLF. Finally, when I save SLF object I want to add this department as subsidiary for SID automatically.

I am trying to override save method like:

```<code>def save(self, *args, **kwargs):
    print('Department.objects.filter(title=self.superior): ', Department.objects.filter(title=self.superior))
    if self.superior__in == Department.objects.filter(title=self.superior.title):
        tmp = Department.objects.filter(title=self.superior.title)
        tmp.create(subsidiary = self.superior)
        tmp.save()

    super(Department, self).save(*args, **kwargs)
</code>```

But it doesn't work. How can implement something like this?

答:
You have to use add() function to add new object to ManyToManyField. Remember also, that with filter you get QuerySet. To get object you should ust get or even get_object_or_404, but look yourself for that :)

```<code>...
    tmp = Department.objects.get(title=self.superior.title)
    tmp.subsidiary.add(self.superior)
...
</code>```

You don't need to save it.

ContentLicense: CC BY-SA 4.0

Body:
I have model Department:

class Department(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=30)
    subsidiary = models.ManyToManyField('self',null=True,blank=True, symmetrical=False, related_name='subsidiary_name')
    superior = models.ForeignKey('self',null=True,blank=True, related_name='superior_name', on_delete = models.DO_NOTHING)
    manager = models.ForeignKey(Manager, on_delete = models.DO_NOTHING)
    history = HistoricalRecords()

def get_subsidiary(self):
        return "\n".join([p.title for p in self.subsidiary.all()])

def __str__(self):
    return self.title

In Department model I have 2 instance of the same model: subsidiary and superior departments. The rules are simple: one department can have only one superior department, and many subsidiary.
I want to implement next logic:

I am creating new department SLF, and f.e. I choose SID department as superior department for SLF. Finally, when I save SLF object I want to add this department as subsidiary for SID automatically.

I am trying to override save method like:

def save(self, *args, **kwargs):
    print('Department.objects.filter(title=self.superior): ', Department.objects.filter(title=self.superior))
    if self.superior__in == Department.objects.filter(title=self.superior.title):
        tmp = Department.objects.filter(title=self.superior.title)
        tmp.create(subsidiary = self.superior)
        tmp.save()

    super(Department, self).save(*args, **kwargs)

But it doesn't work. How can implement something like this?

Body:
You have to use add() function to add new object to ManyToManyField. Remember also, that with filter you get QuerySet. To get object you should ust get or even get_object_or_404, but look yourself for that :)

...
    tmp = Department.objects.get(title=self.superior.title)
    tmp.subsidiary.add(self.superior)
...

You don't need to save it.


问:
Javascript/Node - Question about calling functions from within same module
Hoping somebody could please explain this to me- why can I call the second function from the first without error in the first 2 examples, but the third example errors out.

I can write a module like so:

```<code>function main () {
   const double = doubleThis(5)
   console.log(double);
}

function doubleThis(num) {
   let answer = num*2;
   return answer;
}
</code>```

or like this:

```<code>module.exports = {
   run: function(){
      const double = doubleThis(5);
      console.log(double);
   }
}

function doubleThis(num){
   let answer = num*2
   return answer;
}
</code>```

However, something like this is not allowed:

```<code>module.exports = {
   run: function(){
      const double = doubleThis(5);
      console.log(double);
   },

   doubleThis: function(num){
      let answer = num*2;
      return answer;
   }
}
</code>```

答: Thanks, this.doubleThis(5) works fine- embarrassing question but maybe somebody else might wonder same thing. I'm familiar with usage of this in prototypes but apparently not familiar enough with how this applies everywhere else... will review hoisting. Thanks again.

Body:
Hoping somebody could please explain this to me- why can I call the second function from the first without error in the first 2 examples, but the third example errors out.

I can write a module like so:

function main () {
   const double = doubleThis(5)
   console.log(double);
}

function doubleThis(num) {
   let answer = num*2;
   return answer;
}

or like this:

module.exports = {
   run: function(){
      const double = doubleThis(5);
      console.log(double);
   }
}

function doubleThis(num){
   let answer = num*2
   return answer;
}

However, something like this is not allowed:

module.exports = {
   run: function(){
      const double = doubleThis(5);
      console.log(double);
   },

   doubleThis: function(num){
      let answer = num*2;
      return answer;
   }
}


问:
Hibernate unidirectional @OneToMany association triggers updates of foreign keys
I have the following entities:

```<code>@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "TYPE")
public class Type implements Serializable {

  private static final long serialVersionUID = 563398089758359222L;

  @NotNull
  @Column(name = "OBJECT_TYPE")
  private String objectType;

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TypeNameId")
  @SequenceGenerator(name = "TypeNameId", sequenceName = "SQ_TNAME_WL", allocationSize = 1)
  private Long id;

  @NotNull
  @ToString.Include
  private String code;

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "BOUND_TO_ID", referencedColumnName = "ID")
  @JoinColumn(name = "BOUND_TO_CLASS", referencedColumnName = "OBJECT_TYPE")
  private Set<Translation> translations;

}

@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "TRANSLATION")
public class Translation implements Serializable {

  private static final long serialVersionUID = -4974947078465122824L;

  @NotNull
  @Column(name = "OBJECT_TYPE")
  private String objectType;

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TranslationId")
  @SequenceGenerator(name = "TranslationId", sequenceName = "SQ_LTRANSLATION_WL", allocationSize = 1)
  private Long id;

  @Size(max = 4000)
  @Column(name = "VALUE")
  private String value;

  @Size(max = 150)
  @Column(name = "LOCALE")
  private String locale;

  @Size(max = 150)
  @Column(name = "BOUND_TO_CLASS")
  private String boundToClass;

  @Column(name = "BOUND_TO_ID")
  private Long boundToId;

}
</code>```

Other entities may also have their translations in Translations table but do not include mappings with respect to Translation entity.
When creating a Type with translations, Hibernate wants to do the SQL below:

Hibernate: insert into type (code,  object_type, id) values ("code","Type", 1)

Hibernate: insert into translation (bound_to_class, bound_to_id, locale, object_type, value, id) values (null, null, "en_US", "Translation", "American code", 2)

There is a non-deferrable unique constraint on the columns bound_to_id, bound_to_class and locale. It is not possible to create translations in the same locale for different types since bound_to_class and bound_to_id are null in Hibernate SQL.

How do I change the mappings to allow translation creations without making the unique constraint deferrable or using bidirectional association?

答:
Other than setting up a bi-directional relationship:

```<code>public class Type {
  ..
  @OneToMany(mappedBy="type", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<Translation> translations;
}
..
public class Translation {
  ..
  @ManyToOne
  @JoinColumn(name = "BOUND_TO_ID", referencedColumnName = "ID")
  @JoinColumn(name = "BOUND_TO_CLASS", referencedColumnName = "OBJECT_TYPE")
  Type type;
}
</code>```

Which would then setup the fk values for you, the alternative is to map the BOUND_TO_ID and BOUND_TO_CLASS within the Translation yourself, and pull them yourself from any Type instances:

```<code>public class Translation {
  ..
  @Column(name = "BOUND_TO_CLASS")
  private String objectType;

  @Column(name = "BOUND_TO_ID")
  private Long objectId;

}
</code>```

You'd then need to mark the relationship within Type as read-only:

```<code>public class Type {
  ..
  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "BOUND_TO_ID", referencedColumnName = "ID", updatable=false, insertable=false)
  @JoinColumn(name = "BOUND_TO_CLASS", referencedColumnName = "OBJECT_TYPE", updatable=false, insertable=false)
  private Set<Translation> translations;
}
</code>```

Since the Type id is generated, you'd need to call persist on Type first, flush the context to make sure the ID is assigned, and then use the ID and objectType to set any Transaction instances you wished to create to point to it.

Body:
I have the following entities:

@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "TYPE")
public class Type implements Serializable {

  private static final long serialVersionUID = 563398089758359222L;

  @NotNull
  @Column(name = "OBJECT_TYPE")
  private String objectType;

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TypeNameId")
  @SequenceGenerator(name = "TypeNameId", sequenceName = "SQ_TNAME_WL", allocationSize = 1)
  private Long id;

  @NotNull
  @ToString.Include
  private String code;

  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "BOUND_TO_ID", referencedColumnName = "ID")
  @JoinColumn(name = "BOUND_TO_CLASS", referencedColumnName = "OBJECT_TYPE")
  private Set<Translation> translations;

}

@Entity
@Getter
@Setter
@NoArgsConstructor
@Table(name = "TRANSLATION")
public class Translation implements Serializable {

  private static final long serialVersionUID = -4974947078465122824L;

  @NotNull
  @Column(name = "OBJECT_TYPE")
  private String objectType;

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "TranslationId")
  @SequenceGenerator(name = "TranslationId", sequenceName = "SQ_LTRANSLATION_WL", allocationSize = 1)
  private Long id;

  @Size(max = 4000)
  @Column(name = "VALUE")
  private String value;

  @Size(max = 150)
  @Column(name = "LOCALE")
  private String locale;

  @Size(max = 150)
  @Column(name = "BOUND_TO_CLASS")
  private String boundToClass;

  @Column(name = "BOUND_TO_ID")
  private Long boundToId;

}

Other entities may also have their translations in Translations table but do not include mappings with respect to Translation entity.
When creating a Type with translations, Hibernate wants to do the SQL below:

Hibernate: insert into type (code,  object_type, id) values ("code","Type", 1)

Hibernate: insert into translation (bound_to_class, bound_to_id, locale, object_type, value, id) values (null, null, "en_US", "Translation", "American code", 2)

There is a non-deferrable unique constraint on the columns bound_to_id, bound_to_class and locale. It is not possible to create translations in the same locale for different types since bound_to_class and bound_to_id are null in Hibernate SQL.

How do I change the mappings to allow translation creations without making the unique constraint deferrable or using bidirectional association?

Body:
Other than setting up a bi-directional relationship:

public class Type {
  ..
  @OneToMany(mappedBy="type", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  private Set<Translation> translations;
}
..
public class Translation {
  ..
  @ManyToOne
  @JoinColumn(name = "BOUND_TO_ID", referencedColumnName = "ID")
  @JoinColumn(name = "BOUND_TO_CLASS", referencedColumnName = "OBJECT_TYPE")
  Type type;
}

Which would then setup the fk values for you, the alternative is to map the BOUND_TO_ID and BOUND_TO_CLASS within the Translation yourself, and pull them yourself from any Type instances:

public class Translation {
  ..
  @Column(name = "BOUND_TO_CLASS")
  private String objectType;

  @Column(name = "BOUND_TO_ID")
  private Long objectId;

}

You'd then need to mark the relationship within Type as read-only:

public class Type {
  ..
  @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
  @JoinColumn(name = "BOUND_TO_ID", referencedColumnName = "ID", updatable=false, insertable=false)
  @JoinColumn(name = "BOUND_TO_CLASS", referencedColumnName = "OBJECT_TYPE", updatable=false, insertable=false)
  private Set<Translation> translations;
}

Since the Type id is generated, you'd need to call persist on Type first, flush the context to make sure the ID is assigned, and then use the ID and objectType to set any Transaction instances you wished to create to point to it.


答:
What you're attempting to do is called boolean indexing.

It looks like data is actually a Pandas DataFrame. If so, you don't even need np.where:

data[data.OType.str.contains("YSOc")]
```

If you take a look at the documentation for np.where, it points out that

When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero()

Looking at that documentation shows that the return type is a tuple of arrays. Notice the ,) at the end of your output? The reason you got an invalid key error from the other answer was because you were actually trying to index with a tuple of arrays, instead of a plain array.

Title: Numpy where but keep original data that holds true

Body:
I have an array that I'm using np.where on. However, the output of the conditional statement just return the index of the true values.

Here's the statement I'm using:

data = np.where(data.OType.str.contains("YSOc"))

Input data

        Region     RAJ2000    DEJ2000                OType
0       LUP_III  242.588882 -38.644272                 Zero
1       LUP_III  242.588882 -39.302551                  two
2       LUP_III  242.588882 -39.377029                 star
3       LUP_III  242.595749 -38.762226                  one
4       LUP_III  242.602203 -39.317276                  two
        ...         ...        ...                  ...
582347  LUP_III  242.174133 -39.026955  YSOc_star+dust(MP1)
582348  LUP_III  242.178635 -39.104069  YSOc_star+dust(IR4)
582349  LUP_III  242.199524 -38.833614  YSOc_star+dust(IR4)
582350  LUP_III  242.205811 -39.094246  YSOc_star+dust(IR2)
582351  LUP_III  242.214279 -39.091789  YSOc_star+dust(IR2)

Output

(array([  4350,   5726,   6432,   9324,  13815,  14139,  18445,  29680,
        32350,  37842,  37956,  39458,  40384,  42086,  42241,  70026,
        87998,  95434,  95680, 100641, 140513, 144178, 158947, 161837,
       184541, 187837, 198310, 215526, 218879, 222999, 230776, 232013,
       233383, 235072, 251165, 259407, 267365, 268906, 269205, 286646,
       290633, 291358, 313746, 313779, 315215, 329447, 330986, 336783,
       336831, 339249, 341296, 348079, 351279, 351764, 353540, 356300,
       357192, 363877, 379226, 385232, 385635, 386531, 388968, 389570,
       397586, 400390, 402026, 436435, 438384, 439781, 443509, 447030,
       447881, 459637, 459906, 460051, 460722, 461185, 461459, 461556,
       461655, 461993, 465299, 465743, 466993, 467071, 468263, 469951,
       470610, 471196, 472743, 475490, 475665, 476385, 478243, 478549,
       478599, 478998, 484449, 485657, 486718, 486820, 486851, 487030,
       487446, 489547, 501403, 502071, 506799, 507159, 510826, 511213,
       512757, 513549, 514043, 514117, 514189, 514353, 514611, 514672,
       518171, 518276, 519617, 522213, 532190, 538127, 542022, 542202,
       542283, 542368, 547522, 547810, 548793, 552908, 554167, 557280,
       559775, 561043, 561541, 562073, 562375, 562401, 562634, 562699,
       562928, 562958, 564007, 564567, 567201, 568651, 570026, 573017,
       579175, 580137, 580332, 580402, 580473, 581081, 582273, 582274,
       582275, 582276, 582277, 582278, 582279, 582280, 582281, 582282,
       582283, 582284, 582285, 582286, 582287, 582288, 582289, 582290,
       582291, 582292, 582293, 582294, 582295, 582296, 582297, 582298,
       582299, 582300, 582301, 582302, 582303, 582304, 582305, 582306,
       582307, 582308, 582309, 582310, 582311, 582312, 582313, 582314,
       582315, 582316, 582317, 582318, 582319, 582320, 582321, 582322,
       582323, 582324, 582325, 582326, 582327, 582328, 582329, 582330,
       582331, 582332, 582333, 582334, 582335, 582336, 582337, 582338,
       582339, 582340, 582341, 582342, 582343, 582344, 582345, 582346,
       582347, 582348, 582349, 582350, 582351]),)

How do I make the output return the values from the original array that is returned from the statement rather than their indexes.

Body:
What you're attempting to do is called boolean indexing.

It looks like data is actually a Pandas DataFrame. If so, you don't even need np.where:

data[data.OType.str.contains("YSOc")]

If you take a look at the documentation for np.where, it points out that

When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero()

Looking at that documentation shows that the return type is a tuple of arrays. Notice the ,) at the end of your output? The reason you got an invalid key error from the other answer was because you were actually trying to index with a tuple of arrays, instead of a plain array.


问:
AirFlow Python operator error: got an unexpected keyword argument 'conf'
I am trying to trigger dbt cloud via AirFlow and unable to find an answer to the error below

ERROR - run_job() got an unexpected keyword argument 'conf'

I am using the plugin code from https://github.com/sungchun12/airflow-dbt-cloud

```<code>"""Main handler method to run the dbt Cloud job and track the job run status"""
        job_run_id = self._trigger_job()
        print(f"job_run_id = {job_run_id}")

        visit_url = f"https://cloud.getdbt.com/#/accounts/{self.account_id}/projects/{self.project_id}/runs/{job_run_id}/"
        print(f"Check the dbt Cloud job status! Visit URL:{visit_url}")

        while True:
            time.sleep(1)  # make an api call every 1 second

            job_run_status = self._get_job_run_status(job_run_id)

            print(f"job_run_status = {job_run_status}")

            if job_run_status == dbt_job_run_status.SUCCESS:
                print(f"Success! Visit URL: {visit_url}")
                break
            elif (
                    job_run_status == dbt_job_run_status.ERROR
                    or job_run_status == dbt_job_run_status.CANCELLED
            ):
                raise Exception(f"Failure! Visit URL: {visit_url}")
</code>```

I am calling the function via the following code

```<code>   run_dbt_cloud_job = PythonOperator(
            task_id="run_dbt_cloud_job",
            python_callable=dbt_cloud_job_runner_config.run_job,
            provide_context=True,
        )
</code>```

And get the error

run_job() got an unexpected keyword argument 'conf'

I'm not sure why it is not working.

If I change the provide context = False then I get following error

ERROR - 'NoneType' object is not subscriptable

答:
In this case, you need to pass **kwargs  on the parameters.

You can see this example:

```<code>def my_mult_function(number, **kwargs):
return number*number

</code>```

It is because if you set provide_context=True, the PythonOperator will export context to make available for callables to use. A generic variable will catch all the keywords arguments.

You can see the PythonOperator class.

If your code returns  this error “'NoneType' object is not subscriptable”, it is because there are no results in your query. A solution to this is to change the query to use scalar().

You can see this example.

```<code>    triggered_by = (
    session.query(Log.owner)
    .filter(Log.dag_id == "killer_dag")
    .limit(1)
    .scalar()
)
</code>```

You can see more documentation in this link.

Body:
I am trying to trigger dbt cloud via AirFlow and unable to find an answer to the error below

ERROR - run_job() got an unexpected keyword argument 'conf'

I am using the plugin code from https://github.com/sungchun12/airflow-dbt-cloud

"""Main handler method to run the dbt Cloud job and track the job run status"""
        job_run_id = self._trigger_job()
        print(f"job_run_id = {job_run_id}")

        visit_url = f"https://cloud.getdbt.com/#/accounts/{self.account_id}/projects/{self.project_id}/runs/{job_run_id}/"
        print(f"Check the dbt Cloud job status! Visit URL:{visit_url}")

        while True:
            time.sleep(1)  # make an api call every 1 second

            job_run_status = self._get_job_run_status(job_run_id)

            print(f"job_run_status = {job_run_status}")

            if job_run_status == dbt_job_run_status.SUCCESS:
                print(f"Success! Visit URL: {visit_url}")
                break
            elif (
                    job_run_status == dbt_job_run_status.ERROR
                    or job_run_status == dbt_job_run_status.CANCELLED
            ):
                raise Exception(f"Failure! Visit URL: {visit_url}")

I am calling the function via the following code

   run_dbt_cloud_job = PythonOperator(
            task_id="run_dbt_cloud_job",
            python_callable=dbt_cloud_job_runner_config.run_job,
            provide_context=True,
        )

And get the error

run_job() got an unexpected keyword argument 'conf'

I'm not sure why it is not working.

If I change the provide context = False then I get following error

ERROR - 'NoneType' object is not subscriptable

Body:
In this case, you need to pass **kwargs  on the parameters.

You can see this example:

def my_mult_function(number, **kwargs):
return number*number

It is because if you set provide_context=True, the PythonOperator will export context to make available for callables to use. A generic variable will catch all the keywords arguments.

You can see the PythonOperator class.

If your code returns  this error “'NoneType' object is not subscriptable”, it is because there are no results in your query. A solution to this is to change the query to use scalar().

You can see this example.

    triggered_by = (
    session.query(Log.owner)
    .filter(Log.dag_id == "killer_dag")
    .limit(1)
    .scalar()
)

You can see more documentation in this link.


问:
What is the worst-case asymptotic cost of this algorithm?
```<code>void Ordena(TipoItem *A, int n)
{

    TipoItem x;

    int i, j;

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

        for (j = n; j > i; j--)
        {

            if (A[j].chave < A[j - 1].chave)
            {

                x = A[j];

                A[j] = A[j - 1];

                A[j - 1] = x;
            }
        }
    }

}
</code>```

I believe the worst case is when the array is in descending order, am I right?
About the asymptotic cost in terms of number of movements, is it O(n²) or O(2n²) ?
I've just started learning about asymptotic cost (as you can tell).

答: As you were saying the worst-case scenario here is the one where the array is in descending order because you will have to execute the if statement every single time. However, since we are talking about the asymptotic notation, it is quite irrelevant whether or not you execute the if statement because the cost of those three instructions is actually constant(i.d. O(1)). Therefore, the important thing here is how many times you actually have to loop through the elements in the array and this happens exactly, if you do the math, n^2/2 + n/2 times. So, the computational complexity is O(n^2) because the predominant part here is n^2/2, and the asymptotic notation doesn't take into account the multiplicative factor 1/2, even if sometimes these factors could influence the execution time.</p>

Body:
void Ordena(TipoItem *A, int n)
{

    TipoItem x;

    int i, j;

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

        for (j = n; j > i; j--)
        {

            if (A[j].chave < A[j - 1].chave)
            {

                x = A[j];

                A[j] = A[j - 1];

                A[j - 1] = x;
            }
        }
    }

}

I believe the worst case is when the array is in descending order, am I right?
About the asymptotic cost in terms of number of movements, is it O(n²) or O(2n²) ?
I've just started learning about asymptotic cost (as you can tell).


问:
Pandas datetime format to include 'T'
I have a dataframe with multiple datetime columns with this format:

```<code>2019-02-19 09:47:45.285
</code>```

the required format is:

```<code>2019-02-19T09:47:45.285
</code>```

Tried with the following code, but I get the same thing:

df[columns] = df[columns].apply(pd.to_datetime, format='%Y-%m-%dT%H:%M:%S.%f')
```

答:
The format parameter tells pd.to_datetime how to parse the date. Since it supports the format of your dates automatically, I'd remove that.

What you really want is to format your date back to a string, and you can use column.dt.strftime with your format for that:

```<code>df[columns] = df[columns].apply(pd.to_datetime).apply(lambda col: col.dt.strftime('%Y-%m-%dT%H:%M:%S.%f'))
</code>```

Title: Pandas datetime format to include 'T'

Body:
I have a dataframe with multiple datetime columns with this format:

2019-02-19 09:47:45.285

the required format is:

2019-02-19T09:47:45.285

Tried with the following code, but I get the same thing:

df[columns] = df[columns].apply(pd.to_datetime, format='%Y-%m-%dT%H:%M:%S.%f')

Body:
The format parameter tells pd.to_datetime how to parse the date. Since it supports the format of your dates automatically, I'd remove that.

What you really want is to format your date back to a string, and you can use column.dt.strftime with your format for that:

df[columns] = df[columns].apply(pd.to_datetime).apply(lambda col: col.dt.strftime('%Y-%m-%dT%H:%M:%S.%f'))


问:
Dictionaries as argument in numba
I'm working on a part of a code for which I'm using numba. The functions are defined with dictionaries as an argument. The idea behind this code is to do an integration of a function by for instance trapz rule using numba and saves the result in a new category of the dictionary. Here is my attempt

```<code>from functools import partial
import ctypes
from numba import jit, prange,cfunc, carray
from numba.types import float64, CPointer, void, intp
from numba import njit
from numba import typed, typeof
from numba.experimental import jitclass

def set_variables():
# initialization of parameters
    Var = {}
    x_0, x_1,n = 0,1,4000
    A = 1.2
    Var['xvec'] = linspace(x_0,x_1,n)
    Var['bool'] = True
    Var['Amplitude'] = A
    return Var

@jit
def myfun (x,Var):
#test function
    if Var['bool']:
        A = Var['Amplitude']
        return A*x**x
    else :
        return x**x

@jit(nopython=True, parallel=True)
def parallel_sum3(xvec,Var,fun):
#trapz rule with numba

    Y_0,Y_1 = fun(xvec[0],Var),fun(xvec[1], Var)

    h = xvec[1]-xvec[0]
    sum_f = .5*(Y_0+Y_1)*h
    sum = .0
    for i in prange(1,xvec.shape[0]):
        sum +=fun(xvec[i],Var)
    sum_f += sum*h
    return sum_f

def print_result(Var):
# get result and save  in Var
    xvec = Var['xvec']
    A = parallel_sum3(xvec,Var,myfun)
    Var['result'] = A
    return A

</code>```

My goal is to have a function that performs the integration on parallel and reads and writtes on Var which may have different classes as integers, floats, array, booleans, etc. So far this code gives me an error when I want to do

```<code>Var = set_variables
print_result(Var)
</code>```

which is the following

```<code>Traceback (most recent call last):

  File "<ipython-input-61-d2f49038d612>", line 1, in <module>
    T = printeo3(Var)

  File "/scratch/dgresta/Four terminals/numba_test.py", line 82, in printeo3
    A = parallel_sum3(xvec,Var,myfun)

  File "/home/dgresta/.local/lib/python3.9/site-packages/numba/core/dispatcher.py", line 468, in _compile_for_args
    error_rewrite(e, 'typing')

  File "/home/dgresta/.local/lib/python3.9/site-packages/numba/core/dispatcher.py", line 409, in error_rewrite
    raise e.with_traceback(None)

TypingError: non-precise type pyobject
During: typing of argument at /scratch/dgresta/Four terminals/numba_test.py (69)
</code>```

I'm using python 3.9.1 and numba 0.55.1
Any guess on how to get rid off this error?
Thanks in advance

答:
This is not supported by Numba (and will certainly not be in the future). Indeed, the documentation explicitly states:

Numba does not fully support the Python dict because it is an untyped container that can have any Python types as members. To generate efficient machine code, Numba needs the keys and the values of the dictionary to have fixed types, declared in advance. To achieve this, Numba has a typed dictionary, numba.typed.Dict, for which the type-inference mechanism must be able to infer the key-value types by use, or the user must explicitly declare the key-value type using the Dict.empty() constructor method.

In your case, you cannot specify a precise type that would work for a Numba typed-dict. Thus, you need to split the dictionary in multiple ones so the type of each is well defined for Numba. Regarding your code, it is probable better not to use dictionary but to just use simple variables.

Title: Dictionaries as argument in numba

Body:
I'm working on a part of a code for which I'm using numba. The functions are defined with dictionaries as an argument. The idea behind this code is to do an integration of a function by for instance trapz rule using numba and saves the result in a new category of the dictionary. Here is my attempt

from functools import partial
import ctypes
from numba import jit, prange,cfunc, carray
from numba.types import float64, CPointer, void, intp
from numba import njit
from numba import typed, typeof
from numba.experimental import jitclass

def set_variables():
# initialization of parameters
    Var = {}
    x_0, x_1,n = 0,1,4000
    A = 1.2
    Var['xvec'] = linspace(x_0,x_1,n)
    Var['bool'] = True
    Var['Amplitude'] = A
    return Var

@jit
def myfun (x,Var):
#test function
    if Var['bool']:
        A = Var['Amplitude']
        return A*x**x
    else :
        return x**x

@jit(nopython=True, parallel=True)
def parallel_sum3(xvec,Var,fun):
#trapz rule with numba

    Y_0,Y_1 = fun(xvec[0],Var),fun(xvec[1], Var)

    h = xvec[1]-xvec[0]
    sum_f = .5*(Y_0+Y_1)*h
    sum = .0
    for i in prange(1,xvec.shape[0]):
        sum +=fun(xvec[i],Var)
    sum_f += sum*h
    return sum_f

def print_result(Var):
# get result and save  in Var
    xvec = Var['xvec']
    A = parallel_sum3(xvec,Var,myfun)
    Var['result'] = A
    return A

My goal is to have a function that performs the integration on parallel and reads and writtes on Var which may have different classes as integers, floats, array, booleans, etc. So far this code gives me an error when I want to do

Var = set_variables
print_result(Var)

which is the following

Traceback (most recent call last):

  File "<ipython-input-61-d2f49038d612>", line 1, in <module>
    T = printeo3(Var)

  File "/scratch/dgresta/Four terminals/numba_test.py", line 82, in printeo3
    A = parallel_sum3(xvec,Var,myfun)

  File "/home/dgresta/.local/lib/python3.9/site-packages/numba/core/dispatcher.py", line 468, in _compile_for_args
    error_rewrite(e, 'typing')

  File "/home/dgresta/.local/lib/python3.9/site-packages/numba/core/dispatcher.py", line 409, in error_rewrite
    raise e.with_traceback(None)

TypingError: non-precise type pyobject
During: typing of argument at /scratch/dgresta/Four terminals/numba_test.py (69)

I'm using python 3.9.1 and numba 0.55.1
Any guess on how to get rid off this error?
Thanks in advance


问:
ios_command: Connection type ssh is not valid for this module
Ansible raw command can work via SSH, but this playbook cannot work with the same Cisco command show version.

It is giving this error message, related to SSH:

fatal: [192.168.1.15]: FAILED! => {"changed": false, "msg": "Connection type ssh is not valid for this module"}

Here is the inventory under inventory/host-file

```<code>[routers]
192.168.1.15
[routers:vars]

ansible_network_os=ios
ansible_user=admin
ansible_password=admin
ansible_connection=network_cli
</code>```

And the playbook playbooks/show_version.yml

---

- name: Cisco show version example
  hosts: routers
  gather_facts: false

  tasks:
    - name: run show version on the routers
      ios_command:
        commands: show version | incl Version
      register: output

    - name: print output
      debug:
        var: output.stdout_lines
```
<p>Here is my file structure</p>
<pre class="lang-none prettyprint-override"><code>.
├── ansible.cfg
├── hosts
├── inventory
│   └── host-file
└── playbooks
    └── show_version.yml
</code>```

I do run the playbook with the command below, from the folder playbooks

ansible-playbook show_version.yml
```

Is this a SSH issue?

Can anyone share some experience?

答:
According your error message

Connection type ssh is not valid for this module

at least the variable ansible_connection wasn't set with a value as it should. A minimal working example from a running environment

---
- name: Cisco show version example
  hosts: routers
  gather_facts: false

  vars: # for execution environment

    ansible_connection: ansible.netcommon.network_cli
    ansible_network_os: cisco.ios.ios
    ansible_become: yes
    ansible_become_method: enable

  tasks:

  - name: Gather only the config and default facts
    cisco.ios.ios_facts:
      gather_subset:
      - config

  - name: Show facts
    debug:
      msg: "{{ ansible_facts.net_version }}"
```
<p>In respect to the given comments, maybe you can add a debug task in your playbook</p>
<pre class="lang-yaml prettyprint-override"><code>
- name: Show 'ansible_*' values
  debug:
    msg:
      - "{{ ansible_network_os }}"
      - "{{ ansible_connection }}"

- meta: end_play
</code>```

to see what gets actually loaded.

Body:
Ansible raw command can work via SSH, but this playbook cannot work with the same Cisco command show version.

It is giving this error message, related to SSH:

fatal: [192.168.1.15]: FAILED! => {"changed": false, "msg": "Connection type ssh is not valid for this module"}

Here is the inventory under inventory/host-file

[routers]
192.168.1.15
[routers:vars]

ansible_network_os=ios
ansible_user=admin
ansible_password=admin
ansible_connection=network_cli

And the playbook playbooks/show_version.yml

---

- name: Cisco show version example
  hosts: routers
  gather_facts: false

  tasks:
    - name: run show version on the routers
      ios_command:
        commands: show version | incl Version
      register: output

    - name: print output
      debug:
        var: output.stdout_lines

Here is my file structure

.
├── ansible.cfg
├── hosts
├── inventory
│   └── host-file
└── playbooks
    └── show_version.yml

I do run the playbook with the command below, from the folder playbooks

ansible-playbook show_version.yml

Is this a SSH issue?

Can anyone share some experience?

Body:
According your error message

Connection type ssh is not valid for this module

at least the variable ansible_connection wasn't set with a value as it should. A minimal working example from a running environment

---
- name: Cisco show version example
  hosts: routers
  gather_facts: false

  vars: # for execution environment

    ansible_connection: ansible.netcommon.network_cli
    ansible_network_os: cisco.ios.ios
    ansible_become: yes
    ansible_become_method: enable

  tasks:

  - name: Gather only the config and default facts
    cisco.ios.ios_facts:
      gather_subset:
      - config

  - name: Show facts
    debug:
      msg: "{{ ansible_facts.net_version }}"

In respect to the given comments, maybe you can add a debug task in your playbook

- name: Show 'ansible_*' values
  debug:
    msg:
      - "{{ ansible_network_os }}"
      - "{{ ansible_connection }}"

- meta: end_play

to see what gets actually loaded.


问:
How to set up a link from a column value to a linked object?
I would like to set up a hyperlink from a foreign key column in the backing dataset of object type A to the respective object of type B.

Following an existing and working example, in the dataset preview, I have added a type class in the form of {{object type B id}}.{{object type B's property id}}. However, this is not giving me a link. Do I need to format this differently or are there any additional configurations required?

答: Further investigation revealed that in addition to the type class described in the question, this also requires a configuration change by a Palantir representative.</p>


问:
Multiple cases in switch statement
Is there a way to fall through multiple case statements without stating case value: repeatedly?

I know this works:

```<code>switch (value)
{
   case 1:
   case 2:
   case 3:
      // Do some stuff
      break;
   case 4:
   case 5:
   case 6:
      // Do some different stuff
      break;
   default:
       // Default stuff
      break;
}
</code>```

but I'd like to do something like this:

```<code>switch (value)
{
   case 1,2,3:
      // Do something
      break;
   case 4,5,6:
      // Do something
      break;
   default:
      // Do the Default
      break;
}
</code>```

Is this syntax I'm thinking of from a different language, or am I missing something?

答:
.NET Framework 3.5 has got ranges:

Enumerable.Range from MSDN

you can use it with "contains" and the IF statement, since like someone said the SWITCH statement uses the "==" operator.

Here an example:

```<code>int c = 2;
if(Enumerable.Range(0,10).Contains(c))
    DoThing();
else if(Enumerable.Range(11,20).Contains(c))
    DoAnotherThing();
</code>```

But I think we can have more fun: since you won't need the return values and this action doesn't take parameters, you can easily use actions!

```<code>public static void MySwitchWithEnumerable(int switchcase, int startNumber, int endNumber, Action action)
{
    if(Enumerable.Range(startNumber, endNumber).Contains(switchcase))
        action();
}
</code>```

The old example with this new method:

```<code>MySwitchWithEnumerable(c, 0, 10, DoThing);
MySwitchWithEnumerable(c, 10, 20, DoAnotherThing);
</code>```

Since you are passing actions, not values, you should omit the parenthesis, it's very important. If you need function with arguments, just change the type of Action to Action<ParameterType>. If you need return values, use Func<ParameterType, ReturnType>.

In C# 3.0 there is no easy Partial Application to encapsulate the fact the the case parameter is the same, but you create a little helper method (a bit verbose, tho).

```<code>public static void MySwitchWithEnumerable(int startNumber, int endNumber, Action action){
    MySwitchWithEnumerable(3, startNumber, endNumber, action);
}
</code>```

Here an example of how new functional imported statement are IMHO more powerful and elegant than the old imperative one.

OwnerDisplayName: theo

Title: Multiple cases in switch statement

Body:
Is there a way to fall through multiple case statements without stating case value: repeatedly?

I know this works:

switch (value)
{
   case 1:
   case 2:
   case 3:
      // Do some stuff
      break;
   case 4:
   case 5:
   case 6:
      // Do some different stuff
      break;
   default:
       // Default stuff
      break;
}

but I'd like to do something like this:

switch (value)
{
   case 1,2,3:
      // Do something
      break;
   case 4,5,6:
      // Do something
      break;
   default:
      // Do the Default
      break;
}

Is this syntax I'm thinking of from a different language, or am I missing something?

Body:
.NET Framework 3.5 has got ranges:

Enumerable.Range from MSDN

you can use it with "contains" and the IF statement, since like someone said the SWITCH statement uses the "==" operator.

Here an example:

int c = 2;
if(Enumerable.Range(0,10).Contains(c))
    DoThing();
else if(Enumerable.Range(11,20).Contains(c))
    DoAnotherThing();

But I think we can have more fun: since you won't need the return values and this action doesn't take parameters, you can easily use actions!

public static void MySwitchWithEnumerable(int switchcase, int startNumber, int endNumber, Action action)
{
    if(Enumerable.Range(startNumber, endNumber).Contains(switchcase))
        action();
}

The old example with this new method:

MySwitchWithEnumerable(c, 0, 10, DoThing);
MySwitchWithEnumerable(c, 10, 20, DoAnotherThing);

Since you are passing actions, not values, you should omit the parenthesis, it's very important. If you need function with arguments, just change the type of Action to Action<ParameterType>. If you need return values, use Func<ParameterType, ReturnType>.

In C# 3.0 there is no easy Partial Application to encapsulate the fact the the case parameter is the same, but you create a little helper method (a bit verbose, tho).

public static void MySwitchWithEnumerable(int startNumber, int endNumber, Action action){
    MySwitchWithEnumerable(3, startNumber, endNumber, action);
}

Here an example of how new functional imported statement are IMHO more powerful and elegant than the old imperative one.

OwnerDisplayName: volothamp

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Adam Bellaire


问:
b2RopeJoint how to implement this into box2d?
How do I put b2RopeJoint into my project. The newest Box2d version does not have b2RopeJoint in it. People online tell me to update my box2d but I have 2.1.2 which is the newest version. I'm so confused. Will someone please tell me how to implement b2RopeJoint into my project? Please explain it to me in simple steps. I get confused easily unfortunately. Thanks!</p>

答:
2.1.2 is the newest official release, but the b2RopeJoint is newer than that. You will need to get the latest source from svn.
http://code.google.com/p/box2d/source/checkout

ContentLicense: CC BY-SA 3.0


问:
Image is not selecting from gallery android studio java
I want to select image from phone gallery but when i click on image the app returns to main activity without updating image. currently i created the code in fragment. I wrote the code correctly but it is not working. i checked this similar code on another activity and it is working there fine. Here is the code. please figure out where i am doing mistake.

Java

```<code>public class ProfileFragment extends Fragment {

    ArrayList<FriendsModel> list;
    FragmentProfileBinding binding;

    public ProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FragmentProfileBinding binding = FragmentProfileBinding.inflate(getLayoutInflater());

        // Inflate the layout for this fragment

        list = new ArrayList<>();
        list.add(new FriendsModel(R.drawable.profile2));
        list.add(new FriendsModel(R.drawable.profile3));
        list.add(new FriendsModel(R.drawable.profile4));
        list.add(new FriendsModel(R.drawable.profile2));
        list.add(new FriendsModel(R.drawable.profile3));

        FriendsAdapter adapter = new FriendsAdapter(list, getContext());

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        binding.friendsRV.setLayoutManager(layoutManager);
        binding.friendsRV.setAdapter(adapter);

        binding.changeCoverPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT); // this will open gallery
                intent.setType("image/*");
                startActivityForResult(intent, 11);

            }
        });
        return binding.getRoot();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data.getData() != null) {
            Uri uri = data.getData();
            binding.coverImage.setImageURI(uri);
        }
    }

}
</code>```

答:
First of all check the READ_EXTERNAL_STORAGE permission in your Manifest. Then if you're targeting API 29 or higher try this code:

```<code>void openImageChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {

    new Thread(new Runnable() {
        @Override
        public void run() {
            if (resultCode == RESULT_OK) {
                if (requestCode == SELECT_PICTURE) {
                    // Get the url from data
                    final Uri selectedImageUri = data.getData();
                    if (null != selectedImageUri) {
                        // Get the path from the Uri
                        String path = getPathFromURI(selectedImageUri);
                        Log.i(TAG, "Image Path : " + path);
                        // Set the image in ImageView
                        findViewById(R.id.imgView).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ImageView) findViewById(R.id.imgView)).setImageURI(selectedImageUri);
                            }
                        });

                    }
                }
            }
        }
    }).start();

}

/* Get the real path from the URI */
public String getPathFromURI(Uri contentUri) {
    String res = null;
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
    if (cursor.moveToFirst()) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
}
</code>```

And in this way you can get a Real path as well in case you need it.

Body:
I want to select image from phone gallery but when i click on image the app returns to main activity without updating image. currently i created the code in fragment. I wrote the code correctly but it is not working. i checked this similar code on another activity and it is working there fine. Here is the code. please figure out where i am doing mistake.

Java

public class ProfileFragment extends Fragment {

    ArrayList<FriendsModel> list;
    FragmentProfileBinding binding;

    public ProfileFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        FragmentProfileBinding binding = FragmentProfileBinding.inflate(getLayoutInflater());

        // Inflate the layout for this fragment

        list = new ArrayList<>();
        list.add(new FriendsModel(R.drawable.profile2));
        list.add(new FriendsModel(R.drawable.profile3));
        list.add(new FriendsModel(R.drawable.profile4));
        list.add(new FriendsModel(R.drawable.profile2));
        list.add(new FriendsModel(R.drawable.profile3));

        FriendsAdapter adapter = new FriendsAdapter(list, getContext());

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
        binding.friendsRV.setLayoutManager(layoutManager);
        binding.friendsRV.setAdapter(adapter);

        binding.changeCoverPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT); // this will open gallery
                intent.setType("image/*");
                startActivityForResult(intent, 11);

            }
        });
        return binding.getRoot();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data.getData() != null) {
            Uri uri = data.getData();
            binding.coverImage.setImageURI(uri);
        }
    }

}

Body:
First of all check the READ_EXTERNAL_STORAGE permission in your Manifest. Then if you're targeting API 29 or higher try this code:

void openImageChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}

public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {

    new Thread(new Runnable() {
        @Override
        public void run() {
            if (resultCode == RESULT_OK) {
                if (requestCode == SELECT_PICTURE) {
                    // Get the url from data
                    final Uri selectedImageUri = data.getData();
                    if (null != selectedImageUri) {
                        // Get the path from the Uri
                        String path = getPathFromURI(selectedImageUri);
                        Log.i(TAG, "Image Path : " + path);
                        // Set the image in ImageView
                        findViewById(R.id.imgView).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ImageView) findViewById(R.id.imgView)).setImageURI(selectedImageUri);
                            }
                        });

                    }
                }
            }
        }
    }).start();

}

/* Get the real path from the URI */
public String getPathFromURI(Uri contentUri) {
    String res = null;
    String[] proj = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
    if (cursor.moveToFirst()) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        res = cursor.getString(column_index);
    }
    cursor.close();
    return res;
}

And in this way you can get a Real path as well in case you need it.


问:
How to convert a gdb Value to a python numeral object while debugging C program
I'm using python2.6's gdb module while debugging a C program, and would like to convert a gdb.Value instance into a python numeral object (variable) based off the instance's '.Type'.

E.g. turn my C program's SomeStruct->some_float_val = 1./6; to a Python gdb.Value via sfv=gdb.parse_and_eval('SomeStruct->some_double_val'), but THEN turn this into a double precision floating point python variable -- knowing that str(sfv.type.strip_typedefs())=='double' and its size is 8B -- WITHOUT just converting through a string using dbl=float(str(sfv)) or Value.string() but rather something like unpacking the bytes using struct to get the correct double value.

Every link returned from my searches points https://sourceware.org/gdb/onlinedocs/gdb/Values-From-Inferior.html#Values-From-Inferior, but I can't see how to convert a Value instance into a python variable cleanly, say the Value wasn't even in C memory but represented a gdb.Value.address (so can't use Inferior.read_memory()), how would one turn this into a Python int without casting string values?

答:
I stumbled upon this while trying to figure out how to do bitwise operations on a pointer. In my particular use case, I needed to calculate a page alignment offset. Python did not want to cast a pointer Value to int, however, the following worked:

```<code>int(ptr.cast(gdb.lookup_type("unsigned long long")))
</code>```

We first make gdb cast our pointer to unsigned long long, and then the resulting gdb.Value can be cast to Python int.

Body:
I stumbled upon this while trying to figure out how to do bitwise operations on a pointer. In my particular use case, I needed to calculate a page alignment offset. Python did not want to cast a pointer Value to int, however, the following worked:

int(ptr.cast(gdb.lookup_type("unsigned long long")))

We first make gdb cast our pointer to unsigned long long, and then the resulting gdb.Value can be cast to Python int.


问:
How to create automatic catalog in InDesign with scripting in JavaScript
I have a following code which works great for importing excel to InDesign and creating automatic grid catalog.

```<code>var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// make a table from the text
var rows = text.split('\r');
var table = [];
for (var i = 1; i < rows.length; i++) table.push(rows[i].split('\t'));

// width and height of cards, gaps, properties of the grid
var card_width = 70;
var card_height = 80;
var gap = 5;
var cols = 2;
var rows = 3;
var cards_per_page = cols * rows;

// calculate and add pages
var cards = table.length;
var pages_to_add = Math.ceil(cards / cards_per_page) - 1;
while(pages_to_add--) doc.pages.add();

var page_num = 0; // start page
var start_point = [10,10]; // start point for a first card on a page

main_loop:
for (var i = 0; i < cards; i++) {

    for (var row = 0; row < rows; row++) {

        for (var col = 0; col < cols; col++) {

            // break the loop if there is no more rows in the table
            if (table.length == 0) break main_loop;

            var table_row   = table.shift(); // take a first row from the table
            var title       = table_row[0];
            var description = table_row[1];
            var price       = table_row[2];

            // make a card
            var card = make_card(title, description, price);

            // send the card to the some page and move at some place
            card.move(doc.pages[page_num]);
            card.move(start_point);
            card.move(undefined, [(card_width + gap)*col, (card_height + gap)*row]);
        }
    }

    if (i > (page_num-1) * cards_per_page) page_num++; // increase the page number

}

// the function to create and return a card
function make_card(title, description, price) {
    var doc = app.activeDocument;

    var title_frame = doc.textFrames.add();
    title_frame.geometricBounds = [20, 80, 30, 150];
    title_frame.contents = title;

    var description_frame = doc.textFrames.add();
    description_frame.geometricBounds = [30, 80, 80, 150];
    description_frame.contents = description;

    var price_frame = doc.textFrames.add();
    price_frame.geometricBounds = [80, 80, 100, 150];
    price_frame.contents = price;

    var group = doc.groups.add([title_frame, description_frame, price_frame]);
    return group;
}
</code>```

But what if I want to have for  example 3 pages. Every page will have a different template
Pages 1, 4, 7... will have this template
Pages 2,5,8 ...
and pages 3, 6, 9 ... will use grid template
I didn't get how can I resolve it in javascript.

答:
Here is the template IDML: https://app.box.com/s/muqvroawbwv8zydwdizfc3xsmyzmenmy

Here is the code:

```<code>var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// split the text by rows
var rows = text.split('\r');
rows.shift(); // remove the first row (a header of the table)

// add pages if there is more than 10 rows
var i = rows.length - 10;
while (i > 0) {
    doc.pages[0].duplicate(LocationOptions.AT_END);
    i -= 1; if (i < 0) break;
    doc.pages[1].duplicate(LocationOptions.AT_END);
    i -= 5; if (i < 0) break;
    doc.pages[2].duplicate(LocationOptions.AT_END);
    i -= 4;
}

// fill all the text frames with texts from the rows
var frames = doc.textFrames;
var i = 0;
while (rows.length > 0) {
    var row = rows.shift().split('\t');
    frames[i++].contents = row[0]; // title
    frames[i++].contents = row[1]; // text
    frames[i++].contents = row[2]; // price
}

// remove empty frames
while (frames.length > i) frames[i].remove();
</code>```

The script puts text from the Excel table to the text frames of the template. If there more than 10 rows the script adds pages.

The script depends on the order of the frames in the template. It fills the frames from the frist frame[0] on the frist page to the last frame. If you change the order the texts will get in wrong places.

Here is how the first 10 rows/cards are filling:

Body:
I have a following code which works great for importing excel to InDesign and creating automatic grid catalog.

var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// make a table from the text
var rows = text.split('\r');
var table = [];
for (var i = 1; i < rows.length; i++) table.push(rows[i].split('\t'));

// width and height of cards, gaps, properties of the grid
var card_width = 70;
var card_height = 80;
var gap = 5;
var cols = 2;
var rows = 3;
var cards_per_page = cols * rows;

// calculate and add pages
var cards = table.length;
var pages_to_add = Math.ceil(cards / cards_per_page) - 1;
while(pages_to_add--) doc.pages.add();

var page_num = 0; // start page
var start_point = [10,10]; // start point for a first card on a page

main_loop:
for (var i = 0; i < cards; i++) {

    for (var row = 0; row < rows; row++) {

        for (var col = 0; col < cols; col++) {

            // break the loop if there is no more rows in the table
            if (table.length == 0) break main_loop;

            var table_row   = table.shift(); // take a first row from the table
            var title       = table_row[0];
            var description = table_row[1];
            var price       = table_row[2];

            // make a card
            var card = make_card(title, description, price);

            // send the card to the some page and move at some place
            card.move(doc.pages[page_num]);
            card.move(start_point);
            card.move(undefined, [(card_width + gap)*col, (card_height + gap)*row]);
        }
    }

    if (i > (page_num-1) * cards_per_page) page_num++; // increase the page number

}

// the function to create and return a card
function make_card(title, description, price) {
    var doc = app.activeDocument;

    var title_frame = doc.textFrames.add();
    title_frame.geometricBounds = [20, 80, 30, 150];
    title_frame.contents = title;

    var description_frame = doc.textFrames.add();
    description_frame.geometricBounds = [30, 80, 80, 150];
    description_frame.contents = description;

    var price_frame = doc.textFrames.add();
    price_frame.geometricBounds = [80, 80, 100, 150];
    price_frame.contents = price;

    var group = doc.groups.add([title_frame, description_frame, price_frame]);
    return group;
}

But what if I want to have for  example 3 pages. Every page will have a different template
Pages 1, 4, 7... will have this template
Pages 2,5,8 ...
and pages 3, 6, 9 ... will use grid template
I didn't get how can I resolve it in javascript.

Body:
Here is the template IDML: https://app.box.com/s/muqvroawbwv8zydwdizfc3xsmyzmenmy

Here is the code:

var doc = app.activeDocument;

// get a text from the XLSX file
var inputFile = File("~/Desktop/test.xlsx");
var temp_frame = doc.textFrames.add();
temp_frame.place(inputFile);
var text = temp_frame.parentStory.contents;
temp_frame.remove();

// split the text by rows
var rows = text.split('\r');
rows.shift(); // remove the first row (a header of the table)

// add pages if there is more than 10 rows
var i = rows.length - 10;
while (i > 0) {
    doc.pages[0].duplicate(LocationOptions.AT_END);
    i -= 1; if (i < 0) break;
    doc.pages[1].duplicate(LocationOptions.AT_END);
    i -= 5; if (i < 0) break;
    doc.pages[2].duplicate(LocationOptions.AT_END);
    i -= 4;
}

// fill all the text frames with texts from the rows
var frames = doc.textFrames;
var i = 0;
while (rows.length > 0) {
    var row = rows.shift().split('\t');
    frames[i++].contents = row[0]; // title
    frames[i++].contents = row[1]; // text
    frames[i++].contents = row[2]; // price
}

// remove empty frames
while (frames.length > i) frames[i].remove();

The script puts text from the Excel table to the text frames of the template. If there more than 10 rows the script adds pages.

The script depends on the order of the frames in the template. It fills the frames from the frist frame[0] on the frist page to the last frame. If you change the order the texts will get in wrong places.

Here is how the first 10 rows/cards are filling:


问:
i am tryin to create a method decorator in angular but this error shows up
```<code>export class IceCreamComponent {
  @Emoji()
  flavor = 'vanilla';
}

// Property Decorator
function Emoji() {
  return function(target: Object, key: string | symbol) {

    let val = target[key];

    const getter = () =>  {
        return val;
    };
    const setter = (next:any) => {
        console.log('updating flavor...');
        val = ` ${next} `;
    };

    Object.defineProperty(target, key, {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true,
    });

  };
}
</code>```

i got error:

error TS7053: Element implicitly has an 'any' type because expression
of type 'string | symbol' can't be used to index type 'Object'.   No
index signature with a parameter of type 'string' was found on type
'Object'.

11     let val = target[key];

答:
The reason for the error is that string can't be used to index the type of Object because the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.
You can tell Angular what type of Object that you are expecting by giving its type like this

let val = (key: string) => (target: Record<string, any>) => target[key];
```

Now the error should disappear as we are telling the compiler that target will be a collection of string/value i.e. in our case (string/any) pairs.

Body:
export class IceCreamComponent {
  @Emoji()
  flavor = 'vanilla';
}

// Property Decorator
function Emoji() {
  return function(target: Object, key: string | symbol) {

    let val = target[key];

    const getter = () =>  {
        return val;
    };
    const setter = (next:any) => {
        console.log('updating flavor...');
        val = ` ${next} `;
    };

    Object.defineProperty(target, key, {
      get: getter,
      set: setter,
      enumerable: true,
      configurable: true,
    });

  };
}

i got error:

error TS7053: Element implicitly has an 'any' type because expression
of type 'string | symbol' can't be used to index type 'Object'.   No
index signature with a parameter of type 'string' was found on type
'Object'.

11     let val = target[key];

Body:
The reason for the error is that string can't be used to index the type of Object because the object type is just an empty object by default. Therefore it isn't possible to use a string type to index {}.
You can tell Angular what type of Object that you are expecting by giving its type like this

let val = (key: string) => (target: Record<string, any>) => target[key];

Now the error should disappear as we are telling the compiler that target will be a collection of string/value i.e. in our case (string/any) pairs.


问:
Summation of float in for loop gives numeric errors
when summing up values in a simple for loop, Python gives a numeric error. Any ideas what causes this behaviour?

x = 0.0
for _ in range(1000):
    x += 0.1
print(x)
>>> 99.9999999999986
```

答:
Floating point errors are something you will see happen in any programming language. As kvantour said, computers cannot represent fractions so if you are adding up thirds then the computer will approximate 1/3 as 0.33 and (1/3 + 1/3 + 1/3) will turn out to be 0.99 instead of the 1 it should be.

To prevent this, in most cases, you can probably round off your final answer using the python round() method and you'll get the 100 you're looking for. If you need to be more precise and rounding is not an option for you then you can use the python decimal module as such:

```<code>from decimal import Decimal as D
x = D(0)
for _ in range(1000):
    x += D("0.1")
print(x)
</code>```

Body:
Floating point errors are something you will see happen in any programming language. As kvantour said, computers cannot represent fractions so if you are adding up thirds then the computer will approximate 1/3 as 0.33 and (1/3 + 1/3 + 1/3) will turn out to be 0.99 instead of the 1 it should be.

To prevent this, in most cases, you can probably round off your final answer using the python round() method and you'll get the 100 you're looking for. If you need to be more precise and rounding is not an option for you then you can use the python decimal module as such:

from decimal import Decimal as D
x = D(0)
for _ in range(1000):
    x += D("0.1")
print(x)


问:
Cannot remove eventlistener from noname remote callback function
I put a listener to process in a noname function (because I have to transmit some data further - 'evt' and 'ref' for example). How to close a listener in another remote file, were I process this data.

index.js:

import onClick from "./onClick.js";
const ref = document.querySelector('h1');
ref.addEventListener('click', (evt) => {onClick(evt, ref)}
```
<p><strong>onClick.js</strong>:</p>
<pre class="lang-js prettyprint-override"><code>export default function onClick(evt, ref) {
    console.log(evt);
    ref.removeEventListener('click', onClick)
};
</code>```

答:
You can just assign the anonymous function to a variable to have a function name, and pass it to onClick function. It seems to be anti-pattern (passing callee function to caller), but I guess this is what you're looking for:

index.js

```<code>import onClick from "./onClick.js";

const ref = document.querySelector('h1');

function clickCb(evt) {
  onClick(evt, ref, clickCb)
}

ref.addEventListener('click', clickCb}
</code>```

onClick.js

```<code>export default function onClick(evt, ref, clickCb) {
    console.log(evt);
    ref.removeEventListener('click', clickCb)
};
</code>```

Body:
I put a listener to process in a noname function (because I have to transmit some data further - 'evt' and 'ref' for example). How to close a listener in another remote file, were I process this data.

index.js:

import onClick from "./onClick.js";
const ref = document.querySelector('h1');
ref.addEventListener('click', (evt) => {onClick(evt, ref)}

onClick.js:

export default function onClick(evt, ref) {
    console.log(evt);
    ref.removeEventListener('click', onClick)
};

Body:
You can just assign the anonymous function to a variable to have a function name, and pass it to onClick function. It seems to be anti-pattern (passing callee function to caller), but I guess this is what you're looking for:

index.js

import onClick from "./onClick.js";

const ref = document.querySelector('h1');

function clickCb(evt) {
  onClick(evt, ref, clickCb)
}

ref.addEventListener('click', clickCb}

onClick.js

export default function onClick(evt, ref, clickCb) {
    console.log(evt);
    ref.removeEventListener('click', clickCb)
};


问:
Ruby on Rails Routing Question
I'm working on a website where users can sell tickets to their events. Tickets being sold for events are going to be promoted by promoters. In turn, the client wants a unique url that a promoter can email out to potential customers to sell tickets to.  Thus, I have to create a unique url that includes the promoters unique code along with an event id (To track sales).  The problem I am having is figuring out how to create this unique url. There's a many-to-many relationship between Event and Promoter joined together by a Promotion table.  The Promotion table will track each event's promoters as well as have an attribute to store how many tickets sold. In the Promoter table I will store basic information, such as name, along with the unique code the system will generate.

I know I can create a named route that can find an Event by id or a Promoter by id. The problem is I need to have the Event Id in the url along with the promoters unique code (unless there's a better way to do this). I will then be able to write a query to find an Event with a condition of the Promoter's unique code.

Any thoughts on how I might accomplish this? I think what is stumping me is that there is two parameters in the url.

Update:

```<code>map.buy_ticket 'buy_ticket/:id_1/:id_2',
 :controller => :events,
 :action => :buyTicket,
 :id_1 => /\d+/,
 :id_2 => /[a-z]+[0-9]+/i
</code>```

答:
You can create routes by hand in pretty much whatever format you need. Something like this in your routes.rb:

```<code>match '/ticket/:promoter_id:/:event_id' => 'controller#method', :via => :get, :as => :route_name
</code>```

Then you'll have :promoter_id and :event_id in your params when method is called. This will also give you route_name_path and route_name_url helpers.

The ticket, controller, method, and :route_name are, of course, just placeholders for demonstration purposes.

The routing guide has further details.

Title: Ruby on Rails Routing Question

Body:
I'm working on a website where users can sell tickets to their events. Tickets being sold for events are going to be promoted by promoters. In turn, the client wants a unique url that a promoter can email out to potential customers to sell tickets to.  Thus, I have to create a unique url that includes the promoters unique code along with an event id (To track sales).  The problem I am having is figuring out how to create this unique url. There's a many-to-many relationship between Event and Promoter joined together by a Promotion table.  The Promotion table will track each event's promoters as well as have an attribute to store how many tickets sold. In the Promoter table I will store basic information, such as name, along with the unique code the system will generate.

I know I can create a named route that can find an Event by id or a Promoter by id. The problem is I need to have the Event Id in the url along with the promoters unique code (unless there's a better way to do this). I will then be able to write a query to find an Event with a condition of the Promoter's unique code.

Any thoughts on how I might accomplish this? I think what is stumping me is that there is two parameters in the url.

Update:

map.buy_ticket 'buy_ticket/:id_1/:id_2',
 :controller => :events,
 :action => :buyTicket,
 :id_1 => /\d+/,
 :id_2 => /[a-z]+[0-9]+/i

Body:
You can create routes by hand in pretty much whatever format you need. Something like this in your routes.rb:

match '/ticket/:promoter_id:/:event_id' => 'controller#method', :via => :get, :as => :route_name

Then you'll have :promoter_id and :event_id in your params when method is called. This will also give you route_name_path and route_name_url helpers.

The ticket, controller, method, and :route_name are, of course, just placeholders for demonstration purposes.

The routing guide has further details.


问:
If jupyter notebook is ready but Dask dashboard is still showing that its running some task, can I execute my next cell?
I am new to Dask. I was using it with an xarray dataset. I persisted the dataset in memory and the jupyter cell showed that it was ready (no more asterisk). But the dask dashboard was busy executing the task. I didn't understand. When this happens, should I wait till dask dashboard has stabilized or am I free to run the next cell?

答: Persist submits the task graph to the scheduler and returns future objects pointing to your results. So the calculation will be running in the background while you continue your work. You don't need to wait for the dashboard to finish.</p>


问:
View and Set HTTP headers for Safari/Chrome
I'm testing an API and I would like to hit it with safari and see the raw json that's returned. The API requires a certain HTTP header be sent with every request. Is there a way in Safari or Chrome to set my http headers when visiting a URL?</p>

答:
I would use Fiddler as my debugging proxy and set the header there.  See the "Add a request header" of the FiddlerScript CookBook.  This same solution would work with any browser.

Fiddler is a Web Debugging Proxy which logs all HTTP(S) traffic
  between your computer and the Internet. Fiddler allows you to inspect
  all HTTP(S) traffic, set breakpoints, and "fiddle" with incoming or
  outgoing data. Fiddler includes a powerful event-based scripting
  subsystem, and can be extended using any .NET language.


问:
Can't Run adb On M1 zsh: segmentation fault adb
I try to run my React Native project on MacBook Pro M1 but when I run adb it's gives error : zsh: segmentation fault adb.

I tried run adb from both ~/Library/Android/sdk/platform-tools & ~/usr/local/bin/adb.

Tried reinstall platform-tools in android studio.

Tried install and reinstall platform-tools from brew.

Tried reinstall android studio itself.

Device: MacBook Pro M1 2020, SSD: 512, RAM: 8

OS: macOS Monterey

Android Studio: android-studio-2021.1.1.21-mac_arm

答: This looks similar to your problem. Setting up android emulators on mac m1 pros requires extra installation steps.</p>


问:
Put everything to zero in a np.array except n highest entries
I'm looking for the quickest way to do the following:

```<code>arr = np.array([2.,0.5,1.3,4.5,7.4])
</code>```

I want to build a new array (or overwrite current) where I put to zero everything except the n highest entries.

```<code>[2.0,0,0,4.5,7.4]
</code>```

答:
Let's define the array and a value for N, so we keep the N highest elements.

```<code>N = 3
arr = np.array([2.,0.5,1.3,4.5,7.4])
</code>```

Using argsort we can retrieve the order of elements from lower to highest. We just need to subtract from the size of the array to get from highest to lower.

```<code>order = arr.argsort()
order = arr.size - order
</code>```

Then replace with zeros the smaller elements:

```<code>arr[order > N] = 0
</code>```

Body:
I'm looking for the quickest way to do the following:

arr = np.array([2.,0.5,1.3,4.5,7.4])

I want to build a new array (or overwrite current) where I put to zero everything except the n highest entries.

[2.0,0,0,4.5,7.4]

Body:
Let's define the array and a value for N, so we keep the N highest elements.

N = 3
arr = np.array([2.,0.5,1.3,4.5,7.4])

Using argsort we can retrieve the order of elements from lower to highest. We just need to subtract from the size of the array to get from highest to lower.

order = arr.argsort()
order = arr.size - order

Then replace with zeros the smaller elements:

arr[order > N] = 0


问:
How can I disable checkbox for multi value selection in react-dropdown-tree-select?
I am new to React and I stumbled upon react-dropdown-tree-select for a specific need I had allowing users to view data in Tree format for selection in DropDown. But, I want the users to only select 1 value at a time. How can i enforce that?</p>

答: If you just want one element selected at a time you can use mode="radioSelect"</p>


问:
SASS and Compass on Heroku - What is the best approach
This is not a question on how to implement Compass and SASS on Heroku, as that was fairly simple to implement:  http://devcenter.heroku.com/articles/using-compass

I have my doubts about this solution, however.

The other solution is to add Compass.configuration.sass_options={:never_update=>true} to the production config and make sure the compiled CSS is in source control and the public folder.  Then, make sure the CSS is recompiled before every git push.

I don't like the idea of adding compiled CSS to source, but I also don't like the idea of recompiling the CSS every time the server is hit.

I can't seem to find any information regarding how often the CSS would be compiled or how long files are kept in the tmp folder.  I read somewhere that they are stored for the duration of the request, but I also read contradicting information that they are stored for the life-cycle of the application.

Which of the above two solutions would you choose?  Is there a third solution that I'm missing?

Thanks in advance!

答:
Why do you not like the idea of committing CSS to your source? Getting Sass AND Compass to play nice, at Heroku has been a constant issue that's not worth the time (for me) to solve.

Compile locally, and ship the CSS with your source. Save time :)


问:
Code using discogs_client only works with breakpoints or in shell, otherwise KeyError
discogs_client is a module for working with the vinyl-trading platform discogs. In my code I am trying to retrieve the data for a particular release.

This is the code:

```<code>d = discogs_client.Client(
    "Vinyl-Helper",
    consumer_key=consumer_key,
    consumer_secret=consumer_secret,
    token=access_token['oauth_token'],
    secret=access_token['oauth_token_secret']
    )

releaseId = 12698907

release = d.release(releaseId)
records.append(
    Record(
        release.data['artists_sort'],
        release.data["title"],
        release.data["labels"][0]["catno"],
        "M",
        "M",
        UPLOADER_CODE,
        releaseId
    )
)
</code>```

The code works in the shell, or if I put a breakpoint before, but not when I run it normally, or with a sleep(10) command before.
The exception always spits out "KeyError: 'artists_sort'"

答:
Solved.

The data is more easily fetched like this:

```<code>import urllib, json
releaseId = 12698907
url = f"https://api.discogs.com/releases/{releaseId}"
response = urllib.urlopen(url)
data = json.loads(response.read())
...
</code>```

Body:
discogs_client is a module for working with the vinyl-trading platform discogs. In my code I am trying to retrieve the data for a particular release.

This is the code:

d = discogs_client.Client(
    "Vinyl-Helper",
    consumer_key=consumer_key,
    consumer_secret=consumer_secret,
    token=access_token['oauth_token'],
    secret=access_token['oauth_token_secret']
    )

releaseId = 12698907

release = d.release(releaseId)
records.append(
    Record(
        release.data['artists_sort'],
        release.data["title"],
        release.data["labels"][0]["catno"],
        "M",
        "M",
        UPLOADER_CODE,
        releaseId
    )
)

The code works in the shell, or if I put a breakpoint before, but not when I run it normally, or with a sleep(10) command before.
The exception always spits out "KeyError: 'artists_sort'"

Body:
Solved.

The data is more easily fetched like this:

import urllib, json
releaseId = 12698907
url = f"https://api.discogs.com/releases/{releaseId}"
response = urllib.urlopen(url)
data = json.loads(response.read())
...


问:
Redirect to a new page not working on React application
When the user signups into the application the data is saved to DB using an API that returns an access token. After this step user needs to be redirected to another page (Signup Details). I am using the below-attached code to do the same. Once I submit the button the token is returned and the URL is changed to the new one. But the page is not displayed. Kindly help me fix this issue.

The new page to which the user should be redirected.

App.js

答:
The path="*" matches literally any route, and since you are rendering the Route components into a Switch, only the first matching Route or Redirect is rendered.

Remember that within a Switch path order and specificity matters! If ordered correctly there is almost zero need to use the exact prop. Order the routes by path in inverse path specificity, i.e. both "/SignupDetails" and "/Signup" are more specific than "/" and should appear higher in the Switch.

```<code><Router>
  <Switch>
    <Route path="/SignupDetails" component={SignupDetailsForm} />
    <Route path="/Signup" component={SignupForm} />
    <Route path="/" component={SignupForm} />
  </Switch>
</Router>
</code>```

react-router-dom v6 Route path prop can also take an array of paths, so you can make your code a bit more DRY if you like. Keep in mind that path order and specificity also still matters in the array.

```<code><Router>
  <Switch>
    <Route path="/SignupDetails" component={SignupDetailsForm} />
    <Route path={["/Signup", "/"]} component={SignupForm} />
  </Switch>
</Router>
</code>```

Body:
The path="*" matches literally any route, and since you are rendering the Route components into a Switch, only the first matching Route or Redirect is rendered.

Remember that within a Switch path order and specificity matters! If ordered correctly there is almost zero need to use the exact prop. Order the routes by path in inverse path specificity, i.e. both "/SignupDetails" and "/Signup" are more specific than "/" and should appear higher in the Switch.

<Router>
  <Switch>
    <Route path="/SignupDetails" component={SignupDetailsForm} />
    <Route path="/Signup" component={SignupForm} />
    <Route path="/" component={SignupForm} />
  </Switch>
</Router>

react-router-dom v6 Route path prop can also take an array of paths, so you can make your code a bit more DRY if you like. Keep in mind that path order and specificity also still matters in the array.

<Router>
  <Switch>
    <Route path="/SignupDetails" component={SignupDetailsForm} />
    <Route path={["/Signup", "/"]} component={SignupForm} />
  </Switch>
</Router>


问:
how to add headers to the api response using reactjs
I am new to react js,
I have a home screen with search bar. where user retrieves an employee information by providing the id. here's the code for that.

```<code>const [firstNames, setFirstNames] = useState("");
<input
            value={name}
            type="text"
            id="header-search"
            placeholder="Enter the search term"
            name={'id'}
            onChange={handleChange}
            />

        <button onClick={HandleSearch}>Search</button>

const handleChange= (e) => {
    e.preventDefault();
    setName(e.target.value);
  }

const HandleSearch = e => {

    e.preventDefault();
    axios.get(`http://localhost:8080/search?id=`+name)
        .then(response => {
          setLoading(false);
          if(response.status == 200 && response != null){

              console.log("RES",response.data);
              var tmpArray= [];
              var tmpJsx =[];
              // I was checking to see if I could retrieve the data from my response.
              var dataparse = response.data;
              var length = dataparse.length;
              console.log("length of my response array is: "+length)

              //printing the elements in array
              for (var i=0; i< length; i++){

                //console.log(response.data[i].firstname);

                 setFirstNames((firstNames) => [...firstNames, response.data[i]]);

              }

          } else{
                console.log('problem fetching');
            }
        })
        .catch(error => {
          setLoading(false);
          console.log("error occured: "+error);
        });
}
</code>```

and here's my return function:

```<code>{firstNames.map(function (names, index) {
                  return (
                    <tr key={index}>
                      <td> {names.firstname} -</td>
                      <td> {names.lastname}</td>
                    </tr>
                   )
                })}
</code>```

How do I add the headers to this data.
for example

```<code>firstname lastname
abc        abclast
</code>```

i tried to put this in the map function, but then my data was looking like:

```<code>firstname lastname
abc        abclast
firstname lastname
def        deflast
firstname lastname
ghi        ghilast
</code>```

Im sure there is something that im missing, could anyone help me on how to achieve this: thank you.

```<code>firstname lastname
abc        abclast
def        deflast
ghi        ghilast
</code>```

答:
You can do a conditional rendering by checking if the array has length greater than 0

An example would be like this. You can apply similarly to your problem

let names = [
  {firstName: 'John',lastName: 'Cena'},
  {firstName: 'Rey',lastName: 'Mysterio'},
]

const App = props => {
  return (

      {names.length > 0 &&
 //table renders only when array has elements

        First Name	   //setting headers
        Last Name

        {names.map((name,index) => {       //mapping for individual rows
          return (

              {name.firstName}
              {name.lastName}

          )
        })}

}

  );
};

```

codesandbox demo

Body:
I am new to react js,
I have a home screen with search bar. where user retrieves an employee information by providing the id. here's the code for that.

const [firstNames, setFirstNames] = useState("");
<input
            value={name}
            type="text"
            id="header-search"
            placeholder="Enter the search term"
            name={'id'}
            onChange={handleChange}
            />

        <button onClick={HandleSearch}>Search</button>

const handleChange= (e) => {
    e.preventDefault();
    setName(e.target.value);
  }

const HandleSearch = e => {

    e.preventDefault();
    axios.get(`http://localhost:8080/search?id=`+name)
        .then(response => {
          setLoading(false);
          if(response.status == 200 && response != null){

              console.log("RES",response.data);
              var tmpArray= [];
              var tmpJsx =[];
              // I was checking to see if I could retrieve the data from my response.
              var dataparse = response.data;
              var length = dataparse.length;
              console.log("length of my response array is: "+length)

              //printing the elements in array
              for (var i=0; i< length; i++){

                //console.log(response.data[i].firstname);

                 setFirstNames((firstNames) => [...firstNames, response.data[i]]);

              }

          } else{
                console.log('problem fetching');
            }
        })
        .catch(error => {
          setLoading(false);
          console.log("error occured: "+error);
        });
}

and here's my return function:

{firstNames.map(function (names, index) {
                  return (

                       {names.firstname} -
                       {names.lastname}

                   )
                })}

How do I add the headers to this data.
for example

firstname lastname
abc        abclast

i tried to put this in the map function, but then my data was looking like:

firstname lastname
abc        abclast
firstname lastname
def        deflast
firstname lastname
ghi        ghilast

Im sure there is something that im missing, could anyone help me on how to achieve this: thank you.

firstname lastname
abc        abclast
def        deflast
ghi        ghilast

Body:
You can do a conditional rendering by checking if the array has length greater than 0

An example would be like this. You can apply similarly to your problem

let names = [
  {firstName: 'John',lastName: 'Cena'},
  {firstName: 'Rey',lastName: 'Mysterio'},
]

const App = props => {
  return (
    <div>
      {names.length > 0 && <table> //table renders only when array has elements
        <tbody>
        <tr>
        <th>First Name</th>   //setting headers
        <th>Last Name</th>
        </tr>
        {names.map((name,index) => {       //mapping for individual rows
          return (
            <tr key={index}>
              <td>{name.firstName}</td>
              <td>{name.lastName}</td>
            </tr>
          )
        })}
        </tbody>
      </table>}
    </div>
  );
};

codesandbox demo