问:
My enemy isn't moving when my character is standing still
I'm currently coding a game on python, and I need a way for the enemy to run towards the player. It has to have a constant velocity of 5 pixels a cycle and this is my current code:

```<code>def move(self,character):
    characterposition = Vector(character.posx,character.posy)
    self.position = Vector(self.posx,self.posy)
    dist = characterposition.subtract(self.position)
    dist.normal(dist.length())
    length = dist.length()
    ratio = self.speed/math.sqrt(length)
    self.posx += dist.x * ratio
    self.posy += dist.y * ratio
</code>```

this seems to be working until my character stops moving. When the character stops moving, the enemy stops as well. This is a problem and I would appreciate any suggestions.

Edit: Heres my loop.

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             pygame.quit()
             run = False
             continue
        updatecharacterposition()
        collided = checkforbarriercollision()
        badguy.move(character)
        if collided:
            print("YOU LOST")
            pygame.quit()
            time.sleep(5)
    redrawgamewindow()
```

答:
Is the indenting in the code above correct? It shows updatecharacterposition() and the lines after it inside the for event in pygame.event.get(): loop.

If that is really the case, then none of that code will get called if you are not getting any events. That would cause all of the movement to stop.

Try this:

```<code>while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             pygame.quit()
             run = False
             continue
    updatecharacterposition()
    collided = checkforbarriercollision()
    badguy.move(character)
    if collided:
        print("YOU LOST")
        pygame.quit()
        time.sleep(5)
    redrawgamewindow()
</code>```

On a side note, it seems odd to me that badguy.move(character) is after the collision check. Usually you would move everything (the player and the 'badguy') and then do the collision check.

Body:
I'm currently coding a game on python, and I need a way for the enemy to run towards the player. It has to have a constant velocity of 5 pixels a cycle and this is my current code:

def move(self,character):
    characterposition = Vector(character.posx,character.posy)
    self.position = Vector(self.posx,self.posy)
    dist = characterposition.subtract(self.position)
    dist.normal(dist.length())
    length = dist.length()
    ratio = self.speed/math.sqrt(length)
    self.posx += dist.x * ratio
    self.posy += dist.y * ratio

this seems to be working until my character stops moving. When the character stops moving, the enemy stops as well. This is a problem and I would appreciate any suggestions.

Edit: Heres my loop.

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             pygame.quit()
             run = False
             continue
        updatecharacterposition()
        collided = checkforbarriercollision()
        badguy.move(character)
        if collided:
            print("YOU LOST")
            pygame.quit()
            time.sleep(5)
    redrawgamewindow()

Body:
Is the indenting in the code above correct? It shows updatecharacterposition() and the lines after it inside the for event in pygame.event.get(): loop.

If that is really the case, then none of that code will get called if you are not getting any events. That would cause all of the movement to stop.

Try this:

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             pygame.quit()
             run = False
             continue
    updatecharacterposition()
    collided = checkforbarriercollision()
    badguy.move(character)
    if collided:
        print("YOU LOST")
        pygame.quit()
        time.sleep(5)
    redrawgamewindow()

On a side note, it seems odd to me that badguy.move(character) is after the collision check. Usually you would move everything (the player and the 'badguy') and then do the collision check.


来源: stackexchange

问:
Aspect does not trigger around repositories in my application
I want to trigger my aspect for classes annotated with repositories and belonging to my packages, for example this one:

//com.foo.myapp.bar.repositories.dao
@Repository
public class MyRepo extends JpaRepository<MyEntity, String>{
```

<p>My classes are jpa repositories created like this:</p>

```@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "firstManagerFactory",
    transactionManagerRef = "firstTransactionManager",
    basePackages = {"com.foo.myapp.bar.repositories.first.dao"}
```

<p>)
public class DbConfig {</p>

<p>My aspect is the following but only activates if I leave the repository() pointcut, but if I also specify application packages it doesn't work:</p>

<pre class="lang-java prettyprint-override"><code>@Pointcut("within(@org.springframework.stereotype.Repository *)")
private void repositoryInvocation() {
    // Method is empty as this is just a Pointcut, the implementations are in the advices.
}

@Pointcut("within(com.foo.myapp..*)")
public void applicationPackage() {
    // Method is empty as this is just a Pointcut, the implementations are in the advices.
}

@Around("repositoryInvocation() && applicationPackage()") //this && doesn't work, I have to remove the second one
public Object aspectTriggers(ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = joinPoint.proceed();
    return result;
}
</code>```

What am I missing?

edit:

I think I got it: problem is that the implementation of the repository does not belong to my application package, but to spring's SimpleJPARepository. It's like the aspect is only working on the implementation, totally ignoring the interface.

答:
I think you do not want

@Pointcut("within(@org.springframework.stereotype.Repository *)")
```

<p>but rather</p>

<pre class="lang-java prettyprint-override"><code>@Pointcut("@within(org.springframework.stereotype.Repository)")
</code>```

Be careful with your pointcut syntax, the two are not the same:

within() describes a package or class name you want to scope/limit your pointcut to.

@within() looks for a type (class) with the given annotation.

You want the latter, not the former.

Edit: On a second thought, actually I see no obvious reason why the first version should not work, even though it is a bit more complicated than the second.

But you said that you had problems with the second pointcut anyway. Are you 100% sure that your repository class really is in a com.foo.myapp (sub) package? No typo in either the package name or the pointcut? Actually, without trying and only looking at it, it should work otherwise.

ContentLicense: CC BY-SA 4.0

Body:
I want to trigger my aspect for classes annotated with repositories and belonging to my packages, for example this one:

//com.foo.myapp.bar.repositories.dao
@Repository
public class MyRepo extends JpaRepository<MyEntity, String>{

My classes are jpa repositories created like this:

@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "firstManagerFactory",
    transactionManagerRef = "firstTransactionManager",
    basePackages = {"com.foo.myapp.bar.repositories.first.dao"}

)
public class DbConfig {

My aspect is the following but only activates if I leave the repository() pointcut, but if I also specify application packages it doesn't work:

@Pointcut("within(@org.springframework.stereotype.Repository *)")
private void repositoryInvocation() {
    // Method is empty as this is just a Pointcut, the implementations are in the advices.
}

@Pointcut("within(com.foo.myapp..*)")
public void applicationPackage() {
    // Method is empty as this is just a Pointcut, the implementations are in the advices.
}

@Around("repositoryInvocation() && applicationPackage()") //this && doesn't work, I have to remove the second one
public Object aspectTriggers(ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = joinPoint.proceed();
    return result;
}

What am I missing?

edit:

I think I got it: problem is that the implementation of the repository does not belong to my application package, but to spring's SimpleJPARepository. It's like the aspect is only working on the implementation, totally ignoring the interface.

Body:
I think you do not want

@Pointcut("within(@org.springframework.stereotype.Repository *)")

but rather

@Pointcut("@within(org.springframework.stereotype.Repository)")

Be careful with your pointcut syntax, the two are not the same:

within() describes a package or class name you want to scope/limit your pointcut to.

@within() looks for a type (class) with the given annotation.

You want the latter, not the former.

Edit: On a second thought, actually I see no obvious reason why the first version should not work, even though it is a bit more complicated than the second.

But you said that you had problems with the second pointcut anyway. Are you 100% sure that your repository class really is in a com.foo.myapp (sub) package? No typo in either the package name or the pointcut? Actually, without trying and only looking at it, it should work otherwise.


问:
CS8766: Nullability of reference types in return type doesn't match implicitly implemented member
I've enabled Nullable References in my C# 8.0 project.  I've also set all warnings as errors to force myself to address all such warnings.  But one of them is confusing me.  It is a dependency property that returns an interface pointer that might validly be null.  Here is the property (inside a control called "LayerView")

```<code>private static readonly DependencyProperty ShapeBeingDrawnProperty = DependencyProperty.Register(
    nameof(ShapeBeingDrawn),
    typeof(IShape),
    typeof(LayerView),
    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));

