问:
Pandas Check Excel import for isnumeric() data in Dataframe
I am importing data into Pandas from Excel and I need to verify that the data is numeric based on the Columns.

```<code>        month      value        dp        wd  ...      mg   fee      pr      comment

0  2013-07-31  208372.33   4206.84   4692.22  ...       0     0       0    some comment
1  2013-08-31  210669.77      0.00   1270.28  ...       0     0       0
</code>```

There are about 20 columns and I only need to exclude the "month" and "comment" columns.

Is there something like:  df.iloc[:, 2: 18].isnumeric() or will this require a loop?

I would like to get a True / False response.

thank you.

答:
One way is select_dtypes and compare:

```<code>np.array_equal(df.select_dtypes(include='number').columns, df.columns[1:-1])
</code>```

Body:
I am importing data into Pandas from Excel and I need to verify that the data is numeric based on the Columns.

        month      value        dp        wd  ...      mg   fee      pr      comment

0  2013-07-31  208372.33   4206.84   4692.22  ...       0     0       0    some comment
1  2013-08-31  210669.77      0.00   1270.28  ...       0     0       0

There are about 20 columns and I only need to exclude the "month" and "comment" columns.

Is there something like:  df.iloc[:, 2: 18].isnumeric() or will this require a loop?

I would like to get a True / False response.

thank you.

Body:
One way is select_dtypes and compare:

np.array_equal(df.select_dtypes(include='number').columns, df.columns[1:-1])


来源: stackexchange

问:
Can't understand why my args doesn't work in discord.js
Well, so I was trying to make code that won't send embed if args isn't defined

```<code>var member = message.mentions.members.first();

If(args[0] == member) {
//Here's my embed
} else {
channel.message.send('you need to mention someone to do it');
}
</code>```

I was trying to find answers why it won't work but couldn't found anything about. Also I was trying to replace if(args[0] == member) with if(args[1] == member) or if(args[0] == message.mention.members.first()) but it didn't help. I'm new in JavaScript and don't know a lot about it so please help me.

答:
If I think I know what your doing, This will work.

```<code>var member = message.mentions.users.first(); //Gets the pinged user.
if(!member) return message.reply("There is no user defined in this message.")//checks if a member is pinged.
//rest of code
</code>```

member doesn't need to be set as a argument, This will work the same way.
I am using discord.js version 11.5.1, Hopefully this will still work for you.

ContentLicense: CC BY-SA 4.0

Body:
Well, so I was trying to make code that won't send embed if args isn't defined

var member = message.mentions.members.first();

If(args[0] == member) {
//Here's my embed
} else {
channel.message.send('you need to mention someone to do it');
}

I was trying to find answers why it won't work but couldn't found anything about. Also I was trying to replace if(args[0] == member) with if(args[1] == member) or if(args[0] == message.mention.members.first()) but it didn't help. I'm new in JavaScript and don't know a lot about it so please help me.

Body:
If I think I know what your doing, This will work.

var member = message.mentions.users.first(); //Gets the pinged user.
if(!member) return message.reply("There is no user defined in this message.")//checks if a member is pinged.
//rest of code

member doesn't need to be set as a argument, This will work the same way.
I am using discord.js version 11.5.1, Hopefully this will still work for you.


问:
Python invalid syntax questions
Why does the code below return the error "SyntaxError: invalid syntax"

If(amount_paid==12):

I know it's basic but just starting out learning Python in Visual Studio Code

Thanks for any help,

Phil

答: Most things in Python are case-sensitive. Here, that's the if construct -- If amount_paid == 12: is not well formed, but if amount_paid == 12: is.

Title: Python invalid syntax questions


问:
javax.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator
I followed this blog post and tried to implement a custom validator to validate a composite primary key constraint and it fails with:

```<code>javax.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator: com.directory.domain.model.validators.StorePoolValidator.
    at com.directory.domain.repositories.StorePoolRepositoryTest.shouldReturnPoolByStore(StorePoolRepositoryTest.java:30)
Caused by: java.lang.NoSuchMethodException: com.directory.domain.model.validators.StorePoolValidator.<init>()
    at com.directory.domain.repositories.StorePoolRepositoryTest.shouldReturnPoolByStore(StorePoolRepositoryTest.java:30)
</code>```

Here is the code of the annotation interface of the validator:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)
@Target({FIELD})
@Constraint(validatedBy = StorePoolValidator.class)
public @interface UniqueStorePoolConstraint {
    String message() default "Store pool validation failed";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
```

<p>Here is the validator class:</p>

<pre class="lang-java prettyprint-override"><code>import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

public class StorePoolValidator implements ConstraintValidator<UniqueStorePoolConstraint, StorePoolId> {

    private StorePoolRepository storePoolRepository;

    public StorePoolValidator(StorePoolRepository storePoolRepository) {
        this.storePoolRepository = storePoolRepository;
    }

    @Override
    public void initialize(UniqueStorePoolConstraint constraintAnnotation) {

    }

    @Override
    public boolean isValid(StorePoolId id, ConstraintValidatorContext context) {
        final List<StorePool> storePools = storePoolRepository.findAllByStoreNumber(id.getThirdNumber());

        return storePools.isEmpty();
    }
}
</code>```

Here is the entity class:

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@Table(name = "STORE_POOLS")
public class StorePool implements Serializable {

    public StorePool() {
    }

    @EmbeddedId
    @UniqueStorePoolConstraint
    private StorePoolId id;
}
```

<p>and its primary key class:</p>

<pre class="lang-java prettyprint-override"><code>import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Getter
@Setter
@Builder
@ToString
@Embeddable
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class StorePoolId implements Serializable {

    @Column(name = "pool", nullable = false)
    @NotNull
    private Integer pool;

    @Column(name = "third_number", nullable = false)
    @NotNull
    private Integer thirdNumber;
}
</code>```

I tried to run the following test:

@RunWith(SpringRunner.class)
@DataJpaTest
public class StorePoolRepositoryTest {

    @Autowired
    private StorePoolRepository storePoolRepository;

    @Autowired
    private TestEntityManager entityManager;

    @Test
    public void shouldReturnPoolByStore() {
        final StorePool storePool = StorePoolBuilder.buildStorePool(1, 1);
        entityManager.persist(storePool);
        entityManager.flush();

        final List<StorePool> storePools = storePoolRepository.findAllByStoreNumber(1);

        assertThat(storePools).containsExactly(storePool);
    }
}
```

What am I missing? Thank you.

答:
The Spring framework automatically detects all classes which implement the  ConstraintValidator interface. The framework instantiates them and wires all dependencies like the class was a regular Spring bean. So you don't need to put @Service and @Autowired annotations.
More details here.

Body:
I followed this blog post and tried to implement a custom validator to validate a composite primary key constraint and it fails with:

javax.validation.ValidationException: HV000064: Unable to instantiate ConstraintValidator: com.directory.domain.model.validators.StorePoolValidator.
    at com.directory.domain.repositories.StorePoolRepositoryTest.shouldReturnPoolByStore(StorePoolRepositoryTest.java:30)
Caused by: java.lang.NoSuchMethodException: com.directory.domain.model.validators.StorePoolValidator.<init>()
    at com.directory.domain.repositories.StorePoolRepositoryTest.shouldReturnPoolByStore(StorePoolRepositoryTest.java:30)

Here is the code of the annotation interface of the validator:

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Retention(RUNTIME)
@Target({FIELD})
@Constraint(validatedBy = StorePoolValidator.class)
public @interface UniqueStorePoolConstraint {
    String message() default "Store pool validation failed";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Here is the validator class:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

public class StorePoolValidator implements ConstraintValidator<UniqueStorePoolConstraint, StorePoolId> {

    private StorePoolRepository storePoolRepository;

    public StorePoolValidator(StorePoolRepository storePoolRepository) {
        this.storePoolRepository = storePoolRepository;
    }

    @Override
    public void initialize(UniqueStorePoolConstraint constraintAnnotation) {

    }

    @Override
    public boolean isValid(StorePoolId id, ConstraintValidatorContext context) {
        final List<StorePool> storePools = storePoolRepository.findAllByStoreNumber(id.getThirdNumber());

        return storePools.isEmpty();
    }
}

Here is the entity class:

@Entity
@Getter
@Setter
@Builder
@AllArgsConstructor
@Table(name = "STORE_POOLS")
public class StorePool implements Serializable {

    public StorePool() {
    }

    @EmbeddedId
    @UniqueStorePoolConstraint
    private StorePoolId id;
}

and its primary key class:

import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

@Getter
@Setter
@Builder
@ToString
@Embeddable
@EqualsAndHashCode
@AllArgsConstructor
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class StorePoolId implements Serializable {

    @Column(name = "pool", nullable = false)
    @NotNull
    private Integer pool;

    @Column(name = "third_number", nullable = false)
    @NotNull
    private Integer thirdNumber;
}

I tried to run the following test:

@RunWith(SpringRunner.class)
@DataJpaTest
public class StorePoolRepositoryTest {

    @Autowired
    private StorePoolRepository storePoolRepository;

    @Autowired
    private TestEntityManager entityManager;

    @Test
    public void shouldReturnPoolByStore() {
        final StorePool storePool = StorePoolBuilder.buildStorePool(1, 1);
        entityManager.persist(storePool);
        entityManager.flush();

        final List<StorePool> storePools = storePoolRepository.findAllByStoreNumber(1);

        assertThat(storePools).containsExactly(storePool);
    }
}

What am I missing? Thank you.


问:
How to get the flask-python app to redirect to https with heroku without too many redirects error?
My website here: https://climatebin.herokuapp.com/ is showing this error ERR_TOO_MANY_REDIRECTS I tried deleting cookies and going to Firefox, but none worked. I tried changing the https to http in the URL but it keeps redirecting to https. I don't have a SSL certificate and I'm using free dynos on Heroku. How do I get this to work?

This is my HTTP to HTTPS redirection code.

```<code>@app.before_request
def before_request():

