问:
How do I format a Microsoft JSON date?
I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:

```<code>/Date(1224043200000)/
</code>```

From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() without any success.

FYI: Here's the solution I came up with using a combination of the answers here:

```<code>function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch",
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}
</code>```

This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

答:
TLDR: You cannot reliably convert that date-only value, send a string instead...

...or at least that is how almost all of these answers should start off.

There is a number of conversion issues that are happening here.

This Is a Date Without Time

Something everybody seems to be missing is how many trailing zeros there are in the question - it almost certainly started out as a date without time:

```<code>/Date(1224043200000)/
</code>```

When executing this from a javascript console as a new Date (the basis of many answers)

```<code>new Date(1224043200000)
</code>```

You get:

The original asker was probably in EST and had a pure date (sql) or a DateTime (not DateTimeOffset) with midnight.

In other words, the intention here is that the time portion is meaningless.  However, if the browser executes this in the same timezone as the server that generated it doesn't matter and most of the answers work.

Bit By Timezone

But, if you execute the code above on a machine with a different timezone (PST for example):

You'll note that we are now a day behind in this other timezone.  This will not be fixed by changing the serializer (which will still include the timezone in the iso format)

The Problem

Date (sql) and DateTime (.net) do not have timezone on them, but as soon as you convert them to something that does (javascript inferred thru json in this case), the default action in .net is to assume the current timezone.

The number that the serialization is creating is milliseconds since Unix epoch or:

```<code>(DateTimeOffset.Parse("10/15/2008 00:00:00Z") - DateTimeOffset.Parse("1/1/1970 00:00:00Z")).TotalMilliseconds;
</code>```

Which is something that new Date() in javascript takes as a parameter.  Epoch is from UTC, so now you've got timezone info in there whether you wanted it or not.

Possible solutions:

It might be safer to create a string property on your serialized object that represents the date ONLY - a string with "10/15/2008" is not likely to confuse anybody else with this mess.  Though even there you have to be careful on the parsing side:
https://stackoverflow.com/a/31732581

However, in the spirit of providing an answer to the question asked, as is:

```<code>function adjustToLocalMidnight(serverMidnight){
  var serverOffset=-240; //injected from model? <-- DateTimeOffset.Now.Offset.TotalMinutes
  var localOffset=-(new Date()).getTimezoneOffset();
  return new Date(date.getTime() + (serverOffset-localOffset) * 60 * 1000)
}

var localMidnightDate = adjustToLocalMidnight(new Date(parseInt(jsonDate.substr(6))));
</code>```

OwnerDisplayName: Mark Struzinski

Title: How do I format a Microsoft JSON date?

Body:
I'm taking my first crack at Ajax with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON data that is returned for Date data types. Basically, I'm getting a string back that looks like this:

/Date(1224043200000)/

From someone totally new to JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() without any success.

FYI: Here's the solution I came up with using a combination of the answers here:

function getMismatch(id) {
  $.getJSON("Main.aspx?Callback=GetMismatch",
    { MismatchId: id },

    function (result) {
      $("#AuthMerchId").text(result.AuthorizationMerchantId);
      $("#SttlMerchId").text(result.SettlementMerchantId);
      $("#CreateDate").text(formatJSONDate(Date(result.AppendDts)));
      $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts)));
      $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts)));
      $("#LastUpdatedBy").text(result.LastUpdateNt);
      $("#ProcessIn").text(result.ProcessIn);
    }
  );

  return false;
}

function formatJSONDate(jsonDate) {
  var newDate = dateFormat(jsonDate, "mm/dd/yyyy");
  return newDate;
}

This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

LastEditorDisplayName: unwind

Body:
TLDR: You cannot reliably convert that date-only value, send a string instead...

...or at least that is how almost all of these answers should start off.

There is a number of conversion issues that are happening here.

This Is a Date Without Time

Something everybody seems to be missing is how many trailing zeros there are in the question - it almost certainly started out as a date without time:

/Date(1224043200000)/

When executing this from a javascript console as a new Date (the basis of many answers)

new Date(1224043200000)

You get:

The original asker was probably in EST and had a pure date (sql) or a DateTime (not DateTimeOffset) with midnight.

In other words, the intention here is that the time portion is meaningless.  However, if the browser executes this in the same timezone as the server that generated it doesn't matter and most of the answers work.

Bit By Timezone

But, if you execute the code above on a machine with a different timezone (PST for example):

You'll note that we are now a day behind in this other timezone.  This will not be fixed by changing the serializer (which will still include the timezone in the iso format)

The Problem

Date (sql) and DateTime (.net) do not have timezone on them, but as soon as you convert them to something that does (javascript inferred thru json in this case), the default action in .net is to assume the current timezone.

The number that the serialization is creating is milliseconds since Unix epoch or:

(DateTimeOffset.Parse("10/15/2008 00:00:00Z") - DateTimeOffset.Parse("1/1/1970 00:00:00Z")).TotalMilliseconds;

Which is something that new Date() in javascript takes as a parameter.  Epoch is from UTC, so now you've got timezone info in there whether you wanted it or not.

Possible solutions:

It might be safer to create a string property on your serialized object that represents the date ONLY - a string with "10/15/2008" is not likely to confuse anybody else with this mess.  Though even there you have to be careful on the parsing side:
https://stackoverflow.com/a/31732581

However, in the spirit of providing an answer to the question asked, as is:

function adjustToLocalMidnight(serverMidnight){
  var serverOffset=-240; //injected from model? <-- DateTimeOffset.Now.Offset.TotalMinutes
  var localOffset=-(new Date()).getTimezoneOffset();
  return new Date(date.getTime() + (serverOffset-localOffset) * 60 * 1000)
}

var localMidnightDate = adjustToLocalMidnight(new Date(parseInt(jsonDate.substr(6))));


来源: stackexchange

问:
why homepage is not reachable after adding spring security
I’m adding spring security to the web site
My goal is to show all images, home.html, and index.html to all users (without logging in).

I’ve allowed all requests for images and home and index pages, but still anonymous users cannot proceed to the home page without logging in

My security config Java

```<code>protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/admin").hasRole("ADMIN")
            .antMatchers("/", "home", "index").permitAll()
            .antMatchers("/styles.css", "/css/**", "/js/**", "/fonts/**", "/images/**").permitAll()
            .anyRequest().hasRole("USER")
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?login_error=1")
            .permitAll()
            .and()
            .logout()
            .logoutSuccessUrl("/")
            .permitAll();
}
</code>```

My index.html page

```<code><!doctype html>
<html lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/extras/spring-security">

    <body>

                    <a href="login" class="btn btn-outline-danger btn-lg">login page </a>
                    <a href="home" class="btn btn-outline-danger btn-lg">home page</a>

    </body>
</html>
</code>```

答:
Have you tried refactoring like this:
.antMatchers("/", "home", "index").permitAll() ->                         .antMatchers("/", "/home", "/index").permitAll() ?

ContentLicense: CC BY-SA 4.0

Body:
I’m adding spring security to the web site
My goal is to show all images, home.html, and index.html to all users (without logging in).

I’ve allowed all requests for images and home and index pages, but still anonymous users cannot proceed to the home page without logging in

My security config Java

protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/admin").hasRole("ADMIN")
            .antMatchers("/", "home", "index").permitAll()
            .antMatchers("/styles.css", "/css/**", "/js/**", "/fonts/**", "/images/**").permitAll()
            .anyRequest().hasRole("USER")
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?login_error=1")
            .permitAll()
            .and()
            .logout()
            .logoutSuccessUrl("/")
            .permitAll();
}

My index.html page

<!doctype html>

                    login page
                    home page


问:
Find duplicate fields in database, and update field in row
Okay, so I have a table which has 3000 rows. Each row is unique, however some fields are duplicated.
I want to update the rows with fields that are duplicated. I'm having a hard time putting this into words, so I'm sorry if I'm getting it all wrong.

```<code>For example, the table looks like this:

+----+--------+--------+-----------+-------+-------+------+--+
| id |  name  | place  |    day    | time1 | time2 | dupe |  |
+----+--------+--------+-----------+-------+-------+------+--+
|  1 | George | Garden | Sunday    | 12:00 | 13:00 |    0 |  |
|  2 | George | House  | Monday    | 15:00 | 18:00 |    0 |  |
|  3 | David  | School | Wednesday | 15:00 | 18:00 |    0 |  |
|  4 | Stan   | Church | Sunday    | 12:00 | 13:00 |    0 |  |
+----+--------+--------+-----------+-------+-------+------+--+
</code>```

I'd like to run a mysql query that checks the table for duplicate names in the name field, and marks the dupe field as 1 if they are a duplicate.

So the dupe fields in row 1 and 2 should be '1' and the rest should be '0'.

Thank you for any help you might be able to provide! I hope I explained it right.

答:
You seem to only care about the name field.  So:

```<code>update t join
       (select name
        from t
        group by name
        having count(*) >= 2
       ) dups
       on t.name = dups.name
    set dups = 1;
</code>```

Body:
Okay, so I have a table which has 3000 rows. Each row is unique, however some fields are duplicated.
I want to update the rows with fields that are duplicated. I'm having a hard time putting this into words, so I'm sorry if I'm getting it all wrong.

For example, the table looks like this:

+----+--------+--------+-----------+-------+-------+------+--+
| id |  name  | place  |    day    | time1 | time2 | dupe |  |
+----+--------+--------+-----------+-------+-------+------+--+
|  1 | George | Garden | Sunday    | 12:00 | 13:00 |    0 |  |
|  2 | George | House  | Monday    | 15:00 | 18:00 |    0 |  |
|  3 | David  | School | Wednesday | 15:00 | 18:00 |    0 |  |
|  4 | Stan   | Church | Sunday    | 12:00 | 13:00 |    0 |  |
+----+--------+--------+-----------+-------+-------+------+--+

I'd like to run a mysql query that checks the table for duplicate names in the name field, and marks the dupe field as 1 if they are a duplicate.

So the dupe fields in row 1 and 2 should be '1' and the rest should be '0'.

Thank you for any help you might be able to provide! I hope I explained it right.

Body:
You seem to only care about the name field.  So:

update t join
       (select name
        from t
        group by name
        having count(*) >= 2
       ) dups
       on t.name = dups.name
    set dups = 1;


答:
You can use EXISTS in a CASE statement:</p>

```<code>select
  t.*,
  case
    when exists (
      select 1 from tablename
      where id <> t.id and name = t.name
    ) then 1
    else 0
  end dupe
from tablename t
</code>```

Title: Find duplicate fields in database, and update field in row