public IShape ShapeBeingDrawn
{
    get => GetValue(ShapeBeingDrawnProperty) as IShape;  // RIGHT SIDE OF "=>" UNDERLINED IN RED
    set => SetValue(ShapeBeingDrawnProperty, value);
}
</code>```

With nullable references enabled, this understandably causes a warning on the getter.  The entire right side of the get is underlined in red and I get this build error

```<code>1>C:\Users\jmole\Documents\Dev\Mobile\Core\Views\LayerView.xaml.cs(429,13,429,16): error CS8766:
Nullability of reference types in return type of 'IShape? LayerView.ShapeBeingDrawn.get' doesn't
match implicitly implemented member 'IShape ILayerView.ShapeBeingDrawn.get' (possibly because of
nullability attributes).
</code>```

First of all,  what "implicitly" implemented member are they talking about?  This is an explicitly implemented member.  I am literally implementing it right here.  But that aside, I tried to fix this as I've fixed many other such validly nullable properties:  Make the property return a nullable reference

```<code>public IShape? ShapeBeingDrawn     // ONLY CHANGE IS HERE
{
    get => GetValue(ShapeBeingDrawnProperty) as IShape; // NOW, JUST "get" IS UNDERLINED IN RED
    set => SetValue(ShapeBeingDrawnProperty, value);
}
</code>```

Unfortunately, this does not help.  I still get the same error but this time the only part underlined in red is just the left side of the getter (the word "get").

Finally I was able to eliminate this error by changing the property back to a normal reference and using a hard cast in the getter

```<code>public IShape ShapeBeingDrawn
{
    get => (IShape)GetValue(ShapeBeingDrawnProperty);
    set => SetValue(ShapeBeingDrawnProperty, value);
}
</code>```

But now, any code that tries to set this property to null (which is valid) gets a compiler error and I have to address that.

```<code>private void LayerView_OnKeyDown(object sender, KeyEventArgs e)
{
    // Don't do anything if we've disabled shape mouse/touch input.

    if (e.Key != Key.Escape)
        return;

    UnselectAll();
    ShapeBeingDrawn = null;  // COMPILER NO LIKEY
}
</code>```

So what is the proper way to integrate nullable references and dependency properties?  Should I just #pragma warning disable around such problems?  I'd like to avoid that if I can.

答:
TL;DR

The problem occurs because property ShapeBeingDrawn is declared as non-nullable reference type IShape in the interface ILayerView, but in the class LayerView it is implemented as nullable reference type IShape?. Therefore compiler complains that return type of the property in the class does not match the return type in the interface.

To fix the problem we should ensure that both the interface and the class declare the property as nullable or non-nullable. If in one of them the declaration differs then we will again get compiler error.

Explanation

Why does the problem occur?

error CS8766: Nullability of reference types in return type of
'IShape? LayerView.ShapeBeingDrawn.get' doesn't match implicitly
implemented member 'IShape ILayerView.ShapeBeingDrawn.get' (possibly
because of nullability attributes).

From the error message we can see that there is an interface ILayerView with a non-nullable property ShapeBeignDrawn:

```<code>interface ILayerView
{
    IShape ShapeBeingDrawn { get; set; }
}
</code>```

and a class LayerView that implements this interface but declares property ShapeBeignDrawn as nullable:

```<code>public class LayerView
{
    public IShape? ShapeBeingDrawn
    {
        get => GetValue(ShapeBeingDrawnProperty) as IShape;
        set => SetValue(ShapeBeingDrawnProperty, value);
    }
}
</code>```

So the interface declares property as non-nullable but the class implements it as nullable. Therefore compiler complains that return type of the getter of the property in the class does not match the return type in the interface.

Question:

First of all, what "implicitly" implemented member are they talking
about?

Answer:

When we declare a property compiler implicitly generates for it two methods: get_PropertyName and set_PropertyName. Therefore compiler complains for the return type of the implicitly implemented getter method.

How should we fix the problem?

To fix the problem we should ensure that both an interface and a class declare a property as nullable or non-nullable. If in one of them the declaration differs then we will again get compiler error CS8766.

Here is a code sample that reproduces the problem and gives a hint how to fix it.

Body:
I've enabled Nullable References in my C# 8.0 project.  I've also set all warnings as errors to force myself to address all such warnings.  But one of them is confusing me.  It is a dependency property that returns an interface pointer that might validly be null.  Here is the property (inside a control called "LayerView")

private static readonly DependencyProperty ShapeBeingDrawnProperty = DependencyProperty.Register(
    nameof(ShapeBeingDrawn),
    typeof(IShape),
    typeof(LayerView),
    new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));

public IShape ShapeBeingDrawn
{
    get => GetValue(ShapeBeingDrawnProperty) as IShape;  // RIGHT SIDE OF "=>" UNDERLINED IN RED
    set => SetValue(ShapeBeingDrawnProperty, value);
}

With nullable references enabled, this understandably causes a warning on the getter.  The entire right side of the get is underlined in red and I get this build error

1>C:\Users\jmole\Documents\Dev\Mobile\Core\Views\LayerView.xaml.cs(429,13,429,16): error CS8766:
Nullability of reference types in return type of 'IShape? LayerView.ShapeBeingDrawn.get' doesn't
match implicitly implemented member 'IShape ILayerView.ShapeBeingDrawn.get' (possibly because of
nullability attributes).

First of all,  what "implicitly" implemented member are they talking about?  This is an explicitly implemented member.  I am literally implementing it right here.  But that aside, I tried to fix this as I've fixed many other such validly nullable properties:  Make the property return a nullable reference

public IShape? ShapeBeingDrawn     // ONLY CHANGE IS HERE
{
    get => GetValue(ShapeBeingDrawnProperty) as IShape; // NOW, JUST "get" IS UNDERLINED IN RED
    set => SetValue(ShapeBeingDrawnProperty, value);
}

Unfortunately, this does not help.  I still get the same error but this time the only part underlined in red is just the left side of the getter (the word "get").

Finally I was able to eliminate this error by changing the property back to a normal reference and using a hard cast in the getter

public IShape ShapeBeingDrawn
{
    get => (IShape)GetValue(ShapeBeingDrawnProperty);
    set => SetValue(ShapeBeingDrawnProperty, value);
}

But now, any code that tries to set this property to null (which is valid) gets a compiler error and I have to address that.

private void LayerView_OnKeyDown(object sender, KeyEventArgs e)
{
    // Don't do anything if we've disabled shape mouse/touch input.

    if (e.Key != Key.Escape)
        return;

    UnselectAll();
    ShapeBeingDrawn = null;  // COMPILER NO LIKEY
}

So what is the proper way to integrate nullable references and dependency properties?  Should I just #pragma warning disable around such problems?  I'd like to avoid that if I can.

Body:
TL;DR

The problem occurs because property ShapeBeingDrawn is declared as non-nullable reference type IShape in the interface ILayerView, but in the class LayerView it is implemented as nullable reference type IShape?. Therefore compiler complains that return type of the property in the class does not match the return type in the interface.

To fix the problem we should ensure that both the interface and the class declare the property as nullable or non-nullable. If in one of them the declaration differs then we will again get compiler error.

Explanation

Why does the problem occur?

error CS8766: Nullability of reference types in return type of
'IShape? LayerView.ShapeBeingDrawn.get' doesn't match implicitly
implemented member 'IShape ILayerView.ShapeBeingDrawn.get' (possibly
because of nullability attributes).

From the error message we can see that there is an interface ILayerView with a non-nullable property ShapeBeignDrawn:

interface ILayerView
{
    IShape ShapeBeingDrawn { get; set; }
}

and a class LayerView that implements this interface but declares property ShapeBeignDrawn as nullable:

public class LayerView
{
    public IShape? ShapeBeingDrawn
    {
        get => GetValue(ShapeBeingDrawnProperty) as IShape;
        set => SetValue(ShapeBeingDrawnProperty, value);
    }
}

So the interface declares property as non-nullable but the class implements it as nullable. Therefore compiler complains that return type of the getter of the property in the class does not match the return type in the interface.

Question:

First of all, what "implicitly" implemented member are they talking
about?

Answer:

When we declare a property compiler implicitly generates for it two methods: get_PropertyName and set_PropertyName. Therefore compiler complains for the return type of the implicitly implemented getter method.

How should we fix the problem?

To fix the problem we should ensure that both an interface and a class declare a property as nullable or non-nullable. If in one of them the declaration differs then we will again get compiler error CS8766.

Here is a code sample that reproduces the problem and gives a hint how to fix it.


问:
How to use TScrollbar to richedit;
How to use Tscrollbar to Richedit.

My purpose is to separate the scrollbar in a deferent panel.

is it possible?

答:
I am not sure I understand the question, but if I get it right, your best bet is probably have the rich edit in a scroll box and use windows messages to synchronize the two.

Andrea

ContentLicense: CC BY-SA 3.0

Title: How to use TScrollbar to richedit;


问:
Trouble Getting Changeset Details With Powershell From Within CI Build
I am trying to implement the powershell code that is mentioned in the answer to the following question.
Triggering Azure DevOps builds based on changes to sub folders

My simple attempt to access DevOps results in the following error.

This is the simple powershell code I am trying first. It is the code that caused the error depicted above.

tf changeset /collection:"https://*******.visualstudio.com/******************" 25490

答:
Trouble Getting Changeset Details With Powershell From Within CI Build

I could reproduce this issue with error URL in parameter /collection:TeamProjectCollectionUrl or do not have permission to access the corresponding collection.

To resolve this issue, first, we nee make sure the URL is correct. The URL should be the Team Project Collection:

```<code>tf changeset /collection:http://***.visualstudio.com/YourCollectionName
</code>```

Second, if you do not have permission to access that collection, please add a PAT, which have permission to access that collection to the URL:

```<code>tf changeset /collection:http://<YouPATHere>@***.visualstudio.com/YourCollectionName
</code>```

As test, it works fine on my side:

```<code>tf changeset /collection:http://<PAT>@.visualstudio.com/DefaultCollection 138
</code>```

Hope this helps.

Body:
Trouble Getting Changeset Details With Powershell From Within CI Build

I could reproduce this issue with error URL in parameter /collection:TeamProjectCollectionUrl or do not have permission to access the corresponding collection.

To resolve this issue, first, we nee make sure the URL is correct. The URL should be the Team Project Collection:

tf changeset /collection:http://***.visualstudio.com/YourCollectionName

Second, if you do not have permission to access that collection, please add a PAT, which have permission to access that collection to the URL:

tf changeset /collection:http://<YouPATHere>@***.visualstudio.com/YourCollectionName

As test, it works fine on my side:

tf changeset /collection:http://<PAT>@.visualstudio.com/DefaultCollection 138

Hope this helps.


问:
EF Data migrations won't detect changes when adding new migration
I am using Entity Framework 5.0 Data migrations along with code first.
When i add a new field to my model and execute the following command in the package manager console.

```<code> "Add-migration AddedField"
</code>```

All I get is an empty migration called "n_AddedField", the up and down methods contain no logic.

I tried a bunch of things, reinstalling the EF nuget package, cleaning my solution, rebuilding, manually removing all generated files and directories.

Then i decided that i would scrap all my migrations and start over, and then it got weird.
After deleting all my migrations, and the migrationhistory table in the database, i recreated the database using the CreateDatabaseIfNotExists initializer. After doing this, I should be able to create a new initial migration. But when i try to create create a new migration, I get an error saying that there are pending migrations, and lists all the migrations that i just deleted from my project.

I have no idea why and how EF still has any recollection of those migrations.
I even tried searching through filecontents looking if the migrations were saved somewhere else or something. But nothing..

Data migrations look really neat when scott hansleman demo's it on stage, but for real work, I'm starting to look for alternatives.

When the project started, we were using EF 4.x and a while back switcted to 5.0, but since the switch i have added a bunch of migrations successfully.

Does anyone have any idea how to solve this problem?
Basically i just want to be able to add migrations, and generate a sql script with the changes.

答: I had to run dotnet ef migrations remove even though I'd deleted the previous migration

Body:
I am using Entity Framework 5.0 Data migrations along with code first.
When i add a new field to my model and execute the following command in the package manager console.

 "Add-migration AddedField"

All I get is an empty migration called "n_AddedField", the up and down methods contain no logic.

I tried a bunch of things, reinstalling the EF nuget package, cleaning my solution, rebuilding, manually removing all generated files and directories.

Then i decided that i would scrap all my migrations and start over, and then it got weird.
After deleting all my migrations, and the migrationhistory table in the database, i recreated the database using the CreateDatabaseIfNotExists initializer. After doing this, I should be able to create a new initial migration. But when i try to create create a new migration, I get an error saying that there are pending migrations, and lists all the migrations that i just deleted from my project.

I have no idea why and how EF still has any recollection of those migrations.
I even tried searching through filecontents looking if the migrations were saved somewhere else or something. But nothing..

Data migrations look really neat when scott hansleman demo's it on stage, but for real work, I'm starting to look for alternatives.

When the project started, we were using EF 4.x and a while back switcted to 5.0, but since the switch i have added a bunch of migrations successfully.

Does anyone have any idea how to solve this problem?
Basically i just want to be able to add migrations, and generate a sql script with the changes.


问:
Pandas: Inserting new row based on date condition for each group
I have a dataframe like below:

```<code>  Date        Group   Value   Duration
2018-01-01      A      20       30
2018-02-01      A      10       60
2018-01-01      B      15      180
2018-02-01      B      30      210
2018-03-01      B      25      238
2018-01-01      C      10      235
</code>```

In the above df, we see that for group A last date is 2018-02-01. And I want to insert a row with Date as 2018-03-01 and duplicate the values of the previous row. So in other words, for each group, I want equal number of row count by inserting a duplicating row till the Date reaches 2018-03-01.

My resultant Dataframe would look like

```<code>  Date        Group   Value   Duration
2018-01-01      A      20       30
2018-02-01      A      10       60
2018-03-01      A      10       60   <----New Row
2018-01-01      B      15      180
2018-02-01      B      30      210
2018-03-01      B      25      238
2018-01-01      C      10      235
2018-02-01      C      10      235  <----New Row
2018-03-01      C      10      235  <----New Row
</code>```

N.B.: We can have 0 values for new row instead of duplication from last existing row.

I am trying to achieve the above by the following codes but not able to progress further:

```<code>max_d = df.loc[df.groupby(['Group'])['Date'].idxmax()]
for k,v in df.groupby(['Group']):
   if k['Date'].max() < max_d['Date'].max():
      last_row = 0 <----or k.iloc[-1]
      last_row['Date'] = pd.DateOffset(month=1)
      k.append(last_row)