    # this checks if the user requests http and if they did it changes it to https
    if request.headers.get('X-Forwarded-Proto') == 'http':
        url = request.url.replace('http://', 'https://', 1)
        print("redirected to https?")
        code = 301
        return redirect(url, code=code)
</code>```

答: My website is dynamic and relied on free Heroku dynos and SSL to run it. Heroku only runs free SSL for static websites.</p>

Body:
My website here: https://climatebin.herokuapp.com/ is showing this error ERR_TOO_MANY_REDIRECTS I tried deleting cookies and going to Firefox, but none worked. I tried changing the https to http in the URL but it keeps redirecting to https. I don't have a SSL certificate and I'm using free dynos on Heroku. How do I get this to work?

This is my HTTP to HTTPS redirection code.

@app.before_request
def before_request():

    # this checks if the user requests http and if they did it changes it to https
    if request.headers.get('X-Forwarded-Proto') == 'http':
        url = request.url.replace('http://', 'https://', 1)
        print("redirected to https?")
        code = 301
        return redirect(url, code=code)


问:
filter array and get max values of nested array of each set of objects in javascrip
I would like to filter from the nested array whose condition is count_buyer greater than 0 and then get the max purchase_amount from buyers all this while maintaining the nested array hierarchy.

I have data in an array like this

```<code>var data = [
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
      {
        'product':'ropa varon',
        'count_buyer':0,
        'buyers':[]
      }
    ];
</code>```

first I want to filter the objects that they have in their buyers array.

```<code>[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
</code>```

then filter the maximum number of buyers whose condition is the maximum purchase_amount

```<code>[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
</code>```

this is my code

var data = [
  {
    'product':'laptop',
    'count_buyer':3,
    'buyers':[
          { 'name': 'Vins', 'purchase_amount': 27 },
          { 'name': 'Jan', 'purchase_amount': 38 },
          { 'name': 'Alex', 'purchase_amount': 80 },
    ]
  },
  {
    'product':'televisor',
    'count_buyer':2,
    'buyers':[
          { 'name': 'Carl', 'purchase_amount': 25 },
          { 'name': 'Digi', 'purchase_amount': 40 }
    ]
  },
  {
    'product':'ropa varon',
    'count_buyer':0,
    'buyers':[]
  }
];
var filter0 = data.filter(count=> count.count_buyer > 0 )
var max = filter0.filter(buye => buye.buyers.reduce(function (prev, current) {
   return (prev.purchase_amount > current.purchase_amount) ? prev : current
}));
console.log(max)```
</div>
</div>
</p>

<p>but the result is like this</p>

```[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
```

<p>How could I get to this result?</p>

```[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]
```

答:
I wrote the library rubico to simplify the method we're about to use to do this in one pass: transducers. If you don't know what they are, I wrote a crash course here. First I will show you how to do it with two passes, i.e.

[...products] => [...products_with_buyers]

[...products_with_buyers] => [...products_with_max_buyer].

const { transform, pipe, assign, map, filter, reduce, get, gt } = require('rubico')

const getMaxBuyer = (y, xi) => y.purchase_amount > xi.purchase_amount ? y : xi

const getProductsWithMaxBuyer = pipe([
  filter(gt(get('buyers.length'), 0)), // [...products] => [...products_with_buyers]
  map(assign({
    buyers: pipe([
      get('buyers'), // product => product.buyers
      reduce(getMaxBuyer), // buyers => [max_buyer]
    ]), // assign [max_buyer] the result to the 'buyers' property on the product
  })) // [...products_with_buyers] => [...products_with_max_buyer]
])

getProductsWithMaxBuyer(data) /* creates an intermediate array `product_with_buyers`
[
  {
    product: 'laptop',
    count_buyer: 3,
    buyers: { name: 'Alex', purchase_amount: 80 }
  },
  {
    product: 'televisor',
    count_buyer: 2,
    buyers: { name: 'Digi', purchase_amount: 40 }
  }
]
*/
```

<p>This is how you do it in one pass.</p>

<p><code>[...products] => [...products_with_max_buyer]</code></p>

<pre class="lang-js prettyprint-override"><code>transform(
  getProductsWithMaxBuyer,
  [],
)(data) /* => [ does not create any intermediate arrays, everything is one pass
  {
    product: 'laptop',
    count_buyer: 3,
    buyers: { name: 'Alex', purchase_amount: 80 }
  },
  {
    product: 'televisor',
    count_buyer: 2,
    buyers: { name: 'Digi', purchase_amount: 40 }
  }
] */
</code>```

The difference here is the context in which rubico's functions are used. They are "smart" enough to know if they should behave as transducers. If you'd like to read more, check out the intro and the docs

Body:
I would like to filter from the nested array whose condition is count_buyer greater than 0 and then get the max purchase_amount from buyers all this while maintaining the nested array hierarchy.

I have data in an array like this

var data = [
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
      {
        'product':'ropa varon',
        'count_buyer':0,
        'buyers':[]
      }
    ];

first I want to filter the objects that they have in their buyers array.

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]

then filter the maximum number of buyers whose condition is the maximum purchase_amount

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]

this is my code

var data = [
  {
    'product':'laptop',
    'count_buyer':3,
    'buyers':[
          { 'name': 'Vins', 'purchase_amount': 27 },
          { 'name': 'Jan', 'purchase_amount': 38 },
          { 'name': 'Alex', 'purchase_amount': 80 },
    ]
  },
  {
    'product':'televisor',
    'count_buyer':2,
    'buyers':[
          { 'name': 'Carl', 'purchase_amount': 25 },
          { 'name': 'Digi', 'purchase_amount': 40 }
    ]
  },
  {
    'product':'ropa varon',
    'count_buyer':0,
    'buyers':[]
  }
];
var filter0 = data.filter(count=> count.count_buyer > 0 )
var max = filter0.filter(buye => buye.buyers.reduce(function (prev, current) {
   return (prev.purchase_amount > current.purchase_amount) ? prev : current
}));
console.log(max)

but the result is like this

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Vins', 'purchase_amount': 27 },
              { 'name': 'Jan', 'purchase_amount': 38 },
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Carl', 'purchase_amount': 25 },
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]

How could I get to this result?

[
      {
        'product':'laptop',
        'count_buyer':3,
        'buyers':[
              { 'name': 'Alex', 'purchase_amount': 80 },
        ]
      },
      {
        'product':'televisor',
        'count_buyer':2,
        'buyers':[
              { 'name': 'Digi', 'purchase_amount': 40 }
        ]
      },
]

Body:
I wrote the library rubico to simplify the method we're about to use to do this in one pass: transducers. If you don't know what they are, I wrote a crash course here. First I will show you how to do it with two passes, i.e.

[...products] => [...products_with_buyers]

[...products_with_buyers] => [...products_with_max_buyer].

const { transform, pipe, assign, map, filter, reduce, get, gt } = require('rubico')

const getMaxBuyer = (y, xi) => y.purchase_amount > xi.purchase_amount ? y : xi

const getProductsWithMaxBuyer = pipe([
  filter(gt(get('buyers.length'), 0)), // [...products] => [...products_with_buyers]
  map(assign({
    buyers: pipe([
      get('buyers'), // product => product.buyers
      reduce(getMaxBuyer), // buyers => [max_buyer]
    ]), // assign [max_buyer] the result to the 'buyers' property on the product
  })) // [...products_with_buyers] => [...products_with_max_buyer]
])

getProductsWithMaxBuyer(data) /* creates an intermediate array `product_with_buyers`
[
  {
    product: 'laptop',
    count_buyer: 3,
    buyers: { name: 'Alex', purchase_amount: 80 }
  },
  {
    product: 'televisor',
    count_buyer: 2,
    buyers: { name: 'Digi', purchase_amount: 40 }
  }
]
*/

This is how you do it in one pass.

[...products] => [...products_with_max_buyer]

transform(
  getProductsWithMaxBuyer,
  [],
)(data) /* => [ does not create any intermediate arrays, everything is one pass
  {
    product: 'laptop',
    count_buyer: 3,
    buyers: { name: 'Alex', purchase_amount: 80 }
  },
  {
    product: 'televisor',
    count_buyer: 2,
    buyers: { name: 'Digi', purchase_amount: 40 }
  }
] */

The difference here is the context in which rubico's functions are used. They are "smart" enough to know if they should behave as transducers. If you'd like to read more, check out the intro and the docs


答: Try making If lowercase (make the "I" lowercase)

Title: Python invalid syntax questions

Body:
Why does the code below return the error "SyntaxError: invalid syntax"

If(amount_paid==12):

I know it's basic but just starting out learning Python in Visual Studio Code

Thanks for any help,

Phil


问:
Is it possible to have a separate module for instrumented tests in android
We have a project, that has some instrumented tests that run part of CI
Now we want to add some integration tests (of type instrumentation tests), but they should not run as part of pipeline, but on demand through a separate Jenkins job or command
I am trying to create a separate module for integration tests that depend on "app" module, but that's throwing a lot of errors like below

errors showing up in android studio while it tries to resolve the app module

I wanted to understand if its even possible?

答:
It is possible. There is probably an easier way than what I am about to suggest but you can implement a rule that conditionally ignores test and change the value of this variable in your CI job.

There are different approaches.
1)Determine which tests to run via a boolean stored in server. So mark your normal ui tests with the condition shouldUITest and the others shouldInstrumentationTest and change their value in server
2)Change variables in app.gradle with buildflavors. (Basically create 2 different variants and run whichever one you want
3)Detect the build is a CI build, and act accordingly in app.gradle

```<code>def ciBuild= System.getenv("CI") == "true"
    if (ciBuild) {
        //Do stuff
    }
</code>```

Body:
It is possible. There is probably an easier way than what I am about to suggest but you can implement a rule that conditionally ignores test and change the value of this variable in your CI job.

There are different approaches.
1)Determine which tests to run via a boolean stored in server. So mark your normal ui tests with the condition shouldUITest and the others shouldInstrumentationTest and change their value in server
2)Change variables in app.gradle with buildflavors. (Basically create 2 different variants and run whichever one you want
3)Detect the build is a CI build, and act accordingly in app.gradle