Body:
You can use EXISTS in a CASE statement:

select
  t.*,
  case
    when exists (
      select 1 from tablename
      where id <> t.id and name = t.name
    ) then 1
    else 0
  end dupe
from tablename t


问:
writing junit test to cover cross version serialization
does any of you have any info/idea on how can I test my application for cross version compatibility. I am testing these object's serialization in current "HEAD" version. but I need to wait for my integration testing to see if I broke anything cross version.

I am guessing I will need to store the objects serialized from last released version somewhere on my disk, I can imagine how this kind of system might work but I wonder if someone already did it.

答:
While looking for ways to unit test serialization, I stumbled on this question, and on interesting blog posts on the same subject. I'll post the links here in case others find it useful...

Here is Bob Lee's (Google Guice creator) take on unit testing serialization evolution:

http://blog.crazybob.org/2006/01/unit-testing-serialization-evolution.html

http://blog.crazybob.org/2006/01/unit-testing-serialization-evolution_13.html

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Why using a reference as an iterator
I was learning about the emplace() of std::vector and stumble upon this code:

```<code>// vector::emplace
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30};

  auto it = myvector.emplace ( myvector.begin()+1, 100 );
  myvector.emplace ( it, 200 );
  myvector.emplace ( myvector.end(), 300 );

  std::cout << "myvector contains:";
  for (auto& x: myvector)
    std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}
</code>```

I am wondering why in the for loop they use a reference auto& x instead of a simple copy, I tried without the & and it worked the same, is this a security to avoid a copy or a a performance trick ?

答:
It's as simple as you said, it would be a copy. So it's indeed a performance trick, but for an int it won't be any faster, it might be even be slower. But had you had a std::vector<std::string> with million elements then it would make a big difference. You can try it yourself.

But, it's needed if you want to modify the contents of the iterated container. Without the reference, you would be changing the copy, not the element inside the container. The difference would be seen here:

```<code>std::vector<int> numbers1 = {1,2,3,4};
std::vector<int> numbers2 = {1,2,3,4};
for(auto& x: numbers1) ++x;
for(auto x: numbers2) ++x;
assert(numbers1!=numbers2); // True
</code>```

Also I would recommend using auto&& instead of auto& because it will work better with temporaries, see e.g. this answer.

Title: Why using a reference as an iterator

Body:
I was learning about the emplace() of std::vector and stumble upon this code:

// vector::emplace
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector = {10,20,30};

  auto it = myvector.emplace ( myvector.begin()+1, 100 );
  myvector.emplace ( it, 200 );
  myvector.emplace ( myvector.end(), 300 );

  std::cout << "myvector contains:";
  for (auto& x: myvector)
    std::cout << ' ' << x;
  std::cout << '\n';

  return 0;
}

I am wondering why in the for loop they use a reference auto& x instead of a simple copy, I tried without the & and it worked the same, is this a security to avoid a copy or a a performance trick ?

Body:
It's as simple as you said, it would be a copy. So it's indeed a performance trick, but for an int it won't be any faster, it might be even be slower. But had you had a std::vector<std::string> with million elements then it would make a big difference. You can try it yourself.

But, it's needed if you want to modify the contents of the iterated container. Without the reference, you would be changing the copy, not the element inside the container. The difference would be seen here:

std::vector<int> numbers1 = {1,2,3,4};
std::vector<int> numbers2 = {1,2,3,4};
for(auto& x: numbers1) ++x;
for(auto x: numbers2) ++x;
assert(numbers1!=numbers2); // True

Also I would recommend using auto&& instead of auto& because it will work better with temporaries, see e.g. this answer.


问:
Error when aggregating due to conversion from varchar to bigint
Situation:

I want to aggregate a value from a table but i get the following error :

Error converting data type varchar to big int.

I've been reading countless of different solutions online but they don't seem to solve it.

Current query;
So based on the error message, i simply added the CAST function but it still doesnt work.

```<code>SELECT
    base.target_date AS target_date
  , base.game_id AS game_id
  , base.device AS device
  , ISNULL(CAST(SUM(use_point.point) AS bigint),0) AS result
FROM
    cte AS base

LEFT JOIN cte2 AS use_point
    ON base.target_date = use_point.target_date
    AND base.game_id = use_point.device
    AND base.device = use_point.device

GROUP BY
    base.target_date
  , base.device
  , base.game_id
WITH ROLLUP
GO
</code>```

答:
I'm presuming that use_point.point is a VARCHAR, in which case simply change where you put your CAST statement:

```<code>, ISNULL(SUM(CAST(use_point.point AS bigint)), 0) AS result
</code>```

Note that the CAST now takes place before the SUM.

Body:
Situation:

I want to aggregate a value from a table but i get the following error :

Error converting data type varchar to big int.

I've been reading countless of different solutions online but they don't seem to solve it.

Current query;
So based on the error message, i simply added the CAST function but it still doesnt work.

SELECT
    base.target_date AS target_date
  , base.game_id AS game_id
  , base.device AS device
  , ISNULL(CAST(SUM(use_point.point) AS bigint),0) AS result
FROM
    cte AS base

LEFT JOIN cte2 AS use_point
    ON base.target_date = use_point.target_date
    AND base.game_id = use_point.device
    AND base.device = use_point.device

GROUP BY
    base.target_date
  , base.device
  , base.game_id
WITH ROLLUP
GO

Body:
I'm presuming that use_point.point is a VARCHAR, in which case simply change where you put your CAST statement:

, ISNULL(SUM(CAST(use_point.point AS bigint)), 0) AS result

Note that the CAST now takes place before the SUM.


问:
mocking store.getState()
I want to assert that when a function gets my redux state value using store.getState(), it does various things based on the conditions of that state. How am I able to assert / mock what I want the state value to be for certain tests using the store.getState() method? Thanks.

sampleFunction.js:

```<code>import { store } from './reduxStore';

const sampleFunction = () => {
  const state = store.getState();
  let result = false;
  if (state.foo.isGood) {
    result = true;
  }

  return result;
};

export default sampleFunction;
</code>```

sampleFunction.test.js:

```<code>import sampleFunction from './sampleFunction.js';

test('sampleFunction returns true', () => {
  // assert that state.foo.isGood = true
  expect(sampleFunction()).toBeTruthy();
});
</code>```

答:
What you can do to mock your store is</p>

```<code>import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';

jest.mock('./reduxStore')

const mockState = {
  foo: { isGood: true }
}

// in this point store.getState is going to be mocked
store.getState = () => mockState

test('sampleFunction returns true', () => {
  // assert that state.foo.isGood = true
  expect(sampleFunction()).toBeTruthy();
});
</code>```

Title: mocking store.getState()

Body:
I want to assert that when a function gets my redux state value using store.getState(), it does various things based on the conditions of that state. How am I able to assert / mock what I want the state value to be for certain tests using the store.getState() method? Thanks.

sampleFunction.js:

import { store } from './reduxStore';

const sampleFunction = () => {
  const state = store.getState();
  let result = false;
  if (state.foo.isGood) {
    result = true;
  }

  return result;
};

export default sampleFunction;

sampleFunction.test.js:

import sampleFunction from './sampleFunction.js';

test('sampleFunction returns true', () => {
  // assert that state.foo.isGood = true
  expect(sampleFunction()).toBeTruthy();
});

Body:
What you can do to mock your store is

import { store } from './reduxStore';
import sampleFunction from './sampleFunction.js';

jest.mock('./reduxStore')

const mockState = {
  foo: { isGood: true }
}

// in this point store.getState is going to be mocked
store.getState = () => mockState

test('sampleFunction returns true', () => {
  // assert that state.foo.isGood = true
  expect(sampleFunction()).toBeTruthy();
});


问:
Does the function()-function in R "not" require curly brackets?
I recently encountered this example in my R tutorial:

```<code>sapply(list(runif (10), runif (10)),
   function(x) c(min = min(x), mean = mean(x), max = max(x))
</code>```

I was under the impression that in the function()-function you first had to list your arguments within parenthesis and then the actions performed by the function inside curly brackets.

In this example there are "no" curly brackets and the code seems to function anyway, how can this be?

答:
It is a single statement and for that there is no need for any brackets

```<code>sapply(0:5, function(x) x  + 5)
</code>```

But, if the function demands multiple statements, each statement can be separated within the curly brackets

```<code>sapply(0:5, function(x) {
             x <- sequence(x)
             x1 <- x[x > 2]
             c(mean = mean(x1), min = min(x1))
             })
</code>```

As @qdread mentioned in the comments, a good practice would be to include the curlies though there might be a slight efficiency dip

```<code>library(microbenchmark)
microbenchmark(nocurly = sapply(0:1e6, function(x) x + 5),
      curly = sapply(0:1e6, function(x) {x + 5}))
#Unit: milliseconds
#    expr      min       lq     mean   median       uq      max neval
# nocurly 666.2539 922.0929 928.6206 942.9065 966.8318 1113.828   100
#   curly 710.8450 925.7917 947.7641 955.2041 973.8009 1081.597   100
</code>```

Body:
I recently encountered this example in my R tutorial:

sapply(list(runif (10), runif (10)),
   function(x) c(min = min(x), mean = mean(x), max = max(x))

I was under the impression that in the function()-function you first had to list your arguments within parenthesis and then the actions performed by the function inside curly brackets.

In this example there are "no" curly brackets and the code seems to function anyway, how can this be?

Body:
It is a single statement and for that there is no need for any brackets

sapply(0:5, function(x) x  + 5)

But, if the function demands multiple statements, each statement can be separated within the curly brackets

sapply(0:5, function(x) {
             x <- sequence(x)
             x1 <- x[x > 2]
             c(mean = mean(x1), min = min(x1))
             })

As @qdread mentioned in the comments, a good practice would be to include the curlies though there might be a slight efficiency dip

library(microbenchmark)
microbenchmark(nocurly = sapply(0:1e6, function(x) x + 5),
      curly = sapply(0:1e6, function(x) {x + 5}))
#Unit: milliseconds
#    expr      min       lq     mean   median       uq      max neval
# nocurly 666.2539 922.0929 928.6206 942.9065 966.8318 1113.828   100
#   curly 710.8450 925.7917 947.7641 955.2041 973.8009 1081.597   100


问:
What's a good pattern to create DbContext when dynamic data determines connection string
I get a data set from another web api. It may contain multiple records from different clients. I have to transform these data and write them to the client's database. Each client has their own database. The schema of the client databases are exactly the same.

I created a DbContext factory that creates a new instance of DbContext based on the client the app is currently working on.

```<code>public ClientDbContext CreateClientDbContext(string clientNumber)
{
      var optionsBuilder = new DbContextOptionsBuilder<ClientDbContext>();
      var clientConnection = string.Format(_configuration.GetConnectionString("clientConnection"), clientNumber);
      optionsBuilder.UseSqlServer(clientConnection);

      clientDbContext clientDbContext = new ClientDbContext(optionsBuilder.Options);

      return clientDbContext;
}
</code>```

I use the factory this way:

```<code>foreach (var case in caseList)
{
    var clientDbContext = await _clientDbContextFactory.CreateClientDbContext(case.ClientNumber);
    _clientRepository = new ClientRepository(clientDbContext);
    var updatedCase = /// transform case here
    await _clientRepository.CreateCases(updatedCase);
}
</code>```

Is there an optimal why of doing this?
It's possible that several rows of data will have the same client, so I would like to reuse the same ClientDbContext.

答:
Process the cases in batches, as this allows you to reuse a client connection before moving on to the next one. Something like this:

```<code>var batches = caseList.GroupBy(x => x.ClientNumber);

foreach (var batch in batches)
{
    var clientDbContext = await _clientDbContextFactory.CreateClientDbContext(batch.ClientNumber);
    _clientRepository = new ClientRepository(clientDbContext);

    foreach (var item in batch)
    {
        var updatedCase = /// transform case here
        await _clientRepository.CreateCases(updatedCase);
    }
}
</code>```

You may also benefit from setting off a bunch of tasks for a batch, too, but you should profile that to see if you gain anything from it. That could look something like:

```<code>var tasksInBatch = new List<Task>();
foreach (var item in batch)
{
    var updatedCase = /// transform case here
    tasksInBatch.Add(_clientRepository.CreateCases(updatedCase));
}

await Task.WhenAll(tasksInBatch);
</code>```

Body:
I get a data set from another web api. It may contain multiple records from different clients. I have to transform these data and write them to the client's database. Each client has their own database. The schema of the client databases are exactly the same.

I created a DbContext factory that creates a new instance of DbContext based on the client the app is currently working on.

public ClientDbContext CreateClientDbContext(string clientNumber)
{
      var optionsBuilder = new DbContextOptionsBuilder<ClientDbContext>();
      var clientConnection = string.Format(_configuration.GetConnectionString("clientConnection"), clientNumber);
      optionsBuilder.UseSqlServer(clientConnection);

      clientDbContext clientDbContext = new ClientDbContext(optionsBuilder.Options);

      return clientDbContext;
}

I use the factory this way:

foreach (var case in caseList)
{
    var clientDbContext = await _clientDbContextFactory.CreateClientDbContext(case.ClientNumber);
    _clientRepository = new ClientRepository(clientDbContext);
    var updatedCase = /// transform case here
    await _clientRepository.CreateCases(updatedCase);
}

Is there an optimal why of doing this?
It's possible that several rows of data will have the same client, so I would like to reuse the same ClientDbContext.

Body:
Process the cases in batches, as this allows you to reuse a client connection before moving on to the next one. Something like this:

var batches = caseList.GroupBy(x => x.ClientNumber);

foreach (var batch in batches)
{
    var clientDbContext = await _clientDbContextFactory.CreateClientDbContext(batch.ClientNumber);
    _clientRepository = new ClientRepository(clientDbContext);

    foreach (var item in batch)
    {
        var updatedCase = /// transform case here
        await _clientRepository.CreateCases(updatedCase);
    }
}

You may also benefit from setting off a bunch of tasks for a batch, too, but you should profile that to see if you gain anything from it. That could look something like:

var tasksInBatch = new List<Task>();
foreach (var item in batch)
{
    var updatedCase = /// transform case here
    tasksInBatch.Add(_clientRepository.CreateCases(updatedCase));
}

await Task.WhenAll(tasksInBatch);


问:
Trying to create tree-view of google drive folders
Many thanks for the comments and response. That code was a little too advanced for me and I ended up finding a very inelegant solution that I used because I ran out of time. I was able to get the code to list Folder and first level of subFolders with links, but I have not yet been able to get it to iterate through all levels of folders, mostly because I just need to back up and learn a lot of the basics. I was also able to get all folders to list using some code I found to create a tree, but I couldn't get it to format in a way that you could actually see the structure, or add links. I'm going to continue to try, and will post if I sort it out. Here is what I used, which was fine for our purposes because our shared drive is fairly limited.

For reference, this was the code I used to start with:
https://superuser.com/questions/1095578/list-of-subfolder-names-and-file-links-in-google-sheets-script

```<code>function listFolders(foldername) {
var ss = SpreadsheetApp.openById(ID);
var sheet = ss.getSheetByName("sheet name");
sheet.appendRow("Parent Folder", "Name", "Link" ]);

//change the folder ID below to reflect your folder's ID (look in the
URL when you're in your folder)

var folders = DriveApp.getFolderById(ID);
var contents = folders.getFolders();
var cnt = 0;
var folderD;

while (contents.hasNext()) {
var folderD = contents.next();
cnt++;

data = [
        folders.getName(),
        folderD.getName(),
        folderD.getUrl(),
];

sheet.appendRow(data);
};
};
</code>```

Original Post:
I am a beginner using script in google sheets and I am trying to create a list of folders in a google drive with many subfolders. Ideally it would be a tree form but I'd settle for a list at this point. I don't need to list all the files, just the folders. I have been trying to get the code below to work but it keeps hanging up at calling up the spreadsheet. Can anyone help?

I have tried calling up both the folders and the spreadsheet by both name and ID but it always tells me it can't execute the getactivespreadsheet command. I have also tried to modify the code referred to in another another question but I can't get that to work either: https://ctrlq.org/code/19923-google-drive-files-list

```<code>function generateFolderIndex(myfoldername) {
var folder = DriveApp.getFolderById('0B8vOJQUb-IIVTHdudlZSVkdtdE0');
var subFolders = folder.getFolders();
var childFolders = subFolders
var ss = SpreadsheetApp.getActiveSpreadsheet('1Trv9OtJFnD4AdSHrZKFfsSu6JMV9f78H6wwZNhF2_M4');
var sheet = ss.getSheetByName('Directory');

sheet.clear(directory);
sheet.appendRow([name, link]);

while (subFolders.hasNext())
{
var childFolder = childFolders.next();

var foldername = childFolder.getname();
var name = childFolder.getName()
var link = childFolder.getUrl()
var date = childFolder.getDateCreated()

data = [name, link]
sheet.appendRow(data);

}
};
</code>```

I am trying to get a sheet that lists folders and subfolders with URL links. I am currently receiving the following error message:
[19-05-31 15:32:20:911 EDT] Execution failed: Cannot find method getActiveSpreadsheet(string). (line 5, file "Code") [0.432 seconds total runtime]

答:
SpreadsheetApp.getActiveSpreadsheet() doesn't have any parameters.

However

SpreadsheetApp.openById('ssid') does require and id.  I think perhaps you meant to be using openById();

openById

getActiveSpreadsheet

This is a script that I'm currently working on but it generates a list of Spreadsheets and you can exclude folders by id and files by id.

```<code>function getAllSpreadsheets() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('FilesAndFolders');
  if(sh.getLastRow()>0) {
    sh.getRange(1,1,sh.getLastRow(),2).clear().clearDataValidations();
  }
  getFnF();
  SpreadsheetApp.getUi().alert('Process Complete')
}

var level=0;
function getFnF(folder) {
  var folder= folder || DriveApp.getRootFolder();
  //var folder=DriveApp.getRootFolder();
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('FilesAndFolders');
  var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS)
  while(files.hasNext()) {
    var file=files.next();
    if(isExcluded(file.getId(),'file')){continue;}
    var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
    firg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
    firg.offset(0,1).insertCheckboxes('Exclude','Include');
  }
  var subfolders=folder.getFolders()
  while(subfolders.hasNext()) {
    var subfolder=subfolders.next();
    if(isExcluded(subfolder.getId(),'folder')){continue;}
    var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
    forg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
    //forg.offset(0,1).insertCheckboxes('Exclude','Include');
    //level++;
    getFnF(subfolder);
  }
  //level--;
}

function isExcluded(id,type) {//type: file or folder
  var type=type||'Missing Input';
  var xFldrIdA=['Excluded folder ids'];
  var xFileIdA=['Excluded file ids'];
  var type=type.toLowerCase();
  switch(type) {
    case 'file':
      return xFileIdA.indexOf(id)>-1;
      break;
    case 'folder':
      return xFldrIdA.indexOf(id)>-1;
      break;
    default:
      throw(Utilities.formatString('Error: Invalid Type: %s in isExcluded.',type));
      return true;//assume excluded
      break;
  }
}
</code>```

Your welcome to use it, perhaps it will help.

Body:
Many thanks for the comments and response. That code was a little too advanced for me and I ended up finding a very inelegant solution that I used because I ran out of time. I was able to get the code to list Folder and first level of subFolders with links, but I have not yet been able to get it to iterate through all levels of folders, mostly because I just need to back up and learn a lot of the basics. I was also able to get all folders to list using some code I found to create a tree, but I couldn't get it to format in a way that you could actually see the structure, or add links. I'm going to continue to try, and will post if I sort it out. Here is what I used, which was fine for our purposes because our shared drive is fairly limited.

For reference, this was the code I used to start with:
https://superuser.com/questions/1095578/list-of-subfolder-names-and-file-links-in-google-sheets-script

function listFolders(foldername) {
var ss = SpreadsheetApp.openById(ID);
var sheet = ss.getSheetByName("sheet name");
sheet.appendRow("Parent Folder", "Name", "Link" ]);

//change the folder ID below to reflect your folder's ID (look in the
URL when you're in your folder)

var folders = DriveApp.getFolderById(ID);
var contents = folders.getFolders();
var cnt = 0;
var folderD;

while (contents.hasNext()) {
var folderD = contents.next();
cnt++;

data = [
        folders.getName(),
        folderD.getName(),
        folderD.getUrl(),
];

sheet.appendRow(data);
};
};

Original Post:
I am a beginner using script in google sheets and I am trying to create a list of folders in a google drive with many subfolders. Ideally it would be a tree form but I'd settle for a list at this point. I don't need to list all the files, just the folders. I have been trying to get the code below to work but it keeps hanging up at calling up the spreadsheet. Can anyone help?

I have tried calling up both the folders and the spreadsheet by both name and ID but it always tells me it can't execute the getactivespreadsheet command. I have also tried to modify the code referred to in another another question but I can't get that to work either: https://ctrlq.org/code/19923-google-drive-files-list