</code>```

But I am getting error as:

```<code>  Traceback (most recent call last):
File "<ipython-input-6-44d0a094516e>", line 2, in <module>
  if k['Date'].max() < max_d['Date'].max():
TypeError: 'int' object is not subscriptable
</code>```

Am I missing out anything in the above code? Any clue will be appreciated.

Body:
I have a dataframe like below:

  Date        Group   Value   Duration
2018-01-01      A      20       30
2018-02-01      A      10       60
2018-01-01      B      15      180
2018-02-01      B      30      210
2018-03-01      B      25      238
2018-01-01      C      10      235

In the above df, we see that for group A last date is 2018-02-01. And I want to insert a row with Date as 2018-03-01 and duplicate the values of the previous row. So in other words, for each group, I want equal number of row count by inserting a duplicating row till the Date reaches 2018-03-01.

My resultant Dataframe would look like

  Date        Group   Value   Duration
2018-01-01      A      20       30
2018-02-01      A      10       60
2018-03-01      A      10       60   <----New Row
2018-01-01      B      15      180
2018-02-01      B      30      210
2018-03-01      B      25      238
2018-01-01      C      10      235
2018-02-01      C      10      235  <----New Row
2018-03-01      C      10      235  <----New Row

N.B.: We can have 0 values for new row instead of duplication from last existing row.

I am trying to achieve the above by the following codes but not able to progress further:

max_d = df.loc[df.groupby(['Group'])['Date'].idxmax()]
for k,v in df.groupby(['Group']):
   if k['Date'].max() < max_d['Date'].max():
      last_row = 0 <----or k.iloc[-1]
      last_row['Date'] = pd.DateOffset(month=1)
      k.append(last_row)

But I am getting error as:

  Traceback (most recent call last):
File "<ipython-input-6-44d0a094516e>", line 2, in <module>
  if k['Date'].max() < max_d['Date'].max():
TypeError: 'int' object is not subscriptable

Am I missing out anything in the above code? Any clue will be appreciated.

Body:
Use pd.MultiIndex to reindex your df:

df["Date"] = pd.to_datetime(df["Date"])

s = pd.MultiIndex.from_product([df["Date"].unique(),df["Group"].unique()],names=["Date","Group"])

print (df.set_index(["Date","Group"]).reindex(s)
       .reset_index()
       .sort_values(["Group","Date"])
       .ffill())

        Date Group  Value  Duration
0 2018-01-01     A   20.0      30.0
3 2018-02-01     A   10.0      60.0
6 2018-03-01     A   10.0      60.0
1 2018-01-01     B   15.0     180.0
4 2018-02-01     B   30.0     210.0
7 2018-03-01     B   25.0     238.0
2 2018-01-01     C   10.0     235.0
5 2018-02-01     C   10.0     235.0
8 2018-03-01     C   10.0     235.0


问:
conditional repository injection - Spring Boot
I Have two repository interfaces that connect MongoDB and CouchBase :

public interface UserRepositoryMongo extends MongoRepository<User, Long> {
}
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long> {
}

```
<p>Is there a way to interchangeably <code>@Autowire</code> these repositories into <code>UserService</code> on a condition?
The condition will be inside property file :  <code>application.properties</code>.</p>
```

**Note :**

*These repositories can have custom methods too.*
```

答:
We can use either ConditionalOnProperty or ConditionalOnExpression to switch between two different repository implementation.

If we want to control the autowiring with simple property presence/absence or property value, then ConditionalOnProperty can be used.

If complex evaluation is required, then we can use ConditionalOnExpression.

ConditionalOnProperty (presence/absence of a property)

```<code>@Qualifier("specificRepo")
@ConditionalOnProperty("mongo.url")
public interface UserRepositoryMongo extends MongoRepository<User, Long>{
}

@Qualifier("specificRepo")
@ConditionalOnProperty("couch.url")
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long>{
}
</code>```

ConditionalOnProperty (based on value)

```<code>@ConditionalOnProperty("repo.url", havingValue="mongo", matchIfMissing = true) //this will be default implementation if no value is matching
public interface UserRepositoryMongo extends MongoRepository<User, Long> {
}

@ConditionalOnProperty("repo.url", havingValue="couch")
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long> {
}
</code>```

ConditionalOnExpression

```<code>@ConditionalOnExpression("#{'${repository.url}'.contains('couch')}")
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long> {
}
</code>```

UPDATE

Use CrudRepository/Repository type to inject based on your requirement.

```<code>public class DemoService {

    @Autowired
    @Qualifier("specificRepo")
    private CrudRepository repository;
}
</code>```

Based on bean created, either UserRepositoryMongo or UserRepositoryCouch will be autowired. Make sure only one bean is instantiated to avoid ambiguity error.

Body:
I Have two repository interfaces that connect MongoDB and CouchBase :

public interface UserRepositoryMongo extends MongoRepository<User, Long> {
}
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long> {
}

Is there a way to interchangeably @Autowire these repositories into UserService on a condition?
The condition will be inside property file :  application.properties.

**Note :**

*These repositories can have custom methods too.*

Body:
We can use either ConditionalOnProperty or ConditionalOnExpression to switch between two different repository implementation.

If we want to control the autowiring with simple property presence/absence or property value, then ConditionalOnProperty can be used.

If complex evaluation is required, then we can use ConditionalOnExpression.

ConditionalOnProperty (presence/absence of a property)

@Qualifier("specificRepo")
@ConditionalOnProperty("mongo.url")
public interface UserRepositoryMongo extends MongoRepository<User, Long>{
}

@Qualifier("specificRepo")
@ConditionalOnProperty("couch.url")
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long>{
}

ConditionalOnProperty (based on value)

@ConditionalOnProperty("repo.url", havingValue="mongo", matchIfMissing = true) //this will be default implementation if no value is matching
public interface UserRepositoryMongo extends MongoRepository<User, Long> {
}

@ConditionalOnProperty("repo.url", havingValue="couch")
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long> {
}

ConditionalOnExpression

@ConditionalOnExpression("#{'${repository.url}'.contains('couch')}")
public interface UserRepositoryCouch extends  CouchbasePagingAndSortingRepository<User, Long> {
}

UPDATE

Use CrudRepository/Repository type to inject based on your requirement.

public class DemoService {

    @Autowired
    @Qualifier("specificRepo")
    private CrudRepository repository;
}

Based on bean created, either UserRepositoryMongo or UserRepositoryCouch will be autowired. Make sure only one bean is instantiated to avoid ambiguity error.