def ciBuild= System.getenv("CI") == "true"
    if (ciBuild) {
        //Do stuff
    }


问:
I am using Kaggle FIFA19 dataset . How can i find The best player per position and list them?
I am using Kaggle FIFA19 dataset. How can I find The best player per position and list them?

I am using python

```<code>df.groupby('Position').agg({'Overall': 'avg'}).sort('avg(Overall)', ascending=False).show()
</code>```

I need to list the name of players in another column

答:
Why not grouping on name and position both</p>

```<code>df.groupby('Name','Position').agg({'Overall': 'avg'}).sort('avg(Overall)', ascending=False).show()

</code>```

Body:
I am using Kaggle FIFA19 dataset. How can I find The best player per position and list them?

I am using python

df.groupby('Position').agg({'Overall': 'avg'}).sort('avg(Overall)', ascending=False).show()

I need to list the name of players in another column

Body:
Why not grouping on name and position both

df.groupby('Name','Position').agg({'Overall': 'avg'}).sort('avg(Overall)', ascending=False).show()


问:
How to fix end of statement when trying to insert multiple values in SQL?
I just started a database course that is going over SQL using Access 2016.  I am getting a End of statement error and I am unsure how to fix it.

My table code is `

```<code>Create Table Pet_Owner (
OwnerID autoincrement Null,
OwnerLastName Char(30) Not Null,
OwnerFirstName Char(30) Not Null,
OwnerPhone Int Null,
OwnerEmail VarChar(100) Not Null Unique,
Constraint Pet_Owner_PK Primary Key(OwnerID)
);
</code>```

and the insert query I have so far that I am trying to add is

```<code>Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Downs' , 'Marsha' , '555-537-8765' , 'Marsha.downs@somewhere.com')
Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'James' , 'Richard' , '555-537-7654' , 'Richard.James@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Frier' , 'Liz' , '555-537-6543' , 'Liz.Frier@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerEmail) Values (
'Trent', 'Miles', 'Miles.Trent@somewhere.com') ;
</code>```

When I use append, it is saying I am missing a semicolon at the end of the first set of values, but if i add that then it says i have characters at the end of my statement. If anyone can help me out or point me into the right direction to solve the error I would greatly appreciate it. Thank you

答:
You would need to start each statement with insert into, and separate them with ;.

```<code>Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail)
Values ('Downs' , 'Marsha' , '555-537-8765' , 'Marsha.downs@somewhere.com');

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail)
Values ('James' , 'Richard' , '555-537-7654' , 'Richard.James@somewhere.com');

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail)
Values ('Frier' , 'Liz' , '555-537-6543' , 'Liz.Frier@somewhere.com');

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerEmail)
Values ('Trent', 'Miles', 'Miles.Trent@somewhere.com');
</code>```

Body:
I just started a database course that is going over SQL using Access 2016.  I am getting a End of statement error and I am unsure how to fix it.

My table code is `

Create Table Pet_Owner (
OwnerID autoincrement Null,
OwnerLastName Char(30) Not Null,
OwnerFirstName Char(30) Not Null,
OwnerPhone Int Null,
OwnerEmail VarChar(100) Not Null Unique,
Constraint Pet_Owner_PK Primary Key(OwnerID)
);

and the insert query I have so far that I am trying to add is

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Downs' , 'Marsha' , '555-537-8765' , 'Marsha.downs@somewhere.com')
Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'James' , 'Richard' , '555-537-7654' , 'Richard.James@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail) Values (
'Frier' , 'Liz' , '555-537-6543' , 'Liz.Frier@somewhere.com')
Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerEmail) Values (
'Trent', 'Miles', 'Miles.Trent@somewhere.com') ;

When I use append, it is saying I am missing a semicolon at the end of the first set of values, but if i add that then it says i have characters at the end of my statement. If anyone can help me out or point me into the right direction to solve the error I would greatly appreciate it. Thank you

Body:
You would need to start each statement with insert into, and separate them with ;.

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail)
Values ('Downs' , 'Marsha' , '555-537-8765' , 'Marsha.downs@somewhere.com');

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail)
Values ('James' , 'Richard' , '555-537-7654' , 'Richard.James@somewhere.com');

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerPhone, OwnerEmail)
Values ('Frier' , 'Liz' , '555-537-6543' , 'Liz.Frier@somewhere.com');

Insert Into Pet_Owner (OwnerLastName, OwnerFirstName, OwnerEmail)
Values ('Trent', 'Miles', 'Miles.Trent@somewhere.com');


问:
Cannot access androidx.lifecycle.LifecycleOwner, what is the meaning of error in Android?
On which situation android-build/android-studio shows these errors?

Cannot access androidx.lifecycle.LifecycleOwner
  and

  Cannot access androidx.lifecycle.ViewModelStoreOwner

What is the meaning of this errors? I found that adding androidx.lifecycle:lifecycle-viewmodel as dependency solves these errors, I want to know the meaning of the error in terms of Android Activity LifeCycle(Or is it related to lifecycle or not).

For example in this code call to `super' onSavedInstanceState shows this error

```<code>public class AppActivity extends FragmentActivity {

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);  // Cannot access androidx.lifecycle.LifecycleOwner
    }

}
</code>```

When should I use Android Lifecycles,and when should I avoid using it?

答:
For the sake of completeness, even after adding the dependencies and having properly migrated to androidx using the one-click refactoring, you would still get intellisense errors against your Kotlin code saying

```<code>Cannot access 'Cannot access androidx.lifecycle.LifecycleOwner' ...
</code>```

, although the project builds fine.

Then you would have to

Quit Android Studio

Remove project/.idea folder

Remove ~/.gradle folder

Restart Android Studio

File > Invalidate Caches / Restart won't work.

Body:
On which situation android-build/android-studio shows these errors?

Cannot access androidx.lifecycle.LifecycleOwner
  and

  Cannot access androidx.lifecycle.ViewModelStoreOwner

What is the meaning of this errors? I found that adding androidx.lifecycle:lifecycle-viewmodel as dependency solves these errors, I want to know the meaning of the error in terms of Android Activity LifeCycle(Or is it related to lifecycle or not).

For example in this code call to `super' onSavedInstanceState shows this error

public class AppActivity extends FragmentActivity {

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);  // Cannot access androidx.lifecycle.LifecycleOwner
    }

}

When should I use Android Lifecycles,and when should I avoid using it?

Body:
For the sake of completeness, even after adding the dependencies and having properly migrated to androidx using the one-click refactoring, you would still get intellisense errors against your Kotlin code saying

Cannot access 'Cannot access androidx.lifecycle.LifecycleOwner' ...

, although the project builds fine.

Then you would have to

Quit Android Studio

Remove project/.idea folder

Remove ~/.gradle folder

Restart Android Studio

File > Invalidate Caches / Restart won't work.


问:
How to handle a linq query that returns zero rows and have it return decimal value?
When a this function is given an id that in SQL returns 0 rows I get the error below:

The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.

What is the best way to modify the query to prevent this. I am pulling the value from a different table than I am querying here, so I would like to be able to handle giving it a "bad" id.

```<code>    public decimal GetSumOfValuesForAccount(Guid companyId)
    {
        return (from o in _context.Details
                where o.CustomerID == companyId
                select o).Sum(p => p.SomeValue.GetValueOrDefault());
    }
</code>```

Returns the error:

答:
you should be able to either return:

```<code>return (from o in _context.Details
                where o.CustomerID == companyId
                select o).Sum(p => p.SomeValue) ?? -1.0;
</code>```

or

```<code>decimal? temp = (from o in _context.Details
                where o.CustomerID == companyId
                select o).Sum(p => p.SomeValue);
return temp ?? -1.0;
</code>```

The ?? operator will check for null, and if null, return the next value.

ContentLicense: CC BY-SA 3.0

Body:
When a this function is given an id that in SQL returns 0 rows I get the error below:

The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.

What is the best way to modify the query to prevent this. I am pulling the value from a different table than I am querying here, so I would like to be able to handle giving it a "bad" id.

    public decimal GetSumOfValuesForAccount(Guid companyId)
    {
        return (from o in _context.Details
                where o.CustomerID == companyId
                select o).Sum(p => p.SomeValue.GetValueOrDefault());
    }

Returns the error:

Body:
you should be able to either return:

return (from o in _context.Details
                where o.CustomerID == companyId
                select o).Sum(p => p.SomeValue) ?? -1.0;

or

decimal? temp = (from o in _context.Details
                where o.CustomerID == companyId
                select o).Sum(p => p.SomeValue);
return temp ?? -1.0;

The ?? operator will check for null, and if null, return the next value.


问:
Creating roles with discord.js
I have tried almost all of the code snippets online and when I tried them I always get an error that says ReferenceError: guild is not defined.

case 'setup':
if (msg.member.roles.cache.find(r => r.name === "role")) return msg.reply('bot is already setup')
guild.roles.create({
  data: {
    name: 'role',
    color: 'GREY',
  },
  reason: 'idfk',
})
  .then(console.log)
  .catch(console.error);
break;
```

答:
The error is clear, you need to define guild or in this case, say which guild you're creating the role in, which would be msg.guild, the guild the message was sent in.

case 'setup':
if (msg.member.roles.cache.find(r => r.name === "role")) return msg.reply('bot is already setup')
msg.guild.roles.create({
  data: {
    name: 'role',
    color: 'GREY',
  },
  reason: 'idfk',
})
  .then(console.log)
  .catch(console.error);
break;
```

Title: Creating roles with discord.js


问:
Python write XML data from API to SQL Server (using parse to .csv as intermediate hop)
python novice here.

Trying to pull data from API and insert into SQL Server table (existing) for use in BI tool.

Original result from API is XML with a terribly unfriendly-for-a-novice format.

I have managed to parse this (likely not in the most pythonic way and open to suggestions) to .csv format (3 separate files due to nature of nested XML).  Now that I have these in .csv I am trying to write them to my SQL-Server tables, one table per .csv but have hit a snag.  I am using the code from this answer and all seems okay other than the leading comma that gets created in the column names section of the query.  Anyone help me remove that leading comma?