function generateFolderIndex(myfoldername) {
var folder = DriveApp.getFolderById('0B8vOJQUb-IIVTHdudlZSVkdtdE0');
var subFolders = folder.getFolders();
var childFolders = subFolders
var ss = SpreadsheetApp.getActiveSpreadsheet('1Trv9OtJFnD4AdSHrZKFfsSu6JMV9f78H6wwZNhF2_M4');
var sheet = ss.getSheetByName('Directory');

sheet.clear(directory);
sheet.appendRow([name, link]);

while (subFolders.hasNext())
{
var childFolder = childFolders.next();

var foldername = childFolder.getname();
var name = childFolder.getName()
var link = childFolder.getUrl()
var date = childFolder.getDateCreated()

data = [name, link]
sheet.appendRow(data);

}
};

I am trying to get a sheet that lists folders and subfolders with URL links. I am currently receiving the following error message:
[19-05-31 15:32:20:911 EDT] Execution failed: Cannot find method getActiveSpreadsheet(string). (line 5, file "Code") [0.432 seconds total runtime]

Body:
SpreadsheetApp.getActiveSpreadsheet() doesn't have any parameters.

However

SpreadsheetApp.openById('ssid') does require and id.  I think perhaps you meant to be using openById();

openById

getActiveSpreadsheet

This is a script that I'm currently working on but it generates a list of Spreadsheets and you can exclude folders by id and files by id.

function getAllSpreadsheets() {
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('FilesAndFolders');
  if(sh.getLastRow()>0) {
    sh.getRange(1,1,sh.getLastRow(),2).clear().clearDataValidations();
  }
  getFnF();
  SpreadsheetApp.getUi().alert('Process Complete')
}

var level=0;
function getFnF(folder) {
  var folder= folder || DriveApp.getRootFolder();
  //var folder=DriveApp.getRootFolder();
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('FilesAndFolders');
  var files=folder.getFilesByType(MimeType.GOOGLE_SHEETS)
  while(files.hasNext()) {
    var file=files.next();
    if(isExcluded(file.getId(),'file')){continue;}
    var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
    firg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',file.getUrl(),'FILE: ' + file.getName()));
    firg.offset(0,1).insertCheckboxes('Exclude','Include');
  }
  var subfolders=folder.getFolders()
  while(subfolders.hasNext()) {
    var subfolder=subfolders.next();
    if(isExcluded(subfolder.getId(),'folder')){continue;}
    var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
    forg.setValue(Utilities.formatString('=HYPERLINK("%s","%s")',subfolder.getUrl(),'FOLDER: ' + subfolder.getName()));
    //forg.offset(0,1).insertCheckboxes('Exclude','Include');
    //level++;
    getFnF(subfolder);
  }
  //level--;
}

function isExcluded(id,type) {//type: file or folder
  var type=type||'Missing Input';
  var xFldrIdA=['Excluded folder ids'];
  var xFileIdA=['Excluded file ids'];
  var type=type.toLowerCase();
  switch(type) {
    case 'file':
      return xFileIdA.indexOf(id)>-1;
      break;
    case 'folder':
      return xFldrIdA.indexOf(id)>-1;
      break;
    default:
      throw(Utilities.formatString('Error: Invalid Type: %s in isExcluded.',type));
      return true;//assume excluded
      break;
  }
}

Your welcome to use it, perhaps it will help.


问:
How to find AMI ID of CentOS 7 image in AWS Marketplace?
I have been launching EC2 instances by logging in to the AWS site, hitting the "Launch" button and following the proscribed steps. Now I'd like to launch instance from an Ansible script, and to do this I (think I) need the AMI ID of the image I wish to launch.

The problem is that I am launching an image from the "Marketplace", and I cannot find the AMI ID. In particular I'm using the Centos 7 image. This is easy to find in the web interface, just go to the marketplace and search for "centos", the image I want is the first one found, but the information provided about the image doesn't seem to include the AMI ID that I need to launch it from a script. The workaround is to manually launch an image, and then when inspecting the running image, the AMI ID is given. But is there an easier way to find it?

答:
I used the other answers here for a good way to test AMI lookups in Terraform.

Using...

```<code>aws ec2 describe-images \
    --owners aws-marketplace \
    --filters '[
        {"Name": "name",                "Values": ["CentOS Linux 7*"]},
        {"Name": "virtualization-type", "Values": ["hvm"]},
        {"Name": "architecture",        "Values": ["x86_64"]},
        {"Name": "image-type",          "Values": ["machine"]}
    ]' \
    --query 'sort_by(Images, &CreationDate)[-1]' \
    --region us-east-1 \
    --output json
</code>```

...gave me the chance to trial and error my lookup of

```<code>data "aws_ami" "centos" {
  most_recent = true
  owners      = ["aws-marketplace"]

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  filter {
    name   = "architecture"
    values = ["x86_64"]
  }

  filter {
    name   = "image-type"
    values = ["machine"]
  }

  filter {
    name   = "name"
    values = ["CentOS Linux 7*"]
  }
}

resource "aws_launch_configuration" "launch_configuration" {
  name_prefix = "${var.name}-"

  image_id = "${data.aws_ami.centos.image_id}"
  instance_type        = "t2.nano"
  iam_instance_profile = "${aws_iam_instance_profile.instance_profile.name}"
  security_groups      = ["${aws_security_group.lc_security_group.id}"]

  user_data = "${data.template_file.user_data.rendered}"

  lifecycle {
    create_before_destroy = true
  }
}
</code>```

Body:
I used the other answers here for a good way to test AMI lookups in Terraform.

Using...

aws ec2 describe-images \
    --owners aws-marketplace \
    --filters '[
        {"Name": "name",                "Values": ["CentOS Linux 7*"]},
        {"Name": "virtualization-type", "Values": ["hvm"]},
        {"Name": "architecture",        "Values": ["x86_64"]},
        {"Name": "image-type",          "Values": ["machine"]}
    ]' \
    --query 'sort_by(Images, &CreationDate)[-1]' \
    --region us-east-1 \
    --output json

...gave me the chance to trial and error my lookup of

data "aws_ami" "centos" {
  most_recent = true
  owners      = ["aws-marketplace"]

  filter {
    name   = "virtualization-type"
    values = ["hvm"]
  }

  filter {
    name   = "architecture"
    values = ["x86_64"]
  }

  filter {
    name   = "image-type"
    values = ["machine"]
  }

  filter {
    name   = "name"
    values = ["CentOS Linux 7*"]
  }
}

resource "aws_launch_configuration" "launch_configuration" {
  name_prefix = "${var.name}-"

  image_id = "${data.aws_ami.centos.image_id}"
  instance_type        = "t2.nano"
  iam_instance_profile = "${aws_iam_instance_profile.instance_profile.name}"
  security_groups      = ["${aws_security_group.lc_security_group.id}"]

  user_data = "${data.template_file.user_data.rendered}"

  lifecycle {
    create_before_destroy = true
  }
}


答:
Use TRY_CAST() instead.  And it needs to be an argument to the SUM():

```<code>SELECT base.target_date, base.game_id, base.device,
       COALESCE(SUM(TRY_CAST(use_point.point as bigint)), 0) as result
FROM . . .
</code>```

Note that your column aliases are redundant, because you are assigning the default aliases.

You should also fix the data.  Don't store numeric values as strings.  To find the bad data, you can use:

```<code>select points
from use_points
where try_convert(points as bigint) is null and
      points is not null;
</code>```

Title: Error when aggregating due to conversion from varchar to bigint

Body:
Use TRY_CAST() instead.  And it needs to be an argument to the SUM():

SELECT base.target_date, base.game_id, base.device,
       COALESCE(SUM(TRY_CAST(use_point.point as bigint)), 0) as result
FROM . . .

Note that your column aliases are redundant, because you are assigning the default aliases.

You should also fix the data.  Don't store numeric values as strings.  To find the bad data, you can use:

select points
from use_points
where try_convert(points as bigint) is null and
      points is not null;


问:
How do i route external API URL + credentials into my localhost URL using visual studio WebAPI project?
I currently only have the External API credentials as a result access token in Postman but cannot implement the URL and credentials into c# code using ASP .NET Web API which comes with sample code in the controller but currently have nothing inside because I don't know how to redirect the external url:https://api.elliemae.com/oauth2/v1/token
towards my localhost URL

postman result

Currently i only have created my model class assuming I will need it.
Class Name: Credentials.cs

```<code> using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace APICredential.Models
{
    public class Credentials
    {
        public string grant_type { get; set; } = "password";
        public string username { get; set; } = "admin@encompass:BE11200822";
        public string password { get; set; } = "Sh**********";
        public string client_id {get;set;} = "gpq4sdh";
        public string client_secret { get; set; } = "dcZ42Ps0lyU0XRgpDyg0yXxxXVm9@A5Z4ICK3NUN&DgzR7G2tCOW6VC#HVoZPBwU";
        public string scope { get; set; } = "lp";

    }
}
</code>```

Controller:

```<code>using APICredential.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace APICredential.Controllers
{
    [RoutePrefix("api")]
    public class ValuesController : ApiController
    {

        [HttpPost, Route("post")]
        public async Task<string> Post([FromBody]Credentials cred)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");

                HttpRequestMessage request = new HttpRequestMessage
                (HttpMethod.Post, "v1/token")
                {
                    Content = new StringContent(new JavaScriptSerializer().Serialize(cred), Encoding.UTF8, "application/json")
                };

                HttpResponseMessage response = await client.SendAsync(request);

                //for now, see what response gets you and adjust your code to return the object you need, if the api is returning a serialized json string.. then we can return a string here... like so

                string result = await response.Content.ReadAsStringAsync();

                return result;
            }
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }
</code>```

答:
you're going to need to create a dto that has similar properties to the stuff you're sending to this api end point. and also a model to map the data that's being returned

```<code>public class Credentials
{
    public string grant_type { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string client_id {get;set;}
    public string client_secret { get; set; }
    public string scope { get; set; }
}
</code>```

then you're going to instantiate it and start assigning the values before sending it off

this is going to go in your api controller method