问:
How to parse URLs in Google Apps Script?
I have a GAS project and I need to parse some URLs into their hostname and pathname properties as follows.

Code.gs

```<code>const url = new URL( 'http://www.example.com/cats', );
const { hostname,  pathname, } = url;
</code>```

Here are some docs on the above URL constructor method. [1] | [2]

The above code produces the following error.

Error message:

ReferenceError: URL is not defined (line 64, file "Code")

What am I missing? How can I parse my URLs using GAS?

答:
This article explains how to implement the URI.js library into a Google Apps Script project.

URIjs.gs

```<code>eval(UrlFetchApp.fetch('https://rawgit.com/medialize/URI.js/gh-pages/src/URI.js').getContentText());

// Get the URL protocol (eg. 'https' or 'http')
function urlProtocol(url){
  return URI(url).protocol()
}

// Get the URL hostname (eg. 'googleappscripting.com')
function urlHostname(url){
  return URI(url).hostname()
}

// Get the whole URL path (eg. '/some/directory/filename.png')
function urlPath(url){
  return URI(url).path()
}

// Get the URL directory (eg. '/some/directory')
function urlDirectory(url){
  return URI(url).directory()
}

// Get the URL file name (eg. 'filename.png')
function urlFilename(url){
  return URI(url).filename()
}

// Get the URL query string (eg. 'this=1&that=2')
// If a query string parameter is provided as the second argument
// then the function will return the value of that parameter
function urlQuery(url,param){
  if (param !== undefined){
    var queryMap = URI(url).query(true);
    return queryMap[param]
  }
  return URI(url).query()
}

// Get the URL hash (eg. '#section-two')
function urlHash(url){
  return URI(url).hash()
}

// Check to see if a URL is a fully qualified URL
function urlIsUrl(url){
  return URI(url).is('url')
}

// Check to see if a URL is a fully qualified IP Address
function urlIsIp(url){
    return URI(url).is('ip')
}

// Test function to ensure that each of the above functions do what they are supposed to do.
function testURI() {

  var testUrl = 'https://googleappscripting.com/some/test/page.html?this-is=helpful&it=works#rad';
  var funcTests = [
    urlProtocol,
    urlHostname,
    urlDirectory,
    urlPath,
    urlFilename,
    urlQuery,
    urlHash,
    urlIsUrl,
    urlIsIp
  ]

  // Check that each function returns the expected value
  funcTests.forEach(function(test){
    Logger.log(test(testUrl))
  });

  // Extra check to see that the urlQuery function works with a query parameter argument
  Logger.log(urlQuery(testUrl,'it'));

}
</code>```

Then in my code, as follows:

Code.gs

```<code>const hostname = URIjs.urlHostname( 'http://www.example.com/cats', );
</code>```

Body:
I have a GAS project and I need to parse some URLs into their hostname and pathname properties as follows.

Code.gs

const url = new URL( 'http://www.example.com/cats', );
const { hostname,  pathname, } = url;

Here are some docs on the above URL constructor method. [1] | [2]

The above code produces the following error.

Error message:

ReferenceError: URL is not defined (line 64, file "Code")

What am I missing? How can I parse my URLs using GAS?

Body:
This article explains how to implement the URI.js library into a Google Apps Script project.

URIjs.gs

eval(UrlFetchApp.fetch('https://rawgit.com/medialize/URI.js/gh-pages/src/URI.js').getContentText());

// Get the URL protocol (eg. 'https' or 'http')
function urlProtocol(url){
  return URI(url).protocol()
}

// Get the URL hostname (eg. 'googleappscripting.com')
function urlHostname(url){
  return URI(url).hostname()
}

// Get the whole URL path (eg. '/some/directory/filename.png')
function urlPath(url){
  return URI(url).path()
}

// Get the URL directory (eg. '/some/directory')
function urlDirectory(url){
  return URI(url).directory()
}

// Get the URL file name (eg. 'filename.png')
function urlFilename(url){
  return URI(url).filename()
}

// Get the URL query string (eg. 'this=1&that=2')
// If a query string parameter is provided as the second argument
// then the function will return the value of that parameter
function urlQuery(url,param){
  if (param !== undefined){
    var queryMap = URI(url).query(true);
    return queryMap[param]
  }
  return URI(url).query()
}

// Get the URL hash (eg. '#section-two')
function urlHash(url){
  return URI(url).hash()
}

// Check to see if a URL is a fully qualified URL
function urlIsUrl(url){
  return URI(url).is('url')
}

// Check to see if a URL is a fully qualified IP Address
function urlIsIp(url){
    return URI(url).is('ip')
}

// Test function to ensure that each of the above functions do what they are supposed to do.
function testURI() {

  var testUrl = 'https://googleappscripting.com/some/test/page.html?this-is=helpful&it=works#rad';
  var funcTests = [
    urlProtocol,
    urlHostname,
    urlDirectory,
    urlPath,
    urlFilename,
    urlQuery,
    urlHash,
    urlIsUrl,
    urlIsIp
  ]

  // Check that each function returns the expected value
  funcTests.forEach(function(test){
    Logger.log(test(testUrl))
  });

  // Extra check to see that the urlQuery function works with a query parameter argument
  Logger.log(urlQuery(testUrl,'it'));

}

Then in my code, as follows:

Code.gs

const hostname = URIjs.urlHostname( 'http://www.example.com/cats', );


问:
Binary Search Tree insertion using C++ Class Segmentation fault
I'm trying to implement insertion for a Binary Search Tree class in C++ yet I keep getting segmentation fault. I'm trying to do it with only one class:

Here's my code:

```<code>class BinarySearchTree{
public:
BinarySearchTree(int n);
BinarySearchTree* tree;
BinarySearchTree* right;
BinarySearchTree* left;
int treekey;
BinarySearchTree* insert(int n, BinarySearchTree*& thetree);
}

BinarySearchTree::BinarySearchTree(int n){
tree = new BinarySearchTree();
tree->left = NULL;
tree->right = NULL;
tree->treekey = n;
cout<<"Treekey is "<<tree->treekey<<endl;
}

BinarySearchTree* BinarySearchTree::insert(int n, BinarySearchTree*& thetree){
cout<<"the tree tree key now is "<<thetree->treekey<<endl;
if(thetree == NULL){
    cout<<"is empty"<<endl;
    tree = new BinarySearchTree(n);
    return tree;
}
cout<<"not empty"<<endl;
cout<<"Treekey here is "<<thetree->treekey<<endl;
if(n<thetree->treekey){
    thetree->left = insert(n, thetree->left);
}else{
    thetree->right = insert(n, thetree->right);
}
return thetree;
}

int main(){
BinarySearchTree* newtree= new BinarySearchTree(16);
newtree -> insert(13, newtree);
return 0;
}
</code>```

My current code outputs:

```<code>Treekey is 16
the tree tree key now is -1550649400
not empty
Treekey here is -1550649400
Segmentation fault: 11
</code>```

Sorry that I'm really new to this. Please help me with this, thank you!

答:
Your code is basically fine, except that you are invoking undefined behavior when you access a member of theTree unconditionally. Just move that line after the check:

```<code>BinarySearchTree* BinarySearchTree::insert(int n, BinarySearchTree*& thetree){
  if(thetree == NULL){
     // ...
  }
  cout<<"the tree tree key now is "<<thetree->treekey<<endl;
  // ^^^^ moved this line to after the if
</code>```

Also, you are missing the default constructor for your class. You can reinstate it with:

```<code>BinarySearchTree() = default;
</code>```

Also, you should use give defaults to all your members:

```<code>BinarySearchTree* tree = nullptr;
BinarySearchTree* right = nullptr;
BinarySearchTree* left = nullptr;
int treekey{};
</code>```

Note that nullptr is what you should be using instead of NULL in your code.

Body:
I'm trying to implement insertion for a Binary Search Tree class in C++ yet I keep getting segmentation fault. I'm trying to do it with only one class:

Here's my code:

class BinarySearchTree{
public:
BinarySearchTree(int n);
BinarySearchTree* tree;
BinarySearchTree* right;
BinarySearchTree* left;
int treekey;
BinarySearchTree* insert(int n, BinarySearchTree*& thetree);
}

BinarySearchTree::BinarySearchTree(int n){
tree = new BinarySearchTree();
tree->left = NULL;
tree->right = NULL;
tree->treekey = n;
cout<<"Treekey is "<<tree->treekey<<endl;
}

BinarySearchTree* BinarySearchTree::insert(int n, BinarySearchTree*& thetree){
cout<<"the tree tree key now is "<<thetree->treekey<<endl;
if(thetree == NULL){
    cout<<"is empty"<<endl;
    tree = new BinarySearchTree(n);
    return tree;
}
cout<<"not empty"<<endl;
cout<<"Treekey here is "<<thetree->treekey<<endl;
if(n<thetree->treekey){
    thetree->left = insert(n, thetree->left);
}else{
    thetree->right = insert(n, thetree->right);
}
return thetree;
}

int main(){
BinarySearchTree* newtree= new BinarySearchTree(16);
newtree -> insert(13, newtree);
return 0;
}

My current code outputs:

Treekey is 16
the tree tree key now is -1550649400
not empty
Treekey here is -1550649400
Segmentation fault: 11

Sorry that I'm really new to this. Please help me with this, thank you!

Body:
Your code is basically fine, except that you are invoking undefined behavior when you access a member of theTree unconditionally. Just move that line after the check:

BinarySearchTree* BinarySearchTree::insert(int n, BinarySearchTree*& thetree){
  if(thetree == NULL){
     // ...
  }
  cout<<"the tree tree key now is "<<thetree->treekey<<endl;
  // ^^^^ moved this line to after the if

Also, you are missing the default constructor for your class. You can reinstate it with:

BinarySearchTree() = default;

Also, you should use give defaults to all your members:

BinarySearchTree* tree = nullptr;
BinarySearchTree* right = nullptr;
BinarySearchTree* left = nullptr;
int treekey{};

Note that nullptr is what you should be using instead of NULL in your code.


问:
Test fails when @AfterTest annotation is changed to @Test
I have following class file

```<code>public class AuthenticationTest extends Base {
    private static Logger log = LogManager.getLogger(AuthenticationTest.class.getName());
    private static WebDriver driver;
    LoginPageFactory lp;

    @BeforeTest
    public void initialize() {
        //ExtentReport.config(LoginTest.class.getName());
        log.debug("Initializing WebDriver");
        driver = getDriver();
        log.debug("Driver is Initialized");
        driver.get(p.getProperty("url"));
        log.debug("Navigated to Login page");

    }

    @Test
    public void login() {

                try {

                Map<String,String> data = ExcelUtil.getData("R1SanityTestData.xlsx", "LoginTest", "ValidLoginTest");

                lp = new LoginPageFactory(driver);
                log.debug("LoginPageFactory class initialized");

                lp.txtUsername().click();
                lp.txtUsername().clear();
                lp.txtUsername().sendKeys(data.get("UserName"));
                log.debug("Username entered");
                lp.txtPassword().clear();
                lp.txtPassword().sendKeys(data.get("Password"));
                log.debug("Password entered");
                lp.btnLogin().click();
                log.debug("Login button clicked");

                LandingPageFactory lpf = new LandingPageFactory(driver);

                Assert.assertEquals(lpf.lblAppName().getText(), "OD App");
                Assert.assertTrue(lpf.iconProfile().isDisplayed());
                log.info("Login Success");
                String path = Screenshot.takeScreenshot(driver, "LoginTest/LoginStatus");
                }
                catch(IOException e) {
                    log.fatal("IOException in LoginTest");
                    log.fatal(e.getMessage() +" : " + e.getStackTrace());
                    driver.quit();
                }
                catch(NoSuchElementException e){
                    log.fatal("NosuchElementException in LoginTest");
                    log.fatal(e.getMessage() +" : " + e.getStackTrace());
                    driver.quit();
                }

                catch(Exception e) {
                    log.fatal("Exception in LoginTest");
                    log.fatal(e.getMessage() +" : " + e.getStackTrace());
                    driver.quit();
                }

    }

    @AfterTest
    public void logOut() {
        CommonPageFactory cpf = new CommonPageFactory(driver);
        cpf.linkViewProfile().click();
        log.debug("View Profile Clicked");
        cpf.linkLogOut().click();
        log.debug("Log Out Clicked");
        driver.quit();
    }
}
</code>```

When I run this class individually (Run AS --> TestNG Test), then above test works fine. But when I change the annotation of the logOut() method to @Test then login method passes but takes quite a lot of time to execute and logOut test fails with org.openqa.selenium.NoSuchElementException for first element.

Console output:
[RemoteTestNG] detected TestNG version 7.0.1
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d833300373761342c20cd-refs/branch-heads/4103@{#416}) on port 42250
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
May 31, 2020 8:14:54 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
PASSED: login
FAILED: logOut
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"span[data-aura-class='uiImage']"}
  (Session info: chrome=83.0.4103.61)

My WebDriver is static and is derived from the Base class. I am using test 7.1.0. What could be the issue?

I searched on the forum but could not find the answer.

答:
Try using dependsOn or use a priority in your test annotations. @Test methods are not always executed in the same order as they are written. Also if the Tests are run in parallel this would be an issue as well. Since logOut is completely dependent on the login method, try using

```<code>@Test(dependsOnMethods ="login")
public void logOut() {
....}
</code>```

dependsOn will make sure to run the logOut method only after the login method has completed successfully or passed.

Body:
I have following class file

public class AuthenticationTest extends Base {
    private static Logger log = LogManager.getLogger(AuthenticationTest.class.getName());
    private static WebDriver driver;
    LoginPageFactory lp;

    @BeforeTest
    public void initialize() {
        //ExtentReport.config(LoginTest.class.getName());
        log.debug("Initializing WebDriver");
        driver = getDriver();
        log.debug("Driver is Initialized");
        driver.get(p.getProperty("url"));
        log.debug("Navigated to Login page");

    }

    @Test
    public void login() {

                try {

                Map<String,String> data = ExcelUtil.getData("R1SanityTestData.xlsx", "LoginTest", "ValidLoginTest");

                lp = new LoginPageFactory(driver);
                log.debug("LoginPageFactory class initialized");

                lp.txtUsername().click();
                lp.txtUsername().clear();
                lp.txtUsername().sendKeys(data.get("UserName"));
                log.debug("Username entered");
                lp.txtPassword().clear();
                lp.txtPassword().sendKeys(data.get("Password"));
                log.debug("Password entered");
                lp.btnLogin().click();
                log.debug("Login button clicked");

                LandingPageFactory lpf = new LandingPageFactory(driver);

                Assert.assertEquals(lpf.lblAppName().getText(), "OD App");
                Assert.assertTrue(lpf.iconProfile().isDisplayed());
                log.info("Login Success");
                String path = Screenshot.takeScreenshot(driver, "LoginTest/LoginStatus");
                }
                catch(IOException e) {
                    log.fatal("IOException in LoginTest");
                    log.fatal(e.getMessage() +" : " + e.getStackTrace());
                    driver.quit();
                }
                catch(NoSuchElementException e){
                    log.fatal("NosuchElementException in LoginTest");
                    log.fatal(e.getMessage() +" : " + e.getStackTrace());
                    driver.quit();
                }

                catch(Exception e) {
                    log.fatal("Exception in LoginTest");
                    log.fatal(e.getMessage() +" : " + e.getStackTrace());
                    driver.quit();
                }

    }

    @AfterTest
    public void logOut() {
        CommonPageFactory cpf = new CommonPageFactory(driver);
        cpf.linkViewProfile().click();
        log.debug("View Profile Clicked");
        cpf.linkLogOut().click();
        log.debug("Log Out Clicked");
        driver.quit();
    }
}

When I run this class individually (Run AS --> TestNG Test), then above test works fine. But when I change the annotation of the logOut() method to @Test then login method passes but takes quite a lot of time to execute and logOut test fails with org.openqa.selenium.NoSuchElementException for first element.

Console output:
[RemoteTestNG] detected TestNG version 7.0.1
Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d833300373761342c20cd-refs/branch-heads/4103@{#416}) on port 42250
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
May 31, 2020 8:14:54 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
PASSED: login
FAILED: logOut
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"span[data-aura-class='uiImage']"}
  (Session info: chrome=83.0.4103.61)

My WebDriver is static and is derived from the Base class. I am using test 7.1.0. What could be the issue?

I searched on the forum but could not find the answer.

Body:
Try using dependsOn or use a priority in your test annotations. @Test methods are not always executed in the same order as they are written. Also if the Tests are run in parallel this would be an issue as well. Since logOut is completely dependent on the login method, try using

@Test(dependsOnMethods ="login")
public void logOut() {
....}

dependsOn will make sure to run the logOut method only after the login method has completed successfully or passed.


问:
Azure Subscription: using Certificate or AAD authentication on PowerShell?
I'm currently using AAD authentication for deploying some code but I'm finding that my session times out on the server, which requires me to log back in.

I heard I could use certificates to authenticate to Azure, is this the way to go or is there a different method people use?

答:
If your AAD authentication session times out in a short time, you could consider configuring token lifetimes in Azure Active Directory.

An Powershell cmd sample:

```<code>$policy = New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"02:00:00","MaxAgeSessionSingleFactor":"02:00:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"
</code>```

More samples here.

Body:
If your AAD authentication session times out in a short time, you could consider configuring token lifetimes in Azure Active Directory.

An Powershell cmd sample:

$policy = New-AzureADPolicy -Definition @('{"TokenLifetimePolicy":{"Version":1,"AccessTokenLifetime":"02:00:00","MaxAgeSessionSingleFactor":"02:00:00"}}') -DisplayName "WebPolicyScenario" -IsOrganizationDefault $false -Type "TokenLifetimePolicy"

More samples here.


问:
Binary serialization protocol
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

```<code>class Person
{
   int age;
   string name;
};
</code>```

Java class

```<code>class Person
{
   int age;
   String name;
}
</code>```

C++ encoding

```<code>Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);
</code>```

Java decoding

```<code>byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);
</code>```

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

答:
You can check the amef protocol, an example of C++ encoding in amef would be like,

```<code>    //Create a new AMEF object
    AMEFObject *object = new AMEFObject();

    //Add a child string object
    object->addPacket("This is the Automated Message Exchange Format Object property!!","adasd");

    //Add a child integer object
    object->addPacket(21213);

    //Add a child boolean object
    object->addPacket(true);

    AMEFObject *object2 = new AMEFObject();
    string j = "This is the property of a nested Automated Message Exchange Format Object";
    object2->addPacket(j);
    object2->addPacket(134123);
    object2->addPacket(false);

    //Add a child character object
    object2->addPacket('d');

    //Add a child AMEF Object
    object->addPacket(object2);

    //Encode the AMEF obejct
    string str = new AMEFEncoder()->encode(object,false);
</code>```

Decoding in java would be like,

```<code>    byte arr = amef encoded byte array value;
    AMEFDecoder decoder = new AMEFDecoder()
    AMEFObject object1 = AMEFDecoder.decode(arr,true);
</code>```

The Protocol implementation has codecs for both C++ and Java, the interesting part is it can retain object class representation in the form of name value pairs,
I required a similar protocol in my last project, when i incidentally stumbled upon this protocol, i had actually modified the base library according to my requirements. Hope this helps you.

Title: Binary serialization protocol

Body:
I have a requirement where i need to transfer information through the wire(binary over tcp) between 2 applications. One is in Java and the other in C++. I need a protocol implementation to transfer objects between these 2 applications. The Object classes are present in both the applications (are mapped accordingly). I just need some encoding scheme on one side which retains the Object representation on one side and can be decoded on the other side as a complete Object.

For eg,

C++ class

class Person
{
   int age;
   string name;
};

Java class

class Person
{
   int age;
   String name;
}

C++ encoding

Person p;
p.age = 20;
p.name = "somename";
char[] arr = SomeProtocolEncoder.encode(p);
socket.send(arr);

Java decoding

byte[] arr = socket.read();
SomeProtocolIntermediateObject object = SomeProtocolDecoder.decode(arr);
Person p = (Person)ReflectionUtil.get(object);

The protocol should provide some intermediate object which maintains the object representational state so that using reflection i can get back the object later.

Body:
You can check the amef protocol, an example of C++ encoding in amef would be like,

    //Create a new AMEF object
    AMEFObject *object = new AMEFObject();

    //Add a child string object
    object->addPacket("This is the Automated Message Exchange Format Object property!!","adasd");

    //Add a child integer object
    object->addPacket(21213);

    //Add a child boolean object
    object->addPacket(true);

    AMEFObject *object2 = new AMEFObject();
    string j = "This is the property of a nested Automated Message Exchange Format Object";
    object2->addPacket(j);
    object2->addPacket(134123);
    object2->addPacket(false);

    //Add a child character object
    object2->addPacket('d');

    //Add a child AMEF Object
    object->addPacket(object2);

    //Encode the AMEF obejct
    string str = new AMEFEncoder()->encode(object,false);

Decoding in java would be like,

    byte arr = amef encoded byte array value;
    AMEFDecoder decoder = new AMEFDecoder()
    AMEFObject object1 = AMEFDecoder.decode(arr,true);

The Protocol implementation has codecs for both C++ and Java, the interesting part is it can retain object class representation in the form of name value pairs,
I required a similar protocol in my last project, when i incidentally stumbled upon this protocol, i had actually modified the base library according to my requirements. Hope this helps you.


问:
create matrix with columns populated from vector values and row names from a different vector values
i have this data...

```<code>df <-structure(list(year = c(2017L, 2014L, 2012L, 2014L, 2014L),
               NODCCODE = c(110040218L, 121053801L, 170281801L, 170281801L, 170281801L),
               Number = c(1,  5, 2, 2, 4)), row.names = c(NA, -5L), class = c("data.table", "data.frame"))
df
   year   NODCCODE Number
1: 2017 110040218    1
2: 2014 121053801    5
3: 2012 170281801    2
4: 2014 170281801    2
5: 2014 170281801    4
</code>```

I'd like to create this for a much larger data set

```<code>df3 <- structure(list(year = c(2012L, 2014L, 2017L),
               `110040218` = c(0L, 0L, 1L),
               `121053801` = c(2L, 5L, 0L),
               `170281801` = c(2L, 3L, 0L)),
          row.names = c(NA, -3L), class = c("data.table", "data.frame"))

df3
   year 110040218 121053801 170281801
1: 2012         0         2         2
2: 2014         0         5         3
3: 2017         1         0         0
</code>```

I made the second table manually so let me explain in case I screwed it up. I have the three starting vectors, which all have many repeated values. I want the column names to be the NODCCODE numbers iterated only once, so no repeats. The first column will by consecutive years populated from the year column, but also not repeating. To populate the matrix I want to use the Number values, but if the year and NODCCODE number match then it needs to take the average and put that in that cell of the matrix.

My starting data is number of fish caught per net. So I have many species (NODCCODE code) records for each year. My actual data can be found here:  https://drive.google.com/file/d/1LTxZhD00QvFbioLPiOJMLjm5MftOmbZt/view?usp=sharing  if that is more helpful. There are many nets set and the same species are caught in many of them each year.
The final matrix if using the whole data set, should have years 2008-2018 sequentially in the first column (only one row per year). And something like 136-138 NODCODES as the rest of the column names.

So in other words its going to be a very short but very wide matrix with year as column 1. the rest of the columns will be unique NODCCODE (species). The value for each one will be an average of all the values for that NODCCODE (species) and year combinations.

I've tried many ways to do this including group by and the following code:

```<code>test <- gather(test, NODCCODE, Number, -year) %>% arrange(year, NODCCODE)
</code>```

But I keep getting results that are not even close.

I've probably over complicated this so hopefully my example data helps. Thanks in advance!

答:
I think you are looking for a long to wide format conversion. You can do that using dcast.

```<code>library(data.table)
dcast(data = df,
      formula = year ~ NODCCODE,
      value.var = "Number",
      # Function to aggregate multiple matches
      fun.aggregate = mean,
      # Fill missing values with zeros
      fill = 0)

#    year 110040218 121053801 170281801
# 1: 2012         0         0         2
# 2: 2014         0         5         3
# 3: 2017         1         0         0
</code>```

Body:
i have this data...

df <-structure(list(year = c(2017L, 2014L, 2012L, 2014L, 2014L),
               NODCCODE = c(110040218L, 121053801L, 170281801L, 170281801L, 170281801L),
               Number = c(1,  5, 2, 2, 4)), row.names = c(NA, -5L), class = c("data.table", "data.frame"))
df
   year   NODCCODE Number
1: 2017 110040218    1
2: 2014 121053801    5
3: 2012 170281801    2
4: 2014 170281801    2
5: 2014 170281801    4

I'd like to create this for a much larger data set

df3 <- structure(list(year = c(2012L, 2014L, 2017L),
               `110040218` = c(0L, 0L, 1L),
               `121053801` = c(2L, 5L, 0L),
               `170281801` = c(2L, 3L, 0L)),
          row.names = c(NA, -3L), class = c("data.table", "data.frame"))

df3
   year 110040218 121053801 170281801
1: 2012         0         2         2
2: 2014         0         5         3
3: 2017         1         0         0

I made the second table manually so let me explain in case I screwed it up. I have the three starting vectors, which all have many repeated values. I want the column names to be the NODCCODE numbers iterated only once, so no repeats. The first column will by consecutive years populated from the year column, but also not repeating. To populate the matrix I want to use the Number values, but if the year and NODCCODE number match then it needs to take the average and put that in that cell of the matrix.

My starting data is number of fish caught per net. So I have many species (NODCCODE code) records for each year. My actual data can be found here:  https://drive.google.com/file/d/1LTxZhD00QvFbioLPiOJMLjm5MftOmbZt/view?usp=sharing  if that is more helpful. There are many nets set and the same species are caught in many of them each year.
The final matrix if using the whole data set, should have years 2008-2018 sequentially in the first column (only one row per year). And something like 136-138 NODCODES as the rest of the column names.

So in other words its going to be a very short but very wide matrix with year as column 1. the rest of the columns will be unique NODCCODE (species). The value for each one will be an average of all the values for that NODCCODE (species) and year combinations.

I've tried many ways to do this including group by and the following code:

test <- gather(test, NODCCODE, Number, -year) %>% arrange(year, NODCCODE)

But I keep getting results that are not even close.

I've probably over complicated this so hopefully my example data helps. Thanks in advance!

Body:
I think you are looking for a long to wide format conversion. You can do that using dcast.

library(data.table)
dcast(data = df,
      formula = year ~ NODCCODE,
      value.var = "Number",
      # Function to aggregate multiple matches
      fun.aggregate = mean,
      # Fill missing values with zeros
      fill = 0)

#    year 110040218 121053801 170281801
# 1: 2012         0         0         2
# 2: 2014         0         5         3
# 3: 2017         1         0         0


问:
Kotlin: Mobile: setOnClickListener all buttons have to be double clicked instead of single click
I currently am learning how to code with pretty a combination of basic java tutorials, then converting the process to Kotlin.  I have made an app that does 3 things, it sends a string to a second screen to use in a sentence, and lastly it closes the app. However the buttons require two presses and I do not know why.

Below are my xml's and my kt files. Any input would be helpful.

Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gmail.launch">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".launch2">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Main Activity.kt

```<code>package com.gmail.launch

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import org.w3c.dom.Text

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun sendMessage (view: View){
        val nameb = findViewById<Button>(R.id.namebtn)
                val namet = findViewById<EditText>(R.id.nametext)

        nameb.setOnClickListener {
            val intent = Intent(this, launch2::class.java).apply {
                putExtra("com.gmail.launch.name",namet.text.toString())

            }
            startActivity(intent)
        }
    }

    fun openGoogle (view: View) {
        val gglB = findViewById<Button>(R.id.gglbtn)
        gglB.setOnClickListener {
            val googleURL  =   Intent(android.content.Intent.ACTION_VIEW)
            googleURL.data = Uri.parse("https://www.google.com/")
            startActivity(googleURL)
        }
    }

    fun closeButton (view: View) {
        val closeB = findViewById<Button>(R.id.CloseB)
        closeB.setOnClickListener {
            finishAffinity()

        }
    }
}
</code>```

MainActivity.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/gglbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:onClick="openGoogle"
        android:text="Open Google"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/namebtn" />

    <Button
        android:id="@+id/namebtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sendMessage"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/nametext" />

    <EditText
        android:id="@+id/nametext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/namebtn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/CloseB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="157dp"
        android:layout_marginLeft="157dp"
        android:layout_marginTop="11dp"
        android:layout_marginEnd="156dp"
        android:layout_marginRight="156dp"
        android:onClick="closeButton"
        android:text="Close App"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/gglbtn" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Launch2.kt

```<code>package com.gmail.launch

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import org.w3c.dom.Text

class launch2 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch2)
        val nameE = intent.getStringExtra("com.gmail.launch.name")
        val txtV = findViewById<TextView>(R.id.txtV)
        txtV.text = nameE.plus(" is a giant nerd!")

    }
}
</code>```

Launch2.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".launch2">

    <TextView
        android:id="@+id/txtV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

答:
Mike M. Got it right above but it looks like his answer is not markable as an answer.

You're mixing two different ways to set OnClickListeners. Either use the android:onClick attribute in the layout XML, or use setOnClickListener() in the code, in onCreate(), after setContentView(). Don't try to do both. -Mike M.

Body:
I currently am learning how to code with pretty a combination of basic java tutorials, then converting the process to Kotlin.  I have made an app that does 3 things, it sends a string to a second screen to use in a sentence, and lastly it closes the app. However the buttons require two presses and I do not know why.

Below are my xml's and my kt files. Any input would be helpful.

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gmail.launch">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".launch2">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Main Activity.kt

package com.gmail.launch

import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import kotlinx.android.synthetic.main.activity_main.*
import org.w3c.dom.Text

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    fun sendMessage (view: View){
        val nameb = findViewById<Button>(R.id.namebtn)
                val namet = findViewById<EditText>(R.id.nametext)

        nameb.setOnClickListener {
            val intent = Intent(this, launch2::class.java).apply {
                putExtra("com.gmail.launch.name",namet.text.toString())

            }
            startActivity(intent)
        }
    }

    fun openGoogle (view: View) {
        val gglB = findViewById<Button>(R.id.gglbtn)
        gglB.setOnClickListener {
            val googleURL  =   Intent(android.content.Intent.ACTION_VIEW)
            googleURL.data = Uri.parse("https://www.google.com/")
            startActivity(googleURL)
        }
    }

    fun closeButton (view: View) {
        val closeB = findViewById<Button>(R.id.CloseB)
        closeB.setOnClickListener {
            finishAffinity()

        }
    }
}