This is the code as I have written currently:

```<code>import json
import requests
import pandas as pd
import csv
from pandas.io.json import json_normalize
from datetime import date, timedelta

url = "https://**myAPI_URL.com/Transaction"

paramHeader = '{"Version": "1.0"'
paramHeader += ', "FromDate":"2020-05-01 00:00"'
paramHeader += ', "ToDate": "2020-05-31 00:00"'
paramHeader += ', "MerchantOrgID": null'
paramHeader += ', "CardholderOrgID": null'
paramHeader += ', "CardNumber": null'
paramHeader += ', "DriverID": null'
paramHeader += ', "VehicleID": null'
paramHeader += ', "BillingGroupID": null'
paramHeader += ', "BillingCycleID": null'
paramHeader += ', "EntryMethodID": null'
paramHeader += ', "CardTypeID": null'
paramHeader += ', "TranTypeID": null'
paramHeader += ', "TaxExemptOnly": null}'

headers = {'APIKey': '**myAPI_KEY**'
    , 'content-type': 'application/json'
    , 'Accept': 'application/json'
    , 'parameters': paramHeader}

response = requests.get(url, data='', headers=headers)
if response.status_code == 200:
    r = json.loads(response.content.decode('utf-8'))

    cleanData = pd.json_normalize(r)

    transactionDetails = pd.json_normalize(data=r, record_path='Details', meta=['ID'])

    taxes = pd.json_normalize(data=r, record_path=['Details', 'Taxes'],
                                 meta=['ID'])

    cleanData.to_csv('**filePath**/mainTransactions.csv')
    transactionDetails.to_csv('**filePath**/transactionsDetails.csv')
    taxes.to_csv('**filePath/transactionsTaxes.csv')

    import pyodbc
    connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=**serverIP**;PORT=1433;DATABASE=myDBName;UID=myUserID;PWD=myPWord;')

    with open('**filePath**/transactionsDetails.csv', 'r') as f:
        reader = csv.reader(f)
        columns = next(reader)
        query = 'insert into transactionDetails({0}) values ({1})'
        query = query.format(','.join(columns), ','.join('?' * (int(len(columns)))))
        print(query)   #for debug purposes
        cursor = connection.cursor()
        for data in reader:
            cursor.execute(query, data)
        cursor.commit()
</code>```

This code results in the following error:

```<code>insert into transactionDetails(,RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
Traceback (most recent call last):
  File "**workingDirectory**/myProject.py", line 85, in <module>
    cursor.execute(query, data)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near ','. (102) (SQLExecDirectW)")

Process finished with exit code 1
</code>```

Manually executing the same query (using all 1's as test data) after removing the leading comma results in a successful write to DB.

```<code>myTableName> insert into transactionDetails(RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
[2020-05-28 20:08:55] 1 row affected in 188 ms
</code>```

Thanks!

答:
This was resolved by removing the unnamed column from the .csv that my pandas df created using the snippet found here :

```<code>with open('**filePath**/transactionsDetails.csv', 'r') as source:
            rdr = csv.reader(source)
            with open('**filePath**/transactionsDetails2.csv', 'w') as result:
                wtr = csv.writer(result)
                for r in rdr:
                    wtr.writerow((r[1], r[3], r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15],r[16]))
</code>```

Full working code below:

```<code>import json
import requests
import pandas as pd
import csv
from pandas.io.json import json_normalize
from datetime import date, timedelta

url = "https://**myAPI**.com/Transaction"

paramHeader = '{"Version": "1.0"'
paramHeader += ', "FromDate":"2020-05-01 00:00"'
paramHeader += ', "ToDate": "2020-05-31 00:00"'
paramHeader += ', "MerchantOrgID": null'
paramHeader += ', "CardholderOrgID": null'
paramHeader += ', "CardNumber": null'
paramHeader += ', "DriverID": null'
paramHeader += ', "VehicleID": null'
paramHeader += ', "BillingGroupID": null'
paramHeader += ', "BillingCycleID": null'
paramHeader += ', "EntryMethodID": null'
paramHeader += ', "CardTypeID": null'
paramHeader += ', "TranTypeID": null'
paramHeader += ', "TaxExemptOnly": null}'

headers = {'APIKey': '**myAPIKey**'
    , 'content-type': 'application/json'
    , 'Accept': 'application/json'
    , 'parameters': paramHeader}

response = requests.get(url, data='', headers=headers)

if response.status_code == 200:
    r = json.loads(response.content.decode('utf-8'))

    cleanData = pd.json_normalize(r)
    transactionDetails = pd.json_normalize(data=r, record_path='Details', meta=['ID'])
    #print(transactionDetails)
    taxes = pd.json_normalize(data=r, record_path=['Details', 'Taxes'],
                                 meta=['ID'])

    cleanData.to_csv('**filePath**/mainTransactions.csv')
    transactionDetails.to_csv('**filePath**/transactionsDetails.csv')
    taxes.to_csv('**filePath**/transactionsTaxes.csv')

    import pyodbc
    connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=**serverIP**;PORT=1433;DATABASE=myDBName;UID=myUsername;PWD=myPword;')

    with open('**filePath**/transactionsDetails.csv', 'r') as source:
        rdr = csv.reader(source)
        with open('**filePath**/transactionsDetails2.csv', 'w') as result:
            wtr = csv.writer(result)
            for r in rdr:
                wtr.writerow((r[1], r[3], r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15],r[16]))

    with open('**filePath**/transactionsDetails2.csv', 'r') as f:
        reader = csv.reader(f)
        print(reader)
        columns = next(reader)
        query = 'insert into transactionDetails({0}) values ({1})'
        query = query.format(','.join(columns), ','.join('?' * (int(len(columns)))))
        print(query)
        cursor = connection.cursor()
        for data in reader:
            cursor.execute(query, data)
        cursor.commit()
    connection.close()
</code>```

I'm curious if anyone has a cleaner way to do this?

Body:
python novice here.

Trying to pull data from API and insert into SQL Server table (existing) for use in BI tool.

Original result from API is XML with a terribly unfriendly-for-a-novice format.

I have managed to parse this (likely not in the most pythonic way and open to suggestions) to .csv format (3 separate files due to nature of nested XML).  Now that I have these in .csv I am trying to write them to my SQL-Server tables, one table per .csv but have hit a snag.  I am using the code from this answer and all seems okay other than the leading comma that gets created in the column names section of the query.  Anyone help me remove that leading comma?

This is the code as I have written currently:

import json
import requests
import pandas as pd
import csv
from pandas.io.json import json_normalize
from datetime import date, timedelta

url = "https://**myAPI_URL.com/Transaction"

paramHeader = '{"Version": "1.0"'
paramHeader += ', "FromDate":"2020-05-01 00:00"'
paramHeader += ', "ToDate": "2020-05-31 00:00"'
paramHeader += ', "MerchantOrgID": null'
paramHeader += ', "CardholderOrgID": null'
paramHeader += ', "CardNumber": null'
paramHeader += ', "DriverID": null'
paramHeader += ', "VehicleID": null'
paramHeader += ', "BillingGroupID": null'
paramHeader += ', "BillingCycleID": null'
paramHeader += ', "EntryMethodID": null'
paramHeader += ', "CardTypeID": null'
paramHeader += ', "TranTypeID": null'
paramHeader += ', "TaxExemptOnly": null}'

headers = {'APIKey': '**myAPI_KEY**'
    , 'content-type': 'application/json'
    , 'Accept': 'application/json'
    , 'parameters': paramHeader}

response = requests.get(url, data='', headers=headers)
if response.status_code == 200:
    r = json.loads(response.content.decode('utf-8'))

    cleanData = pd.json_normalize(r)

    transactionDetails = pd.json_normalize(data=r, record_path='Details', meta=['ID'])

    taxes = pd.json_normalize(data=r, record_path=['Details', 'Taxes'],
                                 meta=['ID'])

    cleanData.to_csv('**filePath**/mainTransactions.csv')
    transactionDetails.to_csv('**filePath**/transactionsDetails.csv')
    taxes.to_csv('**filePath/transactionsTaxes.csv')

    import pyodbc
    connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=**serverIP**;PORT=1433;DATABASE=myDBName;UID=myUserID;PWD=myPWord;')

    with open('**filePath**/transactionsDetails.csv', 'r') as f:
        reader = csv.reader(f)
        columns = next(reader)
        query = 'insert into transactionDetails({0}) values ({1})'
        query = query.format(','.join(columns), ','.join('?' * (int(len(columns)))))
        print(query)   #for debug purposes
        cursor = connection.cursor()
        for data in reader:
            cursor.execute(query, data)
        cursor.commit()

This code results in the following error:

insert into transactionDetails(,RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
Traceback (most recent call last):
  File "**workingDirectory**/myProject.py", line 85, in <module>
    cursor.execute(query, data)
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near ','. (102) (SQLExecDirectW)")

Process finished with exit code 1

Manually executing the same query (using all 1's as test data) after removing the leading comma results in a successful write to DB.

myTableName> insert into transactionDetails(RowNumber,RawProductCode,RawUnitPrice,RawAmount,Quantity,ResolvedProductID,ProductCategoryID,ProductCategory,IsFuel,ProductName,ProductCode,IsTaxProduct,ResolvedUnitPrice,ResolvedAmount,Taxes,ID) values (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
[2020-05-28 20:08:55] 1 row affected in 188 ms

Thanks!

Body:
This was resolved by removing the unnamed column from the .csv that my pandas df created using the snippet found here :

with open('**filePath**/transactionsDetails.csv', 'r') as source:
            rdr = csv.reader(source)
            with open('**filePath**/transactionsDetails2.csv', 'w') as result:
                wtr = csv.writer(result)
                for r in rdr:
                    wtr.writerow((r[1], r[3], r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15],r[16]))

Full working code below:

import json
import requests
import pandas as pd
import csv
from pandas.io.json import json_normalize
from datetime import date, timedelta

url = "https://**myAPI**.com/Transaction"

paramHeader = '{"Version": "1.0"'
paramHeader += ', "FromDate":"2020-05-01 00:00"'
paramHeader += ', "ToDate": "2020-05-31 00:00"'
paramHeader += ', "MerchantOrgID": null'
paramHeader += ', "CardholderOrgID": null'
paramHeader += ', "CardNumber": null'
paramHeader += ', "DriverID": null'
paramHeader += ', "VehicleID": null'
paramHeader += ', "BillingGroupID": null'
paramHeader += ', "BillingCycleID": null'
paramHeader += ', "EntryMethodID": null'
paramHeader += ', "CardTypeID": null'
paramHeader += ', "TranTypeID": null'
paramHeader += ', "TaxExemptOnly": null}'

headers = {'APIKey': '**myAPIKey**'
    , 'content-type': 'application/json'
    , 'Accept': 'application/json'
    , 'parameters': paramHeader}

response = requests.get(url, data='', headers=headers)

if response.status_code == 200:
    r = json.loads(response.content.decode('utf-8'))

    cleanData = pd.json_normalize(r)
    transactionDetails = pd.json_normalize(data=r, record_path='Details', meta=['ID'])
    #print(transactionDetails)
    taxes = pd.json_normalize(data=r, record_path=['Details', 'Taxes'],
                                 meta=['ID'])

    cleanData.to_csv('**filePath**/mainTransactions.csv')
    transactionDetails.to_csv('**filePath**/transactionsDetails.csv')
    taxes.to_csv('**filePath**/transactionsTaxes.csv')

    import pyodbc
    connection = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=**serverIP**;PORT=1433;DATABASE=myDBName;UID=myUsername;PWD=myPword;')

    with open('**filePath**/transactionsDetails.csv', 'r') as source:
        rdr = csv.reader(source)
        with open('**filePath**/transactionsDetails2.csv', 'w') as result:
            wtr = csv.writer(result)
            for r in rdr:
                wtr.writerow((r[1], r[3], r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15],r[16]))

    with open('**filePath**/transactionsDetails2.csv', 'r') as f:
        reader = csv.reader(f)
        print(reader)
        columns = next(reader)
        query = 'insert into transactionDetails({0}) values ({1})'
        query = query.format(','.join(columns), ','.join('?' * (int(len(columns)))))
        print(query)
        cursor = connection.cursor()
        for data in reader:
            cursor.execute(query, data)
        cursor.commit()
    connection.close()

I'm curious if anyone has a cleaner way to do this?


问:
Disable PyCharm's light bulbs while keeping intentions available?
I like PyCharm's intentions when I want them, not when they are constantly popping up via the light bulb to distract me.

Is there a way to disable the light bulbs but have the intentions still available as normal via Alt-Enter?

Note this similar question shows an editor.xml config option for IntelliJ to hide the light bulb. PyCharm is based on IntelliJ but I can't find any such XML config file in my installation.

答:
For Windows in 2020 and PyCharm community edition:

@Ghopper21's xml file may be located here:

C:\Users\\AppData\Roaming\JetBrains\PyCharmCE2020.1\options

Another option, in PyCharm IDE:

File -> Settings -> Editor -> Inspections -> Python

Then deselect everything.

This illustrious lightbulb issue may have me moving back to Anaconda's Spyder or EMACS


问:
How to stack marginal increase/decrease? Stacked bar plot -R
This question seems fairly simple, but I wasn't able to find another post that answers it (apologies if I've missed it though).

I have a variable with three factors (a value for each month). The data looks like the below:

```<code>id  variable value
AZ   Feb-20  1085
AZ   Mar-20     1
AZ   Apr-20    61
CO   Feb-20     6
CO   Mar-20   192
FO   Apr-20     2
</code>```

I want to stack the data, such that I have a bar for February, and then the marginal increases for March, and April stacked on top.

Right now, the values for each month are stacked on top of each other.

```<code>ggplot(df3, aes(x = id, y = value, fill=factor(variable, levels=c("Apr-20","Mar-20", "Feb-20")))) + geom_bar(stat = "identity")

</code>```

How do I stack the increases from February? Is there a way to modify a stacked bar plot or do I need to try another method?

EDIT

After thinking on this, I believe the best solution is overlapping bars. But higher bars cover smaller bars. Changing the transparency isn't very useful with three factors. Maybe there is a way to reorder so that the smaller bars are in the forefront?

```<code>ggplot(df2) +geom_bar(aes(x = id, y = `Feb-20`), position = "identity",stat="identity", fill = 'green') +
  geom_bar(aes(x = id, y = `Mar-20`), position = "identity", stat="identity",fill = 'navy') +
  geom_bar(aes(x = id, y = `Apr-20`), position = "identity", stat="identity", fill = 'red')
</code>```

Second Edit
Apologies, this is my fault for being unclear. Prior, I wanted to avoid the cumulative summing that occurs with stacked barplots, and asked that each additional month be added as a marginal increase.

Now, though, as overlapping barplots, it is not necessary for the bars to display change. The problem with the overlapping bar charts is just that the data is obscured for bars with a shorter height.

This plot still plots marginal change. I'm looking for something like plot 2 in this post, but where all of the data is visible.

EDIT 3

Maybe this is a better way to explain:

Take the example of 'WA' in the first plot. For Feb, the data point was 338, for March, the data point was 318, and for April, the data point was 2270. A stacked bar plot adds these on top of each other, cumulatively.

However, the bar that I want for 'WA' should really show 338 for February, then a drop of 20 for March. And finally, an addition of 1952 for April.

This is why I had used the language of a marginal increase/decrease for a stacked barplot. I had also tried an overlapping barplot, but all of the data is not visible, and longer bars cover shorter bars.

答:
We can arrange based on converting the column to yearmon class (from zoo), then convert to factor with levels specified as the unique elements (or do a match and convert)

```<code>library(dplyr)
library(zoo)
library(ggplot2)
df1 %>%
    arrange(id, as.yearmon(variable, '%b-%y')) %>%
    mutate(variable = factor(variable, levels = unique(variable))) %>%
    ggplot(aes(x = id, y = value, fill = variable)) +
        geom_bar(stat = "identity")
</code>```

If we wanted to automate the second plot

```<code>library(tidyr)

df2 <- df1 %>%
       pivot_wider(names_from = variable, values_from = value)

p <- ggplot(df2)

colrs <- c('green', 'navy', 'red')
nm1 <- names(df2)[-1]
for(i in seq_along(nm1)) p <- p +
          geom_bar(aes(x = id, y = !! rlang::sym(nm1[i])),
          position = 'identity', stat = 'identity', fill = colrs[i])
</code>```

Body:
This question seems fairly simple, but I wasn't able to find another post that answers it (apologies if I've missed it though).