```<code>[RoutePrefix("api")]
public class ValuesController : ApiController
{

    // POST api/values
    [HttpPost, Route("values")]
    public async Task<string> Post()
    {
        Credentials cred = new Credentials()
        {
            grant_type = "password",
            username = "admin@encompass:BE11200822",
            password  = "Shmmarch18",
            client_id = "gpq4sdh",
            client_secret = "dcZ42Ps0lyU0XRgpDyg0yXxxXVm9@A5Z4ICK3NUN&DgzR7G2tCOW6VC#HVoZPBwU",
            scope = "lp"
        };

        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");

                HttpRequestMessage request = new HttpRequestMessage
                (HttpMethod.Post, "v1/token")
                {
                    Content = new StringContent(new JavaScriptSerializer().Serialize(cred), Encoding.UTF8, "application/x-www-form-urlencoded")
                };

                HttpResponseMessage response = await client.SendAsync(request);

                //for now, see what response gets you and adjust your code to return the object you need, if the api is returning a serialized json string.. then we can return a string here... like so

               string result = await response.Content.ReadAsStringAsync();

               return result;
           }
        }
        catch(Exception ex)
        {
             throw new Exception(ex.Message);
        }
    }
}
</code>```

There's a chance you might have to serialize the object that's returning from the API call, if that's the case:

```<code>[RoutePrefix("api")]
public class ValuesController : ApiController
{
    // POST api/values
    [HttpPost, Route("values")]
    public string Post([FromBody]Credentials cred)
    {
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");

            HttpRequestMessage request = new HttpRequestMessage
            (HttpMethod.Post, "v1/token")
            {
                Content = new StringContent(new JavaScriptSerializer().Serialize(cred), Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await client.SendAsync(request);

           string result = new JavaScriptSerializer().Serialize(response.Content);

           return result;
       }
    }
}
</code>```

Nice work! Ok, let's test your API, let's pump your Get Method up and make it an easy one to work with to increase moral hehe

```<code>// GET api/values
[HttpGet, Route("values")]
public string Get(int id)
{
    return "Nice! At least we got this one working, Fay... the Id value you entered is: " + id.ToString();
}
</code>```

Body:
I currently only have the External API credentials as a result access token in Postman but cannot implement the URL and credentials into c# code using ASP .NET Web API which comes with sample code in the controller but currently have nothing inside because I don't know how to redirect the external url:https://api.elliemae.com/oauth2/v1/token
towards my localhost URL

postman result

Currently i only have created my model class assuming I will need it.
Class Name: Credentials.cs

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace APICredential.Models
{
    public class Credentials
    {
        public string grant_type { get; set; } = "password";
        public string username { get; set; } = "admin@encompass:BE11200822";
        public string password { get; set; } = "Sh**********";
        public string client_id {get;set;} = "gpq4sdh";
        public string client_secret { get; set; } = "dcZ42Ps0lyU0XRgpDyg0yXxxXVm9@A5Z4ICK3NUN&DgzR7G2tCOW6VC#HVoZPBwU";
        public string scope { get; set; } = "lp";

    }
}

Controller:

using APICredential.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace APICredential.Controllers
{
    [RoutePrefix("api")]
    public class ValuesController : ApiController
    {

        [HttpPost, Route("post")]
        public async Task<string> Post([FromBody]Credentials cred)
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");

                HttpRequestMessage request = new HttpRequestMessage
                (HttpMethod.Post, "v1/token")
                {
                    Content = new StringContent(new JavaScriptSerializer().Serialize(cred), Encoding.UTF8, "application/json")
                };

                HttpResponseMessage response = await client.SendAsync(request);

                //for now, see what response gets you and adjust your code to return the object you need, if the api is returning a serialized json string.. then we can return a string here... like so

                string result = await response.Content.ReadAsStringAsync();

                return result;
            }
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

Body:
you're going to need to create a dto that has similar properties to the stuff you're sending to this api end point. and also a model to map the data that's being returned

public class Credentials
{
    public string grant_type { get; set; }
    public string username { get; set; }
    public string password { get; set; }
    public string client_id {get;set;}
    public string client_secret { get; set; }
    public string scope { get; set; }
}

then you're going to instantiate it and start assigning the values before sending it off

this is going to go in your api controller method

[RoutePrefix("api")]
public class ValuesController : ApiController
{

    // POST api/values
    [HttpPost, Route("values")]
    public async Task<string> Post()
    {
        Credentials cred = new Credentials()
        {
            grant_type = "password",
            username = "admin@encompass:BE11200822",
            password  = "Shmmarch18",
            client_id = "gpq4sdh",
            client_secret = "dcZ42Ps0lyU0XRgpDyg0yXxxXVm9@A5Z4ICK3NUN&DgzR7G2tCOW6VC#HVoZPBwU",
            scope = "lp"
        };

        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");

                HttpRequestMessage request = new HttpRequestMessage
                (HttpMethod.Post, "v1/token")
                {
                    Content = new StringContent(new JavaScriptSerializer().Serialize(cred), Encoding.UTF8, "application/x-www-form-urlencoded")
                };

                HttpResponseMessage response = await client.SendAsync(request);

                //for now, see what response gets you and adjust your code to return the object you need, if the api is returning a serialized json string.. then we can return a string here... like so

               string result = await response.Content.ReadAsStringAsync();

               return result;
           }
        }
        catch(Exception ex)
        {
             throw new Exception(ex.Message);
        }
    }
}

There's a chance you might have to serialize the object that's returning from the API call, if that's the case:

[RoutePrefix("api")]
public class ValuesController : ApiController
{
    // POST api/values
    [HttpPost, Route("values")]
    public string Post([FromBody]Credentials cred)
    {
        using (HttpClient client = new HttpClient())
        {
            client.BaseAddress = new Uri("https://api.elliemae.com/oauth2/");

            HttpRequestMessage request = new HttpRequestMessage
            (HttpMethod.Post, "v1/token")
            {
                Content = new StringContent(new JavaScriptSerializer().Serialize(cred), Encoding.UTF8, "application/json")
            };

            HttpResponseMessage response = await client.SendAsync(request);

           string result = new JavaScriptSerializer().Serialize(response.Content);

           return result;
       }
    }
}

Nice work! Ok, let's test your API, let's pump your Get Method up and make it an easy one to work with to increase moral hehe

// GET api/values
[HttpGet, Route("values")]
public string Get(int id)
{
    return "Nice! At least we got this one working, Fay... the Id value you entered is: " + id.ToString();
}


问:
How to load other page inside the page in Angular 5
I have 4 pages in the project.

```<code>[
  { path: 'page1', component: Page1Component },
  { path: 'page2', component: Page2Component },
  { path: 'page3', component: Page3Component },
  { path: 'page4', component: Page4Component },
]
</code>```

In page4, I retrieve a URL from the backend which is one of /page1, /page2, /page3. And then I have to embed that page in /page4.

I am currently doing it with iframe but it's not good.

Is there any way to do it using ng-template or something else?

答:
Like this?

```<code>{path : 'profile', component: ProfileComponent ,
            children : [
              {path: '' , component: ProfileBoardComponent },
              {path: 'friends' , component: ProfileFriendsComponent }
            ]},
</code>```

Or you mean this in your html components?

```<code>    <app-menu></app-menu>
    <router-outlet></router-outlet>
</code>```

Whit <app-menu> bein a component

Body:
I have 4 pages in the project.

[
  { path: 'page1', component: Page1Component },
  { path: 'page2', component: Page2Component },
  { path: 'page3', component: Page3Component },
  { path: 'page4', component: Page4Component },
]

In page4, I retrieve a URL from the backend which is one of /page1, /page2, /page3. And then I have to embed that page in /page4.

I am currently doing it with iframe but it's not good.

Is there any way to do it using ng-template or something else?

Body:
Like this?

{path : 'profile', component: ProfileComponent ,
            children : [
              {path: '' , component: ProfileBoardComponent },
              {path: 'friends' , component: ProfileFriendsComponent }
            ]},

Or you mean this in your html components?

    <app-menu></app-menu>
    <router-outlet></router-outlet>

Whit <app-menu> bein a component


问:
Which algorithm and what combination of hyper-parameters will be the best to cluster this data?
I was learning about non-linear clustering algorithms and I came across this 2-D graph. I was wondering which clustering alogirthm and combination of hyper-parameters will cluster this data well.

Just like a human will cluster those 5 spikes. I want my algorithm to do it.
I tried KMeans but it was only clustering horizontly or vertically. I started using GMM but couldn't get the hyper-parameters right for the desired clustering.

答:
If it doesn't work, always try to improve the preprocessing first. Algorithms such as k-means are very sensitive to scaling, so that is something that needs to be chosen carefully.

GMM is clearly your first choice here. It may be worth trying out different tools. R's Mclust is very slow. Sklearn's GMM is sometimes unstable. ELKI is a bit harder to get started with, but its EM gave me the best results usually.

Apart from GMM, it likely is worth trying out correlation clustering. These algorithms assume there is some manifold (e.g., a line) on which a cluster exists. Examples include ORCLUS, LMCLUS, CASH, 4C, ... But in my opinion these mostly work for synthetic toy data.


问:
I want to increase brightness and contrast of images in dynamic way so that the program is applicable for any new images
I have few images where I need to increase or decrease the contrast and brightness of the image in a dynamic way so that it is visible clearly. And the program needs to be dynamic so that it even works for new images also. I also want character should be dark.

I was able to increase brightness and contrast but it is not working properly for each image.

```<code>import cv2

import numpy as np

img = cv2.imread('D:\Bright.png')

image = cv2.GaussianBlur(img, (5, 5), 0)

#image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY)[1]

#kernel = np.ones((2,1),np.uint8)

#dilation = cv2.dilate(img,kernel)

cv2.imshow('test', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

imghsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]

cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

#cv2.imwrite('D:\\112.png',cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

cv2.waitKey(0)

cv2.destroyAllWindows()

#raw_input()
</code>```

I want a program which works fine for every image and words are a little darker so that they are easily visible.

答:
As Tilarion suggested, you could try "Auto Brightness And Contrast" to see if it works well. The theory behind this is explained well here in the solution section. The solution is in C++. I've written a version of it in python which you can directly use, works only on 1 channel at a time for colour images:</p>

```<code>def auto_brightandcontrast(input_img, channel, clip_percent=1):
    histSize=180
    alpha=0
    beta=0
    minGray=0
    maxGray=0
    accumulator=[]

    if(clip_percent==0):
        #min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(hist)
        return input_img

    else:
        hist = cv2.calcHist([input_img],[channel],None,[256],[0, 256])
        accumulator.insert(0,hist[0])

        for i in range(1,histSize):
            accumulator.insert(i,accumulator[i-1]+hist[i])

        maxx=accumulator[histSize-1]
        minGray=0

        clip_percent=clip_percent*(maxx/100.0)
        clip_percent=clip_percent/2.0

        while(accumulator[minGray]<clip_percent[0]):
            minGray=minGray+1

        maxGray=histSize-1
        while(accumulator[maxGray]>=(maxx-clip_percent[0])):
            maxGray=maxGray-1

        inputRange=maxGray-minGray

        alpha=(histSize-1)/inputRange
        beta=-minGray*alpha

        out_img=input_img.copy()

        cv2.convertScaleAbs(input_img,out_img,alpha,beta)

        return out_img
</code>```