MainActivity.xml file

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/gglbtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:onClick="openGoogle"
        android:text="Open Google"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/namebtn" />

    <Button
        android:id="@+id/namebtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="sendMessage"
        android:text="Name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/nametext" />

    <EditText
        android:id="@+id/nametext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="120dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintBottom_toTopOf="@+id/namebtn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/CloseB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="157dp"
        android:layout_marginLeft="157dp"
        android:layout_marginTop="11dp"
        android:layout_marginEnd="156dp"
        android:layout_marginRight="156dp"
        android:onClick="closeButton"
        android:text="Close App"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/gglbtn" />

</androidx.constraintlayout.widget.ConstraintLayout>

Launch2.kt

package com.gmail.launch

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import org.w3c.dom.Text

class launch2 : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_launch2)
        val nameE = intent.getStringExtra("com.gmail.launch.name")
        val txtV = findViewById<TextView>(R.id.txtV)
        txtV.text = nameE.plus(" is a giant nerd!")

    }
}

Launch2.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".launch2">

    <TextView
        android:id="@+id/txtV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        android:textSize="20sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>


问:
tf.keras.metrics.MeanIoU with sigmoid layer
I have a network for semantic segmentation and the last layer of my model applies a sigmoid activation, so all predictions are scaled between 0-1. There is this validation metric tf.keras.metrics.MeanIoU(num_classes), which compares classified predictions (0 or 1) with validation (0 or 1). So if i make a prediction and apply this metric, will it automatically map the continuous predictions to binary with threshold = 0.5? Are there any possibilities to manually define the threshold? </p>