I have a variable with three factors (a value for each month). The data looks like the below:

id  variable value
AZ   Feb-20  1085
AZ   Mar-20     1
AZ   Apr-20    61
CO   Feb-20     6
CO   Mar-20   192
FO   Apr-20     2

I want to stack the data, such that I have a bar for February, and then the marginal increases for March, and April stacked on top.

Right now, the values for each month are stacked on top of each other.

ggplot(df3, aes(x = id, y = value, fill=factor(variable, levels=c("Apr-20","Mar-20", "Feb-20")))) + geom_bar(stat = "identity")

How do I stack the increases from February? Is there a way to modify a stacked bar plot or do I need to try another method?

EDIT

After thinking on this, I believe the best solution is overlapping bars. But higher bars cover smaller bars. Changing the transparency isn't very useful with three factors. Maybe there is a way to reorder so that the smaller bars are in the forefront?

ggplot(df2) +geom_bar(aes(x = id, y = `Feb-20`), position = "identity",stat="identity", fill = 'green') +
  geom_bar(aes(x = id, y = `Mar-20`), position = "identity", stat="identity",fill = 'navy') +
  geom_bar(aes(x = id, y = `Apr-20`), position = "identity", stat="identity", fill = 'red')

Second Edit
Apologies, this is my fault for being unclear. Prior, I wanted to avoid the cumulative summing that occurs with stacked barplots, and asked that each additional month be added as a marginal increase.

Now, though, as overlapping barplots, it is not necessary for the bars to display change. The problem with the overlapping bar charts is just that the data is obscured for bars with a shorter height.

This plot still plots marginal change. I'm looking for something like plot 2 in this post, but where all of the data is visible.

EDIT 3

Maybe this is a better way to explain:

Take the example of 'WA' in the first plot. For Feb, the data point was 338, for March, the data point was 318, and for April, the data point was 2270. A stacked bar plot adds these on top of each other, cumulatively.

However, the bar that I want for 'WA' should really show 338 for February, then a drop of 20 for March. And finally, an addition of 1952 for April.

This is why I had used the language of a marginal increase/decrease for a stacked barplot. I had also tried an overlapping barplot, but all of the data is not visible, and longer bars cover shorter bars.

Body:
We can arrange based on converting the column to yearmon class (from zoo), then convert to factor with levels specified as the unique elements (or do a match and convert)

library(dplyr)
library(zoo)
library(ggplot2)
df1 %>%
    arrange(id, as.yearmon(variable, '%b-%y')) %>%
    mutate(variable = factor(variable, levels = unique(variable))) %>%
    ggplot(aes(x = id, y = value, fill = variable)) +
        geom_bar(stat = "identity")

If we wanted to automate the second plot

library(tidyr)

df2 <- df1 %>%
       pivot_wider(names_from = variable, values_from = value)

p <- ggplot(df2)

colrs <- c('green', 'navy', 'red')
nm1 <- names(df2)[-1]
for(i in seq_along(nm1)) p <- p +
          geom_bar(aes(x = id, y = !! rlang::sym(nm1[i])),
          position = 'identity', stat = 'identity', fill = colrs[i])


问:
Is it possible to set the Expires/Max-Age of an existing cookie with the Set-Cookie header?
I'm trying to have the expiration of an existing cookie on a site update from "Session" to some date in the future using the Set-Cookie header.