Body:
I have few images where I need to increase or decrease the contrast and brightness of the image in a dynamic way so that it is visible clearly. And the program needs to be dynamic so that it even works for new images also. I also want character should be dark.

I was able to increase brightness and contrast but it is not working properly for each image.

import cv2

import numpy as np

img = cv2.imread('D:\Bright.png')

image = cv2.GaussianBlur(img, (5, 5), 0)

#image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY)[1]

#kernel = np.ones((2,1),np.uint8)

#dilation = cv2.dilate(img,kernel)

cv2.imshow('test', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

imghsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

imghsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in imghsv[:,:,2]]

cv2.imshow('contrast', cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

#cv2.imwrite('D:\\112.png',cv2.cvtColor(imghsv, cv2.COLOR_HSV2BGR))

cv2.waitKey(0)

cv2.destroyAllWindows()

#raw_input()

I want a program which works fine for every image and words are a little darker so that they are easily visible.

Body:
As Tilarion suggested, you could try "Auto Brightness And Contrast" to see if it works well. The theory behind this is explained well here in the solution section. The solution is in C++. I've written a version of it in python which you can directly use, works only on 1 channel at a time for colour images:

def auto_brightandcontrast(input_img, channel, clip_percent=1):
    histSize=180
    alpha=0
    beta=0
    minGray=0
    maxGray=0
    accumulator=[]

    if(clip_percent==0):
        #min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(hist)
        return input_img

    else:
        hist = cv2.calcHist([input_img],[channel],None,[256],[0, 256])
        accumulator.insert(0,hist[0])

        for i in range(1,histSize):
            accumulator.insert(i,accumulator[i-1]+hist[i])

        maxx=accumulator[histSize-1]
        minGray=0

        clip_percent=clip_percent*(maxx/100.0)
        clip_percent=clip_percent/2.0

        while(accumulator[minGray]<clip_percent[0]):
            minGray=minGray+1

        maxGray=histSize-1
        while(accumulator[maxGray]>=(maxx-clip_percent[0])):
            maxGray=maxGray-1

        inputRange=maxGray-minGray

        alpha=(histSize-1)/inputRange
        beta=-minGray*alpha

        out_img=input_img.copy()

        cv2.convertScaleAbs(input_img,out_img,alpha,beta)

        return out_img


问:
jqTransformReset() for the jqtransform form (Reset Button)
Does anyone have a complete code example for the jqTransformReset() for the jqtransform form? My ultimate goal is to add a reset button to the form and reset all form fields (especially checkboxes which I can't get to reset). Thanks in advance!</p>

答:
whenever I call document.form.reset() I also call

```<code>$(".jqTransformCheckbox").each(function(){ if($(this).hasClass('jqTransformChecked')) $(this).removeClass('jqTransformChecked');});
</code>```

seems to work fine.

Body:
whenever I call document.form.reset() I also call

$(".jqTransformCheckbox").each(function(){ if($(this).hasClass('jqTransformChecked')) $(this).removeClass('jqTransformChecked');});

seems to work fine.


问:
Caveats while checking dtype in pandas DataFrame
Guided by this answer I started to build up pipe for processing columns of dataframe based on its dtype. But after getting some unexpected output and some debugging i ended up with test dataframe and test dtype checking:

# Creating test dataframe
test = pd.DataFrame({'bool' :[False, True], 'int':[-1,2],'float': [-2.5, 3.4],
                     'compl':np.array([1-1j, 5]),
                     'dt'   :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
                     'td'   :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
                              pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
                     'prd'  :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
                     'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
                     'str'  :['s1', 's2'],
                     'cat'  :[1, -1],
                     'obj'  :[[1,2,3], [5435,35,-52,14]]
                    })
test['cat'] = test['cat'].astype('category')
test
test.dtypes

# Testing types
types = list(test.columns)
df_types = pd.DataFrame(np.zeros((len(types),len(types)), dtype=bool),
                        index = ['is_'+el for el in types],
                        columns = types)
for col in test.columns:
    df_types.at['is_bool', col] = pd.api.types.is_bool_dtype(test[col])
    df_types.at['is_int' , col] = pd.api.types.is_integer_dtype(test[col])
    df_types.at['is_float',col] = pd.api.types.is_float_dtype(test[col])
    df_types.at['is_compl',col] = pd.api.types.is_complex_dtype(test[col])
    df_types.at['is_dt'  , col] = pd.api.types.is_datetime64_dtype(test[col])
    df_types.at['is_td'  , col] = pd.api.types.is_timedelta64_dtype(test[col])
    df_types.at['is_prd' , col] = pd.api.types.is_period_dtype(test[col])
    df_types.at['is_intrv',col] = pd.api.types.is_interval_dtype(test[col])
    df_types.at['is_str' , col] = pd.api.types.is_string_dtype(test[col])
    df_types.at['is_cat' , col] = pd.api.types.is_categorical_dtype(test[col])
    df_types.at['is_obj' , col] = pd.api.types.is_object_dtype(test[col])

# Styling func
def coloring(df):
    clr_g = 'color : green'
    clr_r = 'color : red'
    mask = ~np.logical_xor(df.values, np.eye(df.shape[0], dtype=bool))
    # OUTPUT
    return pd.DataFrame(np.where(mask, clr_g, clr_r),
                        index = df.index,
                        columns = df.columns)

# OUTPUT colored
df_types.style.apply(coloring, axis=None)
```

<p>OUTPUT:
<img src="https://i.stack.imgur.com/nzzXb.png" alt="enter image description here"></p>

<pre class="lang-py prettyprint-override"><code>bool                  bool
int                  int64
float              float64
compl           complex128
dt          datetime64[ns]
td         timedelta64[ns]
prd              period[D]
intrv    interval[float64]
str                 object
cat               category
obj                 object
</code>```

Almost everything is good, but this test code produces two questions:

The most strange here is that pd.api.types.is_string_dtype fires
on category dtype. Why is that? Should it be treated as 'expected'
behavior?

Why is_string_dtype and  is_object_dtype fires on each
other? This is a bit expected, because even in .dtypes both types
are noted as object, but it would be better if someone clarify it
step by step.

P.s.: Bonus question - am i right when thinking that pandas has its internal tests that should be passed when building new release (like df_types from test code, but not with 'coloring in red' rather 'recording info about errors')?

EDIT: pandas version 0.24.2.

答:
This comes down to is_string_dtype being a fairly loose check, with the implementation even having a TODO note to make it more strict, linking to Issue #15585.

The reason this check is not strict is because there isn't a dedicated string dtype in pandas, and instead strings are just stored with object dtype, which could really store anything.  As such, a more strict check would likely introduce a performance overhead.

To answer your questions:

This is a result of CategoricalDtype.kind being set to 'O', which is one of the loose checks is_string_dtype does.  This could probably change in the future given the TODO note, so it's not something I'd rely upon.

Since strings are stored as object dtype it makes sense for is_object_dtype to fire on strings, and I'd consider this behavior to be reliable as the implementation will almost certainly not change in the immediate future. The reverse is true due to the reliance on dtype.kind in is_string_dtype, which has the same caveats as with categoricals described above.

Yes, pandas has a test suite that will run automatically on various CI services for every PR that's created. The test suite includes checks similar to what you're doing.

One tangentially related note to add: there is a library called fletcher that uses Apache Arrow to implement a more native string type in a way that's compatible with pandas.  It's still under development and probably doesn't currently have support for all the string operations that pandas does.

Body:
Guided by this answer I started to build up pipe for processing columns of dataframe based on its dtype. But after getting some unexpected output and some debugging i ended up with test dataframe and test dtype checking:

# Creating test dataframe
test = pd.DataFrame({'bool' :[False, True], 'int':[-1,2],'float': [-2.5, 3.4],
                     'compl':np.array([1-1j, 5]),
                     'dt'   :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
                     'td'   :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
                              pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
                     'prd'  :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
                     'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
                     'str'  :['s1', 's2'],
                     'cat'  :[1, -1],
                     'obj'  :[[1,2,3], [5435,35,-52,14]]
                    })
test['cat'] = test['cat'].astype('category')
test
test.dtypes

# Testing types
types = list(test.columns)
df_types = pd.DataFrame(np.zeros((len(types),len(types)), dtype=bool),
                        index = ['is_'+el for el in types],
                        columns = types)
for col in test.columns:
    df_types.at['is_bool', col] = pd.api.types.is_bool_dtype(test[col])
    df_types.at['is_int' , col] = pd.api.types.is_integer_dtype(test[col])
    df_types.at['is_float',col] = pd.api.types.is_float_dtype(test[col])
    df_types.at['is_compl',col] = pd.api.types.is_complex_dtype(test[col])
    df_types.at['is_dt'  , col] = pd.api.types.is_datetime64_dtype(test[col])
    df_types.at['is_td'  , col] = pd.api.types.is_timedelta64_dtype(test[col])
    df_types.at['is_prd' , col] = pd.api.types.is_period_dtype(test[col])
    df_types.at['is_intrv',col] = pd.api.types.is_interval_dtype(test[col])
    df_types.at['is_str' , col] = pd.api.types.is_string_dtype(test[col])
    df_types.at['is_cat' , col] = pd.api.types.is_categorical_dtype(test[col])
    df_types.at['is_obj' , col] = pd.api.types.is_object_dtype(test[col])

# Styling func
def coloring(df):
    clr_g = 'color : green'
    clr_r = 'color : red'
    mask = ~np.logical_xor(df.values, np.eye(df.shape[0], dtype=bool))
    # OUTPUT
    return pd.DataFrame(np.where(mask, clr_g, clr_r),
                        index = df.index,
                        columns = df.columns)

# OUTPUT colored
df_types.style.apply(coloring, axis=None)

OUTPUT:

bool                  bool
int                  int64
float              float64
compl           complex128
dt          datetime64[ns]
td         timedelta64[ns]
prd              period[D]
intrv    interval[float64]
str                 object
cat               category
obj                 object

Almost everything is good, but this test code produces two questions:

The most strange here is that pd.api.types.is_string_dtype fires
on category dtype. Why is that? Should it be treated as 'expected'
behavior?

Why is_string_dtype and  is_object_dtype fires on each
other? This is a bit expected, because even in .dtypes both types
are noted as object, but it would be better if someone clarify it
step by step.

P.s.: Bonus question - am i right when thinking that pandas has its internal tests that should be passed when building new release (like df_types from test code, but not with 'coloring in red' rather 'recording info about errors')?

EDIT: pandas version 0.24.2.


问:
Need tkinter on my python 3.6 installation (Windows 10)
I'm running Python 3.6 on a Windows 10 machine. I want to display a simple matplotlib plot like this:

```<code>import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
</code>```

Unfortunately, I get the error:

```<code>ModuleNotFoundError: No module named 'tkinter'
</code>```

I try installing tkinter through my terminal:

```<code>> pip install tkinter
Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
  No matching distribution found for tkinter
</code>```

I also tried pip install python3-tk but without success. I found a couple of posts on StackOverflow explaining how to install tkinter properly, but they're all about Python 2 and/or Linux systems. I couldn't find a post particularly for Python 3.6 on Windows 10.

答:
OK that is weird it worked like that, I had to re-install before and actually downgrade for it to work and uninstall on windows and have issues on linux also. I've done pip for both and everything else. Windows got it working from downgrading from 3.7 to 3.6 and uninstalling 3.7. So that may help someone.

Also a key factor is having access or a clear 'path' to C:\User\"UserName"\appdata from there usually \local but can be \roaming and it ccan appear in a file that is just named python with the version number after or \Local\packages\PythonSoftwareFoundation.python.3.7 or many other files it has shown up in, due to what seems random half the time I read about these occurances and even on Pythons help page, they suggest all the places without giving reason for why it would be in each, seeming like it is almost random.

Body:
I'm running Python 3.6 on a Windows 10 machine. I want to display a simple matplotlib plot like this:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)

Unfortunately, I get the error:

ModuleNotFoundError: No module named 'tkinter'

I try installing tkinter through my terminal:

> pip install tkinter
Collecting tkinter
  Could not find a version that satisfies the requirement tkinter (from versions: )
  No matching distribution found for tkinter

I also tried pip install python3-tk but without success. I found a couple of posts on StackOverflow explaining how to install tkinter properly, but they're all about Python 2 and/or Linux systems. I couldn't find a post particularly for Python 3.6 on Windows 10.


答: I will suggest trying out hierarchical clustering. In the Agglomerative approach, you will assign individual clusters to each point, and then combine clusters based on their distances from each other.</p>

Title: Which algorithm and what combination of hyper-parameters will be the best to cluster this data?

Body:
I was learning about non-linear clustering algorithms and I came across this 2-D graph. I was wondering which clustering alogirthm and combination of hyper-parameters will cluster this data well.

Just like a human will cluster those 5 spikes. I want my algorithm to do it.
I tried KMeans but it was only clustering horizontly or vertically. I started using GMM but couldn't get the hyper-parameters right for the desired clustering.


问:
Cannot inject Templating on Symfony 4 Service
I have the following class:

EmailNotification

```<code>namespace App\Component\Notification\RealTimeNotification;

use Symfony\Bridge\Twig\TwigEngine;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

use App\Component\Notification\NotificationInterface;

class EmailNotification implements NotificationInterface
{
    private $logNotification;

    public function __construct(LogNotification $logNotification, \Swift_Mailer $mailer,  EngineInterface $twigEngine)
    {
        $this->logNotification = $logNotification;
    }

    public function send(array $options): void
    {
        $this->logNotification->send($options);

        dump('Sent to email');
    }
}
</code>```

I have the following service definition on my yml:

```<code>app.email_notification:
    class: App\Component\Notification\RealTimeNotification\EmailNotification
    decorates: app.log_notification
    decoration_inner_name: app.log_notification.inner
    arguments: ['@app.log_notification.inner', '@mailer', '@templating']
</code>```

However, when i tried to run my app it throws an Exception saying:

Cannot autowire service
  "App\Component\Notification\RealTimeNotification\EmailNotification":
  argument "$twigEngine" of method "__construct()" has type
  "Symfony\Bundle\FrameworkBundle\Templating\EngineInterface" but this
  class was not found.

Why is that so?

Thanks!

答:
I managed to do it with Twig Environment and HTTP Response</p>

```<code><?php

namespace App\Controller;

use Twig\Environment;
use Symfony\Component\HttpFoundation\Response;

class MyClass
{
    private $twig;

    public function __construct(Environment $twig)
    {
        $this->twig = $twig;
    }

    public function renderTemplateAction($msg)
    {
        return new Response($this->twig->render('myTemplate.html.twig'));
    }
}
</code>```

Body:
I have the following class:

EmailNotification

namespace App\Component\Notification\RealTimeNotification;

use Symfony\Bridge\Twig\TwigEngine;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;

use App\Component\Notification\NotificationInterface;

class EmailNotification implements NotificationInterface
{
    private $logNotification;

    public function __construct(LogNotification $logNotification, \Swift_Mailer $mailer,  EngineInterface $twigEngine)
    {
        $this->logNotification = $logNotification;
    }

    public function send(array $options): void
    {
        $this->logNotification->send($options);

        dump('Sent to email');
    }
}

I have the following service definition on my yml:

app.email_notification:
    class: App\Component\Notification\RealTimeNotification\EmailNotification
    decorates: app.log_notification
    decoration_inner_name: app.log_notification.inner
    arguments: ['@app.log_notification.inner', '@mailer', '@templating']

However, when i tried to run my app it throws an Exception saying:

Cannot autowire service
  "App\Component\Notification\RealTimeNotification\EmailNotification":
  argument "$twigEngine" of method "__construct()" has type
  "Symfony\Bundle\FrameworkBundle\Templating\EngineInterface" but this
  class was not found.

Why is that so?

Thanks!

Body:
I managed to do it with Twig Environment and HTTP Response

<?php

namespace App\Controller;

use Twig\Environment;
use Symfony\Component\HttpFoundation\Response;

class MyClass
{
    private $twig;

    public function __construct(Environment $twig)
    {
        $this->twig = $twig;
    }

    public function renderTemplateAction($msg)
    {
        return new Response($this->twig->render('myTemplate.html.twig'));
    }
}


问:
How to fix "Could not retrieve mirrorlist" error in vagrant?
When ever I run vagrant up, I am getting the following error.

```<code>==> default: [2019-05-30T13:09:31+00:00] INFO: Running queued delayed notifications before re-raising exception
==> default:
==> default: ================================================================================
==> default: Error executing action `create` on resource 'yum_repository[ius]'
==> default: ================================================================================
==> default:
==> default:
==> default: Mixlib::ShellOut::ShellCommandFailed
==> default: ------------------------------------
==> default: execute[yum-makecache-ius] (/tmp/vagrant-chef/bb6e5277837de973166d09e85978af4a/cookbooks/yum/providers/repository.rb line 55) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
==> default: ---- Begin output of yum -q makecache --disablerepo=* --enablerepo=ius ----
==> default: STDOUT: Could not retrieve mirrorlist http://mirrors.iuscommunity.org/mirrorlist/?repo=ius-el6&arch=x86_64&protocol=https error was
==> default: 14: problem making ssl connection
==> default: STDERR: Error: Cannot find a valid baseurl for repo: ius
==> default: ---- End output of yum -q makecache --disablerepo=* --enablerepo=ius ----
==> default: Ran yum -q makecache --disablerepo=* --enablerepo=ius returned 1
==> default:
</code>```

Seems like something wrong with this URL:
http://mirrors.iuscommunity.org/mirrorlist/?repo=ius-el6&arch=x86_64&protocol=https

I tried with https and http. Even tried disabling sslverify false.

Can someone please help me with this?

答:
You’re probably running into some SSL certificate and TLS problems. Type on terminal :

```<code>yum -y install ca-certificates openssl nss
</code>```

Than retry again

Body:
When ever I run vagrant up, I am getting the following error.

==> default: [2019-05-30T13:09:31+00:00] INFO: Running queued delayed notifications before re-raising exception
==> default:
==> default: ================================================================================
==> default: Error executing action `create` on resource 'yum_repository[ius]'
==> default: ================================================================================
==> default:
==> default:
==> default: Mixlib::ShellOut::ShellCommandFailed
==> default: ------------------------------------
==> default: execute[yum-makecache-ius] (/tmp/vagrant-chef/bb6e5277837de973166d09e85978af4a/cookbooks/yum/providers/repository.rb line 55) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received '1'
==> default: ---- Begin output of yum -q makecache --disablerepo=* --enablerepo=ius ----
==> default: STDOUT: Could not retrieve mirrorlist http://mirrors.iuscommunity.org/mirrorlist/?repo=ius-el6&arch=x86_64&protocol=https error was
==> default: 14: problem making ssl connection
==> default: STDERR: Error: Cannot find a valid baseurl for repo: ius
==> default: ---- End output of yum -q makecache --disablerepo=* --enablerepo=ius ----
==> default: Ran yum -q makecache --disablerepo=* --enablerepo=ius returned 1
==> default:

Seems like something wrong with this URL:
http://mirrors.iuscommunity.org/mirrorlist/?repo=ius-el6&arch=x86_64&protocol=https

I tried with https and http. Even tried disabling sslverify false.

Can someone please help me with this?

Body:
You’re probably running into some SSL certificate and TLS problems. Type on terminal :

yum -y install ca-certificates openssl nss

Than retry again


问:
calculateDropLocation not working
I have this <s:list> with an itemrenderer and arraycollection as dataprovider.
Now my problem is I want to be able to drag and drop to reorder those items.

To do so I need to know the dragged item index, and the drop location.
I have the selected item index but when I want to calculate my drop location using this code in my dragcompletehandler()...

```<code>var dropLocal:DropLocation = listfiles.layout.calculateDropLocation(event);
trace (event.currentTarget.selectedIndex + "," + dropLocal.dropIndex);
</code>```

It always returns me the number 3 and not the correct drop locations index.

How is that possible?

答:
The list shouild drag and drop for you.  Set dragEnabled=true, dropEnabled=true, and dragMoveEnabled=true and you're done.  Dragging from within the list will reorder it.

If you want to manually implement the drop, you should do your work on a dragDrop handler, as that only executes on a valid dragDrop.  The dragComplete event fires even if there was no valid drop (dropping the item when a component was not marked to accept the drag).

Title: calculateDropLocation not working

Body:
I have this <s:list> with an itemrenderer and arraycollection as dataprovider.
Now my problem is I want to be able to drag and drop to reorder those items.

To do so I need to know the dragged item index, and the drop location.
I have the selected item index but when I want to calculate my drop location using this code in my dragcompletehandler()...

var dropLocal:DropLocation = listfiles.layout.calculateDropLocation(event);
trace (event.currentTarget.selectedIndex + "," + dropLocal.dropIndex);

It always returns me the number 3 and not the correct drop locations index.

How is that possible?


问:
Copying same name files from different locations
For the purpose of incident response I am trying to create a powershell script that will go through all c:\users directories and copy the ntuser.dat then paste them into a new directory that the script creates. I have some pieces of the puzzle however I am having a hard time putting it all together.
Some of the problems I cannot solve is
1. Look for all c:\users*\ntuser.dat and unhide
2. Rename all ntuser.dat to include the folder name
3. Copying all newly renamed ntuser.dat into new folder
4. Renaming all ntuser.dat in c:\users back to normal.

```<code>#1 Unhides the ntuser.dat
$h = gci C:\Users\Test1\NTUSER.DAT -Force
$h.Attributes = $h.Attributes -bxor [System.IO.FileAttributes]::Hidden

#2 Renames ntuser.dat as foldername_ntuser.dat
Get-ChildItem C:\users\test1\ -Filter *.dat -Recurse | Rename-Item -NewName {$_.Directory.Name+'_'+$_.Name}

#3 Creating a new folder and copying the newly named test_ntuser.dat
$SourceFile = "c:\users\test1\*.dat"
$DestinationFile = "c:\users\user2\desktop\test\test_netuser.dat"
If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i +=1
        $DestinationFile = "c:\users\user2\desktop\test\"
    }
}Else {
    New-Item -ItemType file -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force
</code>```

At the end of this I would like the script to unhide, rename, and move to a new folder from
c:\users\test1\
c:\users\test2
c:\users\test3
Without having to reference each individual users path

答:
Well you will have a few problems doing this as NTUSER.dat is loaded into memory if a user is being used. So you couldnt copy your own NTUSER.dat while you are logged into the computer. Also if there is a service running under the name of a user you will not be able to get those ether.

So lets go over what you wanted and why you didnt need it.

1 Look for all c:\users\ntuser.dat and unhide* :
There is no need to unhide the original file. You just need to unhide the copy.

2 Rename all ntuser.dat to include the folder name : No Need to rename the original file just the copy.

3 Copying all newly renamed ntuser.dat into new folder : The Copy itself allows you to name the file whatever you want without the first 2 steps.

4 Renaming all ntuser.dat in c:\users back to normal : No need for this step ether as the original files were never renamed.

```<code>Function Copy-NTUser($SavePath){
    Get-ChildItem C:\Users\ -Directory | %{
        $Name = $_.Name
        Get-ChildItem "$($_.FullName)\ntuser.dat" -File -force -ErrorAction SilentlyContinue | %{
            $FullName = $_.FullName
            try{
                Copy-Item -Path $_.FullName -Destination "$($SavePath)\$($Name)_$($_.name)" -Force -PassThru  | %{
                    $_.Attributes = $_.Attributes -bxor [System.IO.FileAttributes]::Hidden
                }
            }catch{
                "$($FullName) could not be copied as its currently in use."
            }
        }
    }
}

Copy-NTUser -SavePath C:\Test\NTUSER
</code>```

Body:
For the purpose of incident response I am trying to create a powershell script that will go through all c:\users directories and copy the ntuser.dat then paste them into a new directory that the script creates. I have some pieces of the puzzle however I am having a hard time putting it all together.
Some of the problems I cannot solve is
1. Look for all c:\users*\ntuser.dat and unhide
2. Rename all ntuser.dat to include the folder name
3. Copying all newly renamed ntuser.dat into new folder
4. Renaming all ntuser.dat in c:\users back to normal.

#1 Unhides the ntuser.dat
$h = gci C:\Users\Test1\NTUSER.DAT -Force
$h.Attributes = $h.Attributes -bxor [System.IO.FileAttributes]::Hidden

#2 Renames ntuser.dat as foldername_ntuser.dat
Get-ChildItem C:\users\test1\ -Filter *.dat -Recurse | Rename-Item -NewName {$_.Directory.Name+'_'+$_.Name}

#3 Creating a new folder and copying the newly named test_ntuser.dat
$SourceFile = "c:\users\test1\*.dat"
$DestinationFile = "c:\users\user2\desktop\test\test_netuser.dat"
If (Test-Path $DestinationFile) {
    $i = 0
    While (Test-Path $DestinationFile) {
        $i +=1
        $DestinationFile = "c:\users\user2\desktop\test\"
    }
}Else {
    New-Item -ItemType file -Path $DestinationFile -Force
}
Copy-Item -Path $SourceFile -Destination $DestinationFile -Force

At the end of this I would like the script to unhide, rename, and move to a new folder from
c:\users\test1\
c:\users\test2
c:\users\test3
Without having to reference each individual users path

Body:
Well you will have a few problems doing this as NTUSER.dat is loaded into memory if a user is being used. So you couldnt copy your own NTUSER.dat while you are logged into the computer. Also if there is a service running under the name of a user you will not be able to get those ether.

So lets go over what you wanted and why you didnt need it.

1 Look for all c:\users\ntuser.dat and unhide* :
There is no need to unhide the original file. You just need to unhide the copy.

2 Rename all ntuser.dat to include the folder name : No Need to rename the original file just the copy.

3 Copying all newly renamed ntuser.dat into new folder : The Copy itself allows you to name the file whatever you want without the first 2 steps.

4 Renaming all ntuser.dat in c:\users back to normal : No need for this step ether as the original files were never renamed.

Function Copy-NTUser($SavePath){
    Get-ChildItem C:\Users\ -Directory | %{
        $Name = $_.Name
        Get-ChildItem "$($_.FullName)\ntuser.dat" -File -force -ErrorAction SilentlyContinue | %{
            $FullName = $_.FullName
            try{
                Copy-Item -Path $_.FullName -Destination "$($SavePath)\$($Name)_$($_.name)" -Force -PassThru  | %{
                    $_.Attributes = $_.Attributes -bxor [System.IO.FileAttributes]::Hidden
                }
            }catch{
                "$($FullName) could not be copied as its currently in use."
            }
        }
    }
}

Copy-NTUser -SavePath C:\Test\NTUSER


问:
string editing in ios swift
I am having a string in that I have getting a tag
 and I want to append  ahead of

```<code>let str = "<p>A new week-long event is kicking off soon in <a href="/pokemon-go/" data-ref-id="5000-449545">Pokemon Go</a>. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.</p><p>During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.</p>"
</code>```

I want this string as:

```<code>let newStr = #"<b><p>A new week-long event is kicking off soon in <a href="/pokemon-go/" data-ref-id="5000-449545">Pokemon Go</a>. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.</p></b><p>During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.</p>"#
</code>```

答:
If you want to replace all occurrences of a string with another string you can use replacingOccurrences(of:with:). If you want to replace the first occurrence find range of the substring and replace with new substring </p>

```<code>if let range = str.range(of: "<p>") {
    str.replaceSubrange(range, with: "<b><p>")
}
if let range = str.range(of: "</p>") {
    str.replaceSubrange(range, with: "</b></p>")
}
</code>```

Title: string editing in ios swift

Body:
I am having a string in that I have getting a tag
 and I want to append  ahead of

let str = "
A new week-long event is kicking off soon in Pokemon Go. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.

During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.
"

I want this string as:

let newStr = #"
A new week-long event is kicking off soon in Pokemon Go. Niantic is holding another Adventure Week beginning Tuesday, June 4, and it'll give players a chance to earn extra rewards, catch some rare Rock-types, and even find a couple of new Shiny Pokemon.

During Adventure Week, Geodude, Rhyhorn, Omanyte, Aron, Lileep, Anorith, and other Rock Pokemon will appear in the wild much more frequently than normal.
"#

Body:
If you want to replace all occurrences of a string with another string you can use replacingOccurrences(of:with:). If you want to replace the first occurrence find range of the substring and replace with new substring

if let range = str.range(of: "<p>") {
    str.replaceSubrange(range, with: "<b><p>")
}
if let range = str.range(of: "</p>") {
    str.replaceSubrange(range, with: "</b></p>")
}


问:
How to get request header values in symfony
Am using symfony frame work in my application to make rest web service. I want to get request header values in controller method. Is there any way to achieve it. </p>

答:
If you need to get a specific header you can use:

```<code>$request->headers->get('My-Header');
</code>```

See documentation: https://symfony.com/doc/current/components/http_foundation.html#accessing-accept-headers-data

Body:
If you need to get a specific header you can use:

$request->headers->get('My-Header');

See documentation: https://symfony.com/doc/current/components/http_foundation.html#accessing-accept-headers-data


问:
Can I change the table that a mysql foreign key references without locking anything?
We have a large schema migration to run, and we don't want the site to go down for ages, so we're trying to do it on the fly and without read locking the tables involved.  The tables involved only get written to at specific times of the day, so we have a window in which we can afford to have write locks; but while a lot of the mysql docs claim ALTER TABLE should only write lock tables, in our experience anything nontrivial such as adding an index read locks it.

So, we've had to do the migrations by hand.  We've had some success with the following procedure:

CREATE TABLE new_mytable LIKE mytable;

apply the migration to new_mytable

mysqldump -t mydb mytable > mytable.sql

use sed to change mytable.sql to insert into the correct columns of new_mytable

mysql mydb < mytable.sql

drop foreign keys on mytable - they're not copied by CREATE TABLE ... LIKE ...

add foreign keys to new_mytable

RENAME TABLE mytable TO old_mytable, new_mytable TO mytable

run a few sanity checks

DROP TABLE old_mytable

As I say, the tables involved only get written to at specific times of the day, so we're certain that the data stays consistent - otherwise we wouldn't dream of trying something like that.  Even so, we've hit a problem.  Until now, we've only tried it on tables where the FKs point outwards.  Today I tried it on a table which was referred to by several other tables.  When I dropped the old table, I was told that a foreign key constraint failed, and was horrified to see that the referring tables now refer to the old table.

Now, we could drop the FKs and re-add them to the new one, but the process is fragile enough as it is; there are a lot of tables pointing to this one; and re-adding the keys may give us read locks.  We're certain - certain - that the new table contains all the same data as the first one, so what would be nice would be to change the referent of those FKs without dropping and adding them.  Is there a way to manipulate the DB such that the existing FKs are altered to refer to the new table?

答:
Provided you know how to alter the tables themselves.</p>

```<code>SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

...Alter the tables and change the keys

SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
</code>```

Body:
Provided you know how to alter the tables themselves.

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

...Alter the tables and change the keys

SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;