答:
Try this(remember to replace the space with tab):</p>

```<code>def mean_iou(y_true, y_pred):
    th = 0.5
    y_pred_ = tf.to_int32(y_pred > th)
    score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)
    K.get_session().run(tf.local_variables_initializer())
    with tf.control_dependencies([up_opt]):
        score = tf.identity(score)
    return score
</code>```

Body:
Try this(remember to replace the space with tab):

def mean_iou(y_true, y_pred):
    th = 0.5
    y_pred_ = tf.to_int32(y_pred > th)
    score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)
    K.get_session().run(tf.local_variables_initializer())
    with tf.control_dependencies([up_opt]):
        score = tf.identity(score)
    return score


问:
Is there a way to accmplish the following loop without all the repetitive if statements?
The following is to fill out the values for a histogram:

```<code>for(index=0; index<256; index++) {
         while(1) {
             if(store[index] < bin_edge[1]) {
                 bins[0]++;
                 break;
             }
             if(store[index] < bin_edge[2]) {
                 bins[1]++;
                 break;
             }
             if(store[index] < bin_edge[3]) {
                 bins[2]++;
                 break;
             }
             if(store[index] < bin_edge[4]) {
                 bins[3]++;
                 break;
             }
             if(store[index] < bin_edge[5]) {
                 bins[4]++;
                 break;
             }
             if(store[index] < bin_edge[6]) {
                bins[5]++;
                break;
             }
             if(store[index] < bin_edge[7]) {
                bins[6]++;
                break;
             }
             if(store[index] < bin_edge[8]) {
                bins[7]++;
                break;
             }
             if(store[index] < bin_edge[9]) {
                bins[8]++;
                break;
             }
             if(store[index] < bin_edge[10]) {
                bins[9]++;
                break;
             }
             if(store[index] < bin_edge[11]) {
                bins[10]++;
                break;
             }
             if(store[index] < bin_edge[12]) {
                bins[11]++;
                break;
             }
             if(store[index] < bin_edge[13]) {
                bins[12]++;
                break;
             }
             if(store[index] < bin_edge[14]) {
                bins[13]++;
                break;
             }
             if(store[index] < bin_edge[15]) {
                bins[14]++;
                break;
             }
                bins[15]++;                       /* Default case */
                break;
         }
     }
</code>```

store is an integer array I am graphing, bins array is the graph values, bin_edge array holds the right hand edge of each bin. I admit to being a novice at the "c" language". This works but is clumsy and tedious to code.

答:
I guess this is a competition for the most efficient replacement loop :-)

Here's yet another one (assuming int, but set type of curval to whatever the type of store is) ...

```<code>for (index = 0; index < 256; index++) {
    int curval = store[index];
    int edgeidx;

    for (edgeidx = 1;  edgeidx <= 15;  ++edgeidx) {
        if (curval < bin_edge[edgeidx])
            break;
    }

    bins[edgeidx - 1]++;
}
</code>```

Body:
The following is to fill out the values for a histogram:

for(index=0; index<256; index++) {
         while(1) {
             if(store[index] < bin_edge[1]) {
                 bins[0]++;
                 break;
             }
             if(store[index] < bin_edge[2]) {
                 bins[1]++;
                 break;
             }
             if(store[index] < bin_edge[3]) {
                 bins[2]++;
                 break;
             }
             if(store[index] < bin_edge[4]) {
                 bins[3]++;
                 break;
             }
             if(store[index] < bin_edge[5]) {
                 bins[4]++;
                 break;
             }
             if(store[index] < bin_edge[6]) {
                bins[5]++;
                break;
             }
             if(store[index] < bin_edge[7]) {
                bins[6]++;
                break;
             }
             if(store[index] < bin_edge[8]) {
                bins[7]++;
                break;
             }
             if(store[index] < bin_edge[9]) {
                bins[8]++;
                break;
             }
             if(store[index] < bin_edge[10]) {
                bins[9]++;
                break;
             }
             if(store[index] < bin_edge[11]) {
                bins[10]++;
                break;
             }
             if(store[index] < bin_edge[12]) {
                bins[11]++;
                break;
             }
             if(store[index] < bin_edge[13]) {
                bins[12]++;
                break;
             }
             if(store[index] < bin_edge[14]) {
                bins[13]++;
                break;
             }
             if(store[index] < bin_edge[15]) {
                bins[14]++;
                break;
             }
                bins[15]++;                       /* Default case */
                break;
         }
     }

store is an integer array I am graphing, bins array is the graph values, bin_edge array holds the right hand edge of each bin. I admit to being a novice at the "c" language". This works but is clumsy and tedious to code.

Body:
I guess this is a competition for the most efficient replacement loop :-)

Here's yet another one (assuming int, but set type of curval to whatever the type of store is) ...

for (index = 0; index < 256; index++) {
    int curval = store[index];
    int edgeidx;

    for (edgeidx = 1;  edgeidx <= 15;  ++edgeidx) {
        if (curval < bin_edge[edgeidx])
            break;
    }

    bins[edgeidx - 1]++;
}


问:
Soap App Delegate error
please tell me what this error means:

/Users/macbook2/Desktop/20/Soap
  2/MainWindow.xib:3:0 The
  'viewController' outlet of 'Soap App
  Delegate' is connected to 'Root View
  Controllers' but 'RootViewControllers'
  is not a kind of 'SoapViewController'
  as specified by the outlet type.

答: It means that you have an instance of UIViewController(SoapViewController) created in App Delegate but you have not changed the class Type of RootViewController in your mainwindow.xib file. Change the classType and then run the code.</p>

Title: Soap App Delegate error


问:
The query has timed out.; nested exception is com.microsoft.sqlserver.jdbc.SQLServerException: The query has timed out
Getting this error when trying to execute the procedure from spring's transaction.

SQL state [HY008]; error code [0]; The query has timed out.; nested
  exception is com.microsoft.sqlserver.jdbc.SQLServerException: The
  query has timed out.

This occurs at 10 min when the dataset is large.
Using the Azure SQL server for this.

Tried:

@transaction(timeout=18000)

Azure DB is not showing the connection properties to edit the remote query time out time option.