I believe my issue has to do with limitations on how browsers interpret the Path directive on the Set-Cookie header but I'm not sure nor can I find a use case quite like mine.

Example use case:

Browser navigates to:

```<code>GET / HTTP/2
Host: example.com
</code>```

Server replies:

```<code>HTTP/2 200
set-cookie: PHPSESSID=abcd; Path=/; SameSite=None; Secure
</code>```

Browser performs action and navigates to:

```<code>POST /some/path HTTP/2
Cookie: PHPSESSID=abcd;...
</code>```

Server replies:

```<code>HTTP/2 302
Set-Cookie: PHPSESSID=dcba; expires=Mon, 17-Aug-2020 19:08:24 GMT; Max-Age=7776000; path=/
Location: /somewhere-else
</code>```

All following requests from the browser contain the updated cookie value:

```<code>Cookie: PHPSESSID=dcba;...
</code>```

Yet, upon inspecting the cookies with the dev tools (or simply closing the browser) I noticed that the Expires/Max-Age of the cookie is still "Session" (tried on Chrome and Firefox).

Is being able to update the value but not the expiration of a cookie through a Set-Cookie header a known/expected behavior? Or is there perhaps something wrong with how it's formed?

答:
For any that come across this question/issue:

I discovered(?) that with each Set-Cookie header received: the browser will update the Expiration/Max-Age of that cookie to "Session" if it is absent but will not update other directive values to anything else if they are absent (such as the Secure flag or the value for SameSite).

This revealed that the underlying issue was that, in the next page, there was a request happening with the Set-Cookie header but did not have any value for the expires/Max-Age directives thus resetting the expiration to "Session", making the solution to ensure every Set-Cookie response header has a deliberate value (or absence) for the expires and/or Max-Age directive.

Explained with raw http, continuing the example in the question:

If the response for say an ajax request comes back with:

```<code>HTTP/2 200
Set-Cookie: PHPSESSID=efgh; Path=/; SameSite=None; Secure
</code>```

Then the browser will update the cookie's value and set its expiration from "17-Aug-2020 19:08:24 GMT" to "Session".

Making the solution, as mentioned before, to ensure that the response contains the correct (or deliberate) value for the expires or Max-Age directive, so the correct response for the ajax call that accidentally set the expiration to "Session" in the example above would be something like:

```<code>HTTP/2 200
Set-Cookie: PHPSESSID=efgh; expires=Mon, 17-Aug-2020 19:08:24 GMT; Max-Age=7775900; Path=/
</code>```

Body:
I'm trying to have the expiration of an existing cookie on a site update from "Session" to some date in the future using the Set-Cookie header.

I believe my issue has to do with limitations on how browsers interpret the Path directive on the Set-Cookie header but I'm not sure nor can I find a use case quite like mine.

Example use case:

Browser navigates to:

GET / HTTP/2
Host: example.com

Server replies:

HTTP/2 200
set-cookie: PHPSESSID=abcd; Path=/; SameSite=None; Secure

Browser performs action and navigates to:

POST /some/path HTTP/2
Cookie: PHPSESSID=abcd;...

Server replies:

HTTP/2 302
Set-Cookie: PHPSESSID=dcba; expires=Mon, 17-Aug-2020 19:08:24 GMT; Max-Age=7776000; path=/
Location: /somewhere-else

All following requests from the browser contain the updated cookie value:

Cookie: PHPSESSID=dcba;...

Yet, upon inspecting the cookies with the dev tools (or simply closing the browser) I noticed that the Expires/Max-Age of the cookie is still "Session" (tried on Chrome and Firefox).

Is being able to update the value but not the expiration of a cookie through a Set-Cookie header a known/expected behavior? Or is there perhaps something wrong with how it's formed?

Body:
For any that come across this question/issue:

I discovered(?) that with each Set-Cookie header received: the browser will update the Expiration/Max-Age of that cookie to "Session" if it is absent but will not update other directive values to anything else if they are absent (such as the Secure flag or the value for SameSite).

This revealed that the underlying issue was that, in the next page, there was a request happening with the Set-Cookie header but did not have any value for the expires/Max-Age directives thus resetting the expiration to "Session", making the solution to ensure every Set-Cookie response header has a deliberate value (or absence) for the expires and/or Max-Age directive.

Explained with raw http, continuing the example in the question:

If the response for say an ajax request comes back with:

HTTP/2 200
Set-Cookie: PHPSESSID=efgh; Path=/; SameSite=None; Secure

Then the browser will update the cookie's value and set its expiration from "17-Aug-2020 19:08:24 GMT" to "Session".

Making the solution, as mentioned before, to ensure that the response contains the correct (or deliberate) value for the expires or Max-Age directive, so the correct response for the ajax call that accidentally set the expiration to "Session" in the example above would be something like:

HTTP/2 200
Set-Cookie: PHPSESSID=efgh; expires=Mon, 17-Aug-2020 19:08:24 GMT; Max-Age=7775900; Path=/


问:
Is there a way to specify a relative border-box width and a minimum content width?
Is there a way to apply different box-sizing to different width specs? Can the min width be specified to use content-box and a % width to use border-box, or does box-sizing apply to all width specs on the element?

td,
th {
  border: 1px solid;
  width: 1px;
}

input {
  /* including padding and border */
  width: 100%;
  /* based on content only */
  min-width: 2em;
  /* box-sizing: border-box; */
  /* emphasized border to really show the issue. */
  border: 8px solid;
}

div {
  white-space: nowrap;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <th>
      <div>Content that increases the width of the column</div>
    </th>
    <th>
      <div>...
        <!-- content less than the desired minimum width of the input element -->
      </div>
    </th>
  </tr>
  <tr>
    <td><input type="text" value="42" /></td>
    <td><input type="text" value="42" /></td>
  </tr>
</table></code>```

In this particular case, the input should fill the width of the column without going beyond. Uncommenting the box-sizing fixes this, but makes the content space of the input less than the desired minimum width.

答:
Here's the JavaScript solution I've developed so far:

$("[style*='min-width']").each(function(ndx, elem) {
    $elem = $(elem);
    $elem.css("min-width", parseInt($elem.css("min-width").slice(0, -2)) + $(elem).outerWidth() - $(elem).width() + "px");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td,
th {
  border: 1px solid;
  width: 1px;
}

input {
  width: 100%;
  /* including padding and border */
  box-sizing: border-box;
  /* emphasized border to really show the issue. */
  border: 8px solid;
}

div {
  white-space: nowrap;
}</code>```

Content that increases the width of the column

...

    <input type="text" value="42" style="min-width: 2em;" />
    <input type="text" value="42" style="min-width: 2em;" />

```

Body:
Is there a way to apply different box-sizing to different width specs? Can the min width be specified to use content-box and a % width to use border-box, or does box-sizing apply to all width specs on the element?

td,
th {
  border: 1px solid;
  width: 1px;
}

input {
  /* including padding and border */
  width: 100%;
  /* based on content only */
  min-width: 2em;
  /* box-sizing: border-box; */
  /* emphasized border to really show the issue. */
  border: 8px solid;
}

div {
  white-space: nowrap;
}

Content that increases the width of the column

...

    <input type="text" value="42" />
    <input type="text" value="42" />

In this particular case, the input should fill the width of the column without going beyond. Uncommenting the box-sizing fixes this, but makes the content space of the input less than the desired minimum width.

Body:
Here's the JavaScript solution I've developed so far:

$("[style*='min-width']").each(function(ndx, elem) {
    $elem = $(elem);
    $elem.css("min-width", parseInt($elem.css("min-width").slice(0, -2)) + $(elem).outerWidth() - $(elem).width() + "px");
})

td,
th {
  border: 1px solid;
  width: 1px;
}

input {
  width: 100%;
  /* including padding and border */
  box-sizing: border-box;
  /* emphasized border to really show the issue. */
  border: 8px solid;
}

div {
  white-space: nowrap;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<table>
  <tr>
    <th>
      <div>Content that increases the width of the column</div>
    </th>
    <th>
      <div>...
        <!-- content less than the desired minimum width of the input element -->
      </div>
    </th>
  </tr>
  <tr>
    <td><input type="text" value="42" style="min-width: 2em;" /></td>
    <td><input type="text" value="42" style="min-width: 2em;" /></td>
  </tr>
</table>


问:
Authentication plugin 'caching_sha2_password' is not supported
I am trying to connect to a MySQL server with python connector. I created a new user lcherukuri with the authentication plugin mysql_native_password.

But I got the error

mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported

Can someone help me?

```<code>import mysql.connector

cnx = mysql.connector.connect(user='lcherukuri', password='password',
                              host='127.0.0.1',
                              database='test')
cnx.close()
</code>```

答: Using MySql 8 I got the same error when connecting my code to the DB, using the pip install mysql-connector-python did solve this error.</p>

Body:
I am trying to connect to a MySQL server with python connector. I created a new user lcherukuri with the authentication plugin mysql_native_password.

But I got the error

mysql.connector.errors.NotSupportedError: Authentication plugin 'caching_sha2_password' is not supported

Can someone help me?

import mysql.connector

cnx = mysql.connector.connect(user='lcherukuri', password='password',
                              host='127.0.0.1',
                              database='test')
cnx.close()


问:
TypeError: context.guild.members.has is not a function(162:30)
I was adding new features to my Discord Bot then suddenly the following problem has stopped me from completing my code !
( What is my mistake ? Where is my mistake ? How can I solve it ? )

The Problem :
TypeError: context.guild.members.has is not a function(162:30)

My Code :

```<code>1:     const { RichEmbed } = require("discord.js");
2:     const timedEvents = ["minute", "fiveMinutes", "fifteenMinutes", "halfAnHour", "hour", "day"];

157:   const getMember = context => {
158:       if (!context.member) {
159:           if (context.newMember)
160:               context.member = context.newMember;
161:           if (context.guild && context.user && !context.member)
162:               if (context.guild.members.has(context.user.id))
163:                   context.member = context.guild.members.get(context.user.id);
164:       }
165:   };
</code>```

答:
Since discord.js v12, you need to use cache to access the members collection.

const getMember = context => {
  if (!context.member) {
    if (context.newMember)
      context.member = context.newMember;
    if (context.guild && context.user && !context.member)
      if (context.guild.members.cache.has(context.user.id))
        context.member = context.guild.members.cache.get(context.user.id);
  }
};
```

Body:
I was adding new features to my Discord Bot then suddenly the following problem has stopped me from completing my code !
( What is my mistake ? Where is my mistake ? How can I solve it ? )

The Problem :
TypeError: context.guild.members.has is not a function(162:30)

My Code :

1:     const { RichEmbed } = require("discord.js");
2:     const timedEvents = ["minute", "fiveMinutes", "fifteenMinutes", "halfAnHour", "hour", "day"];

157:   const getMember = context => {
158:       if (!context.member) {
159:           if (context.newMember)
160:               context.member = context.newMember;
161:           if (context.guild && context.user && !context.member)
162:               if (context.guild.members.has(context.user.id))
163:                   context.member = context.guild.members.get(context.user.id);
164:       }
165:   };


问:
Using a Blob as iframe source and a trouble with loading img src images located in a subdirectory
EDIT: I added live version of the issue here:
https://www.lieksa.info/demot/stackoverflow/blob_issue/problem.html

I am trying to use Javascript to preview images inside an iFrame to show the user how the image looks like. The images are located in a subdirectory, for example: "kuvat/kuva0.jpg".

If a user presses "preview" button, I take the generated html data (html source data in a string format) and turn it into a Blob object and use that as a iframe source for preview.

The generated html and images itself does work, if for example copy-pasted in to a new .html file and displayd via there. Images and everything display nicely.

The problem is that the images in the subdirectory and referenced using "src" inside img html-tag are not working after conversion into iFrame source. What happens to the image source paths and references during the Blob and URL.createObjectURL(blob) process?

Generated html source code includes images in the following way

```<code><img src="kuvat/kuva0.jpg" alt="slideshow image">
</code>```

Below is the Blob and iframe process:

```<code>var html_source = document.getElementById("source_container").value;
var blob = new Blob([html_source], {type: "text/html"});
document.getElementById("iframe_container").src = URL.createObjectURL(blob);
</code>```

I even tried only to pass only the image tag in to Blob object and also test a File object. But neither of them worked:

```<code>var blob = new Blob(['<img src="kuvat/kuva0.jpg" alt="slideshow image">'], {type: "text/html"});
var file = new File(['<img src="kuvat/kuva0.jpg" alt="slideshow image">'], "index.html", { type: "text/plain"});

document.getElementById("preview_container").src = URL.createObjectURL(blob);
// or
document.getElementById("preview_container").src = URL.createObjectURL(file);
</code>```

答:
The problem is that your iframe's document's baseURI is set to blob:https://www.lieksa.info/[UUID].

So when the browser will try to resolve the relative path of the image, it will use that baseURI to resolve it, resulting in an invalid URI:

const http_base = "https://www.lieksa.info/[UUID]";
console.log( 'http:', new URL( "kuva1.jpg", http_base ) ); // Success

const blob_base = "blob:https://www.lieksa.info/[UUID]";
console.log( 'blob:', new URL( "kuva1.jpg", blob_base ) ); // Error```
</div>
</div>
</p>

<p>To fix that, you can append a <code><base></code> element in the head of your document, <strong>before the <code><img></code> gets declared</strong>, this will set the correct <code>baseURI</code> for your document and the browser will be able to parse your relative path correctly:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const frame = document.getElementById('frame');
const html_content = `<!DOCTYPE html>
<html>
<head>
  <title>Test relative URI in blob:// frame</title>
  <!-- here we set the baseURI of our document -->
  <base href="https://upload.wikimedia.org/wikipedia/commons/4/47/">
</head>
<body>
  <!-- here we can use relative URIs, as if we were really on wikimedia's page -->
  <img src="PNG_transparency_demonstration_1.png" width="300">
</body>
</html>`;
const blob = new Blob( [html_content], { type: "text/html" } );
frame.src = URL.createObjectURL( blob );</code>```

```

Body:
EDIT: I added live version of the issue here:
https://www.lieksa.info/demot/stackoverflow/blob_issue/problem.html

I am trying to use Javascript to preview images inside an iFrame to show the user how the image looks like. The images are located in a subdirectory, for example: "kuvat/kuva0.jpg".

If a user presses "preview" button, I take the generated html data (html source data in a string format) and turn it into a Blob object and use that as a iframe source for preview.

The generated html and images itself does work, if for example copy-pasted in to a new .html file and displayd via there. Images and everything display nicely.

The problem is that the images in the subdirectory and referenced using "src" inside img html-tag are not working after conversion into iFrame source. What happens to the image source paths and references during the Blob and URL.createObjectURL(blob) process?

Generated html source code includes images in the following way

Below is the Blob and iframe process:

var html_source = document.getElementById("source_container").value;
var blob = new Blob([html_source], {type: "text/html"});
document.getElementById("iframe_container").src = URL.createObjectURL(blob);

I even tried only to pass only the image tag in to Blob object and also test a File object. But neither of them worked:

var blob = new Blob([''], {type: "text/html"});
var file = new File([''], "index.html", { type: "text/plain"});

document.getElementById("preview_container").src = URL.createObjectURL(blob);
// or
document.getElementById("preview_container").src = URL.createObjectURL(file);

Body:
The problem is that your iframe's document's baseURI is set to blob:https://www.lieksa.info/[UUID].

So when the browser will try to resolve the relative path of the image, it will use that baseURI to resolve it, resulting in an invalid URI:

const http_base = "https://www.lieksa.info/[UUID]";
console.log( 'http:', new URL( "kuva1.jpg", http_base ) ); // Success

const blob_base = "blob:https://www.lieksa.info/[UUID]";
console.log( 'blob:', new URL( "kuva1.jpg", blob_base ) ); // Error

To fix that, you can append a <base> element in the head of your document, before the <img> gets declared, this will set the correct baseURI for your document and the browser will be able to parse your relative path correctly:

const frame = document.getElementById('frame');
const html_content = `<!DOCTYPE html>
<html>
<head>
  <title>Test relative URI in blob:// frame</title>
  <!-- here we set the baseURI of our document -->
  <base href="https://upload.wikimedia.org/wikipedia/commons/4/47/">
</head>
<body>
  <!-- here we can use relative URIs, as if we were really on wikimedia's page -->
  <img src="PNG_transparency_demonstration_1.png" width="300">
</body>
</html>`;
const blob = new Blob( [html_content], { type: "text/html" } );
frame.src = URL.createObjectURL( blob );

<iframe id="frame"></iframe>


问:
dispatchEvent doesn't work in javascript with Internet explorer 11
In my website I have a javascript in which I wish to open a file save dialog. The purpose is to save in a text file some data that are coming from the web server.

I am trying to use the code snippet shown in this post:

[Using HTML5/JavaScript to generate and save a file

And to be precise:

```<code>function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}
</code>```

This works great for Firefox and Chrome. However with Internet Explorer 11 it doesn't work. When this instruction is executed...

```<code>pom.dispatchEvent(event);
</code>```

...nothing happens. The save dialog is not opened, and no error is shown in the java console of the browser. The event seems to get lost in the void.
Any help would be greatly appreciated.

答:
I tried to test the issue on my side and I can see that file is not getting download in the IE 11 browser.

Below is the modified code that you can use for the IE and other browsers. It will download the file properly.

```<code><!doctype html>
<html>
<head>
<script>
function download(data, filename, type)
{
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob)
    {
        window.navigator.msSaveOrOpenBlob(file, filename);
    }
    else
    {   var pom = document.createElement('a');
        pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
        pom.setAttribute('download', filename);

        if (document.createEvent)
        {
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            pom.dispatchEvent(event);
        }
        else
        {
            pom.click();
        }
    }
}
download('Hello world!','test.txt','text/plain');
</script>
</head>
<body>
<h2>Refresh the page</h2>
</body>
</html>
</code>```

Output in the IE 11 browser:

Body:
In my website I have a javascript in which I wish to open a file save dialog. The purpose is to save in a text file some data that are coming from the web server.

I am trying to use the code snippet shown in this post:

[Using HTML5/JavaScript to generate and save a file

And to be precise:

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

This works great for Firefox and Chrome. However with Internet Explorer 11 it doesn't work. When this instruction is executed...

pom.dispatchEvent(event);

...nothing happens. The save dialog is not opened, and no error is shown in the java console of the browser. The event seems to get lost in the void.
Any help would be greatly appreciated.

Body:
I tried to test the issue on my side and I can see that file is not getting download in the IE 11 browser.

Below is the modified code that you can use for the IE and other browsers. It will download the file properly.

<!doctype html>
<html>
<head>
<script>
function download(data, filename, type)
{
    var file = new Blob([data], {type: type});
    if (window.navigator.msSaveOrOpenBlob)
    {
        window.navigator.msSaveOrOpenBlob(file, filename);
    }
    else
    {   var pom = document.createElement('a');
        pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(data));
        pom.setAttribute('download', filename);

        if (document.createEvent)
        {
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            pom.dispatchEvent(event);
        }
        else
        {
            pom.click();
        }
    }
}
download('Hello world!','test.txt','text/plain');
</script>
</head>
<body>
<h2>Refresh the page</h2>
</body>
</html>

Output in the IE 11 browser:


问:
jquery how to figure out what the JSON Object contains
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

```<code>$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});
</code>```

If I do this - I get an object, but I don't know what it contains.

答:
I use this piece of code, please notice the error function which will trigger if the request was not successful. (ie error 500 on the server side)</p>

```<code>jQuery.ajax(
        {
            url: "http://yoururl/bla",
            success: function (data) { console.log(data); },
            error: function (data) { console.log(data); },
            dataType: "json",
            type: "POST",
            data: { name: "value", name2: "this will be posted in the request" }
        });
</code>```

Body:
I'm using JQuery with CodeIgniter PHP to figure make AJAX calls and return data via JSON. I want to figure out what my JSON object has returned, but I'm not sure what the syntax might be. Is there a way to just alert or log all the contents of the JSON object somehow? This is my code:

$.ajax({
    type: "GET",
    url: groups_url,
    success: function(parent){
        alert (parent);
    }
});

If I do this - I get an object, but I don't know what it contains.

Body:
I use this piece of code, please notice the error function which will trigger if the request was not successful. (ie error 500 on the server side)

jQuery.ajax(
        {
            url: "http://yoururl/bla",
            success: function (data) { console.log(data); },
            error: function (data) { console.log(data); },
            dataType: "json",
            type: "POST",
            data: { name: "value", name2: "this will be posted in the request" }
        });


问:
Can't use source code for deprecated control SlidableListItem
Microsoft has deprecated SlidableListItem in favour of SwipeControl. I tried SwipeControl using the XAML controls gallery - it does not let me swipe left and right with a mouse (I can using SlidableListItem). I think I need a touchscreen device for it to work.

So I'd like to continue using SlidableListItem despite having updated to the latest nuget packages.

I've copied the code for SlidableListItem into my project from WindowsCommunityToolKit branch 4.0.0. I get this crash when I try to use the control:

System.TypeLoadException: Failure has occurred while loading a
  type.\r\n   at Windows.UI.Xaml.FrameworkElement.MeasureOverride(Size
  availableSize)

(I successfully copied the code for the HamburgerControl into my project yesterday.)

答:
I tried to copy the source code of SlidableListItem, after paying attention to the following points, I successfully copied it:

If you don't need SwipeControl, please delete the related code:

Do not copy the code of SlidableListItemSwipeControlTemplate.xaml

Delete the properties and callback methods related to UseSwipeControlWhenPossible in SlidableListItem.cs (such as OnUseSwipeControlWhenPossibleChanged, OnSwipeControlValueChanged, UpdateSwipeControlItems, etc.)

In the SledableListItem.cs file, there are two places that refer to the resource file path, please modify it according to your own project structure (you can also delete the relevant code if SwipeControl is not needed)

If you are migrating the code to your own control library, please remember to introduce SlidableListItem.xaml resource file in App.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ms-appx:///Controls/SlidableListItem.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
```

But in fact, SwipeControl is a common control that UWP adapts to the operating habits of different platforms. On the desktop, we hold down the left mouse button and drag and drop is usually used to perform the transfer operation instead of calling out the secondary menu (we usually right-click on the desktop).

Simulating touch screen operation experience in keyboard and mouse mode is sometimes not a pleasant thing. If you plan to adapt to the operation habits of multiple platforms, please refer to this document to add compound commands.

Body:
I tried to copy the source code of SlidableListItem, after paying attention to the following points, I successfully copied it:

If you don't need SwipeControl, please delete the related code:

Do not copy the code of SlidableListItemSwipeControlTemplate.xaml

Delete the properties and callback methods related to UseSwipeControlWhenPossible in SlidableListItem.cs (such as OnUseSwipeControlWhenPossibleChanged, OnSwipeControlValueChanged, UpdateSwipeControlItems, etc.)

In the SledableListItem.cs file, there are two places that refer to the resource file path, please modify it according to your own project structure (you can also delete the relevant code if SwipeControl is not needed)

If you are migrating the code to your own control library, please remember to introduce SlidableListItem.xaml resource file in App.xaml

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ms-appx:///Controls/SlidableListItem.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

But in fact, SwipeControl is a common control that UWP adapts to the operating habits of different platforms. On the desktop, we hold down the left mouse button and drag and drop is usually used to perform the transfer operation instead of calling out the secondary menu (we usually right-click on the desktop).

Simulating touch screen operation experience in keyboard and mouse mode is sometimes not a pleasant thing. If you plan to adapt to the operation habits of multiple platforms, please refer to this document to add compound commands.


问:
Can you read/amend/replace AndroidManifest.xml file with a Custom Annotation Processor
I am investigating custom annotation processors for Android applications.

I have a use case where I would like to be able to use an annotation processor to read/amend the AndroidManifest.xml and add the following intent section for all Activities mentioned there in?

```<code>        <intent-filter>
            <action android:name="com.my.package.name.my_activity.open"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</code>```

Is this possible?

答:
In case you want to add these intents conditionally depending on flavour of your app, you could use gradle flavours and manifest merging to achieve this - read more about flavours at https://developer.android.com/studio/build/build-variants

Also refer to following question for example of using gradle to modify manifest

https://stackoverflow.com/a/22759572/9640177

Body:
I am investigating custom annotation processors for Android applications.

I have a use case where I would like to be able to use an annotation processor to read/amend the AndroidManifest.xml and add the following intent section for all Activities mentioned there in?

        <intent-filter>
            <action android:name="com.my.package.name.my_activity.open"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

Is this possible?


问:
Pass single table entry to another sibling component in react
I have a table that includes various country data (data is coming from API). There is an edit option with each table entry. What this edit does is take the user to another component by which the user can edit respective field data.

I have edit API ready for editing purposes, but I want to show data before editing. Of course, I can make another GET request from the edit page. But if possible I want to send each data (from table) to the edit component. So that there is no need for another GET request. I added the table code.

CodeSandbox Link

https://pitqx.csb.app/list

```<code>  <table className="table table-striped table-hover table-bordered">
                        <thead>
                            <tr>
                                <td><p className="paragraph">Country</p></td>
                                <td><p className="paragraph">State</p></td>
                                <td><p className="paragraph">City</p></td>
                                <td><p className="paragraph">Area</p></td>
                                <td><p className="paragraph">Postal Code</p></td>
                                <td> <p className="paragraph">Delete</p></td>
                                <td> <p className="paragraph">Action</p></td>
                            </tr>
                        </thead>
                        <tbody>

                        {
                            countries ?
                    countries.map((country,index) =>(
                        <tr key={index} data-id={country._id} >

                        <td>
                            <h3 className="paragraph">{country.country}</h3>
                        </td>
                        <td>
                            <h3 className="paragraph" style={marginBottom}>{country.state}</h3>

                        </td>
                        <td>
                            <p className="paragraph" style={marginBottom}>{country.city}</p>
                        </td>
                        <td>
                            <p className="paragraph" style={marginBottom}>{country.area}</p>
                        </td>

                         <td>
                         <p className="paragraph" style={marginBottom}>{country.postal_code}</p>
                         </td>
                          <td>
                         <i className="fa fa-trash" ></i>
                         </td>
                         <td className="relative">
                             <Link to={"/dashboard/setting/country-and-city-setting/edit/"+country._id}>
                                 <button type="button" className="golden-button-sm">Edit</button>
                             </Link>

                        </td>
                         </tr>

                    )) : null
                }

                        </tbody>
                    </table>

</code>```

答:
Here is what I find a solution. We can pass state data with the Link attribute itself.</p>

```<code>
<td className="relative">
 <Link
      to={{
         pathname:"/dashboard/setting/country-and-city-setting/edit/",
         state:country
         }}
  >
  <button type="button" className="golden-button-sm">Edit</button>
  </Link>

  </td>

</code>```

Body:
I have a table that includes various country data (data is coming from API). There is an edit option with each table entry. What this edit does is take the user to another component by which the user can edit respective field data.

I have edit API ready for editing purposes, but I want to show data before editing. Of course, I can make another GET request from the edit page. But if possible I want to send each data (from table) to the edit component. So that there is no need for another GET request. I added the table code.

CodeSandbox Link

https://pitqx.csb.app/list

Country

State

City

Area

Postal Code

Delete

Action

                        {
                            countries ?
                    countries.map((country,index) =>(

{country.country}

{country.state}

{country.city}

{country.area}

{country.postal_code}

                             <Link to={"/dashboard/setting/country-and-city-setting/edit/"+country._id}>
                                 <button type="button" className="golden-button-sm">Edit</button>
                             </Link>

                    )) : null
                }

Body:
Here is what I find a solution. We can pass state data with the Link attribute itself.

<td className="relative">
 <Link
      to={{
         pathname:"/dashboard/setting/country-and-city-setting/edit/",
         state:country
         }}
  >
  <button type="button" className="golden-button-sm">Edit</button>
  </Link>

  </td>


问:
Refresh previous screen on goBack()
I am new to React Native. How can we refresh/reload previous screen when returning to it by calling goBack()?

Lets say we have 3 screens A, B, C:

```<code>A -> B -> C
</code>```

When we run goBack() from screen C it goes back to screen B but with old state/data. How can we refresh it? The constructor doesn't get called 2nd time.

答:
I have a similar situation and the way i refreshed was to reset the route when the back button is pressed. So, what happens is when the back button is pressed the screen is re-pushed into the stack and the useEffect on my screen loads the data

navigation.reset({
  index: 0,
  routes: [{ name: "SCREEN WHERE THE GOBACK BUTTON SHOULD GO" }],
});```

Title: Refresh previous screen on goBack()

Body:
I am new to React Native. How can we refresh/reload previous screen when returning to it by calling goBack()?

Lets say we have 3 screens A, B, C:

A -> B -> C

When we run goBack() from screen C it goes back to screen B but with old state/data. How can we refresh it? The constructor doesn't get called 2nd time.


问:
Customising Session ID's?
I'm building a little shoppping cart in WebMatrix (C#), and I would like to know if it's possible to customize session id's. And also, let's just say thatI have 2 tables, one table is for Orders and the other one is Cart.

The items of an order go into the Cart table, and when the person has paid for an order, then an OrderId is generated and details about that order go into the Orders table. But, how am I to know, from the Orders table, which Order corresponds to an Order Item in the Cart Table?

That's when I thought of using Session Id's. Am I doing this the right way?

答:
First, your question.

You can customize session IDs by implementing your own ISessionIDManager.

Now, is that the right solution?

In my opinion, I would say no. I'd have an Order and OrderItem table with a 1->* relationship, and have the entirety of the Cart stored in a cookie. When it's time to check out, just read off the cookie.

Title: Customising Session ID's?