答:
Congratulation you solved the timeout error now:

"I fixed my problem by JDBC template timeout option for now. Will try to reduce the time query is taking"

I help you post it is as answer, this can be beneficial to other community members.


问:
Troubleshooting conflicting elements on a website
I am working on a website and there seems to be conflicting elements.

I started with a template that contains a lot of "borrowed" CSS and JS elements from different places, and now I am trying to add a Slick slideshow, and there are conflicts in either the JS or the CSS that prevent me from editing the Slick slider (parts of the slick-slider code were already present in the "Organic Farm" template).

Right now I have js/core.min.js, js/script.js and js/slick.js being loaded into the page, and then at the bottom of the index page:

```<code><script type="text/javascript">
    $(document).ready(function(){
      $('.swiper-slide').slick({
          dots: true,
          infinite: true,
          speed: 300,
          slidesToShow: 1,
          centerMode: true,
          variableWidth: true,
      });
    });
</script>
</code>```

The HTML portion is:

```<code>  <section class="section">
    <div class="swiper-container swiper-slider swiper-custom" data-height="35.10416666666667%" data-min-height="375px" data-index-bullet="false" data-slide-effect="swipe" data-autoplay="5000">
      <div class="swiper-wrapper swiper-wrapper-custom">
        <div class="swiper-slide" data-slide-bg="images/ergfer1.jpg">
          <div class="swiper-slide-caption">
            <div class="container text-center">
              <div class="row justify-content-center">
                <div class="col-md-9 col-lg-8 top">
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="swiper-slide" data-slide-bg="images/gdrger.jpg">
          <div class="swiper-slide-caption">
            <div class="container text-center">
              <div class="row justify-content-center">
                <div class="col-md-9 col-lg-8 top">
                </div>
              </div>
            </div>
          </div>
        </div>
</code>```

Is there a way to find out why my custom script is not active? The arrows are also not showing up. For anything HTML and CSS I use the Inspector of Firefox, but here I'm really stumped.

答:
Two things to consider:

1) When using slick.js, it is customary to add it to the element which is the parent of a set of elements which are then converted into slides. For example:

```<code><div id="slide-wrapper">
    <div class="my-slide">...</div>
    <div class="my-slide">...</div>
    <div class="my-slide">...</div>
</div>

$('.slide-wrapper').slick({
    ...
});
</code>```

In your case, that would mean adding Slick to swiper-wrapper:

```<code>$('.swiper-wrapper').slick({
    ...
});
</code>```

2) More likely the problem is that you have a conflict with the setup of a different slide show library altogether, Swiper.js (https://swiperjs.com/api/), which uses classes like swiper-container, swiper-wrapper and swiper-slide. To implement that slideshow, you would have to include that library on your page and initialize the slideshow with something like:

```<code>var mySwiper = new Swiper('.swiper-container', {
    speed: 400,
    spaceBetween: 100
});
</code>```

Body:
I am working on a website and there seems to be conflicting elements.

I started with a template that contains a lot of "borrowed" CSS and JS elements from different places, and now I am trying to add a Slick slideshow, and there are conflicts in either the JS or the CSS that prevent me from editing the Slick slider (parts of the slick-slider code were already present in the "Organic Farm" template).

Right now I have js/core.min.js, js/script.js and js/slick.js being loaded into the page, and then at the bottom of the index page:

The HTML portion is:

Is there a way to find out why my custom script is not active? The arrows are also not showing up. For anything HTML and CSS I use the Inspector of Firefox, but here I'm really stumped.

Body:
Two things to consider:

1) When using slick.js, it is customary to add it to the element which is the parent of a set of elements which are then converted into slides. For example:

<div id="slide-wrapper">
    <div class="my-slide">...</div>
    <div class="my-slide">...</div>
    <div class="my-slide">...</div>
</div>

$('.slide-wrapper').slick({
    ...
});

In your case, that would mean adding Slick to swiper-wrapper:

$('.swiper-wrapper').slick({
    ...
});

2) More likely the problem is that you have a conflict with the setup of a different slide show library altogether, Swiper.js (https://swiperjs.com/api/), which uses classes like swiper-container, swiper-wrapper and swiper-slide. To implement that slideshow, you would have to include that library on your page and initialize the slideshow with something like:

var mySwiper = new Swiper('.swiper-container', {
    speed: 400,
    spaceBetween: 100
});


问:
Custom syntax highlight color settings are reset/overridden on next launch
I have no extensions at the moment, yet VS2019 keeps forcing the following purple/golden colors on syntax every launch:

If I go to Options > Environment > Fonts and Colors and click on "Use Defaults" I get the correct (blue) theme again. However, if I restart VS, it's broken again.

I run VS2017 on the same machine and that works correctly.

Am I missing a setting somewhere or is this a bug in VS2019? I've already reinstalled it a few times and cleared out all settings I could find in registry and disk, but the problem remains.

As a side note, Import and Export Settings... isn't working correctly either. If I try Reset all settings I can only click one time Next and then after the following Next the window disappears (same with Import selected environment settings).

答:
Tools -> Options -> Text Editor -> C# -> Advanced (SCROLL DOWN)

Editor Color Scheme (Drop Down Menu) choose Visual Studio 2019.

Tools

Options

Text Editor

C# -> Advanced (Scroll Down)


问:
Show masked area on top of camera widget
I'm trying to implement a credit card reader (using some API). For the user to take a picture of the card, I'm presenting the camera preview widget full screen. I would like to mask out an area so the user centers the card there.

He're an illustration of what I have in mind

I was wondering how this masking could be accomplished in flutter? Currently I'm just drawing a BoxDecoration, but that's missing the semi transparent, greyed out area.

```<code>Container(
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.width * 0.8 / 1.55,
decoration: new BoxDecoration(
    border: Border.all(
        color: Colors.white,
        width: 2.0,
        style: BorderStyle.solid),
    shape: BoxShape.rectangle,
    borderRadius: BorderRadius.all(Radius.circular(4.0))),
)
</code>```

答:
Probably, you can try with columns, rows, and containers :).

```<code>Widget getMaskCard(BuildContext context) {

    Color _background = Colors.grey.withOpacity(0.2);

    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: 1,
                color: _background,
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width * 0.8,
              child: Column(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      color: _background,
                    ),
                  ),
                  Container(
                    height: 180,
                    width: MediaQuery.of(context).size.width * 0.8,
                    color: Colors.transparent,
                  ),
                  Expanded(
                    child: Container(
                      color: _background,
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: 1,
                color: _background,
              ),
            ),
          ],
        )
      ],
    );
  }
</code>```

Example

Body:
I'm trying to implement a credit card reader (using some API). For the user to take a picture of the card, I'm presenting the camera preview widget full screen. I would like to mask out an area so the user centers the card there.

He're an illustration of what I have in mind

I was wondering how this masking could be accomplished in flutter? Currently I'm just drawing a BoxDecoration, but that's missing the semi transparent, greyed out area.

Container(
width: MediaQuery.of(context).size.width * 0.8,
height: MediaQuery.of(context).size.width * 0.8 / 1.55,
decoration: new BoxDecoration(
    border: Border.all(
        color: Colors.white,
        width: 2.0,
        style: BorderStyle.solid),
    shape: BoxShape.rectangle,
    borderRadius: BorderRadius.all(Radius.circular(4.0))),
)

Body:
Probably, you can try with columns, rows, and containers :).

Widget getMaskCard(BuildContext context) {

    Color _background = Colors.grey.withOpacity(0.2);

    return Column(
      children: <Widget>[
        Row(
          children: <Widget>[
            Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: 1,
                color: _background,
              ),
            ),
            Container(
              height: MediaQuery.of(context).size.height,
              width: MediaQuery.of(context).size.width * 0.8,
              child: Column(
                children: <Widget>[
                  Expanded(
                    child: Container(
                      color: _background,
                    ),
                  ),
                  Container(
                    height: 180,
                    width: MediaQuery.of(context).size.width * 0.8,
                    color: Colors.transparent,
                  ),
                  Expanded(
                    child: Container(
                      color: _background,
                    ),
                  ),
                ],
              ),
            ),
            Expanded(
              child: Container(
                height: MediaQuery.of(context).size.height,
                width: 1,
                color: _background,
              ),
            ),
          ],
        )
      ],
    );
  }

Example


问:
Can nested LookUp be done?
Hi again dear stackoverflowers!

I have one column in Sharepoint for an ID number (say that the number is 29) and another column that for that ID holds different subIDs (29.1, 29.2, 29.3, etc.).

What I need is that my PowerApp looks up into the Sharepoint list and takes the maximum subID number associated with the ID given, and automatically sums 0.1, because I do not want people to introduce two equal subIDs.

I'll give you the formula I tried (but the problem is that StartsWith is for text and Max is for numbers), so if you have any ideas about how can it be solved or you have any function that works with both text and numbers I would really appreciate it:

LookUp(my_list.'Prueba', StartsWith('Prueba' , DataCardValue9_2.Text), Max('Prueba')+0.1)

Another thing I tried was to nest LookUp functions, but that did not work either, do you know if that can be done?

LookUp(my_list, Prueba = DataCardValue9_2.Text + 0.3 , Max(Prueba) + 0.1) & LookUp(my_list, Prueba = DataCardValue9_2.Text + 0.2 , Max(Prueba) + 0.1) & LookUp(my_list, Prueba = DataCardValue9_2.Text + 0.1 , Max(Prueba) + 0.1)

Thank you very much for your time and help.

答:
You must convert your column to a number datatype. Value() function for number.

Please do check this link: https://learn.microsoft.com/en-us/powerapps/maker/canvas-apps/functions/function-value

Title: Can nested LookUp be done?