问:
create a variable from multiple variables in R
I have a data set looks like, dat. I want to create one new variable (newVar) with values 1 through 4 using the Q1 through Q6 in R. Can anyone help how to do this, please?

```<code>newVar of 1: If any variable in Q1 through Q6 = "A"
newVar of 2: **If none of variables in Q1 through Q6 = "A", and** If any variable in Q59_1 through Q6= "B"
newVar of 3: **If none of variables in Q1 through Q6 = "A" or "B", and** If any variable in Q1 through Q6= "C"
newVar of 4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and**strong text** If any variable in Q1 through Q6= "D"

dat = data.frame(Q1 = c("A","D","B","A","D","C","B"),
                 Q2 = c("C","A","B","A","C","C","B"),
                 Q3 = c("B","D","D","A","B","C","A"),
                 Q4 = c("A","C","A","D","B","D","B"),
                 Q5 = c("C","D","D","A","A","C","B"),
                 Q6 = c("D","B","A","A","C","C","A"),
                 Q7 = c("5","1","2","2","4","0","3"),
                 Q8 = c("T","U","O","O","Z","W","Y"),
                 Q9 = c("X","T","V","P","I","U","Y"))
</code>```

Additional comment: I actually need all the conditions especially the bold parts (If none of variables in ...) such as
    NewVar 2: If none of variables in Q1 through Q6 = "A", and If any variable in Q59_1 through Q6= "B"
       3: If none of variables in Q1 through Q6 = "A" or "B", and If any variable in Q1 through Q6= "C"
       4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and If any variable in Q1 through Q6= "D"

答:
Using packages tidyr and dplyr:

dat %>%
  mutate(id = row_number()) %>%
  pivot_longer(cols=starts_with("Q"), names_to="Q", names_prefix="Q") %>%
  group_by(id) %>%
  mutate(newVar=case_when(Q %in% 1:6 & any(value == "A") ~ 1,
                          Q %in% 1:6 & any(value == "B") ~ 2,
                          Q %in% 1:6 & any(value == "C") ~ 3,
                          Q %in% 1:6 & any(value == "D") ~ 4)) %>%
  pivot_wider(names_from="Q", names_prefix="Q", names_sep="") %>%
  fill(everything(), .direction="down") %>%
  slice(2)
```

<p>I'm not sure if I got your conditions right. And there are surely more tidy ways, but this one yields</p>

<pre class="lang-r prettyprint-override"><code># A tibble: 7 x 11
# Groups:   id [7]
     id newVar Q1    Q2    Q3    Q4    Q5    Q6    Q7    Q8    Q9
  <int>  <dbl> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1     1      1 A     C     B     A     C     D     5     T     X
2     2      1 D     A     D     C     D     B     1     U     T
3     3      1 B     B     D     A     D     A     2     O     V
4     4      1 A     A     A     D     A     A     2     O     P
5     5      1 D     C     B     B     A     C     4     Z     I
6     6      3 C     C     C     D     C     C     0     W     U
7     7      1 B     B     A     B     B     A     3     Y     Y
</code>```

Body:
I have a data set looks like, dat. I want to create one new variable (newVar) with values 1 through 4 using the Q1 through Q6 in R. Can anyone help how to do this, please?

newVar of 1: If any variable in Q1 through Q6 = "A"
newVar of 2: **If none of variables in Q1 through Q6 = "A", and** If any variable in Q59_1 through Q6= "B"
newVar of 3: **If none of variables in Q1 through Q6 = "A" or "B", and** If any variable in Q1 through Q6= "C"
newVar of 4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and**strong text** If any variable in Q1 through Q6= "D"

dat = data.frame(Q1 = c("A","D","B","A","D","C","B"),
                 Q2 = c("C","A","B","A","C","C","B"),
                 Q3 = c("B","D","D","A","B","C","A"),
                 Q4 = c("A","C","A","D","B","D","B"),
                 Q5 = c("C","D","D","A","A","C","B"),
                 Q6 = c("D","B","A","A","C","C","A"),
                 Q7 = c("5","1","2","2","4","0","3"),
                 Q8 = c("T","U","O","O","Z","W","Y"),
                 Q9 = c("X","T","V","P","I","U","Y"))

Additional comment: I actually need all the conditions especially the bold parts (If none of variables in ...) such as
    NewVar 2: If none of variables in Q1 through Q6 = "A", and If any variable in Q59_1 through Q6= "B"
       3: If none of variables in Q1 through Q6 = "A" or "B", and If any variable in Q1 through Q6= "C"
       4: If none of variables in Q1 through Q6 = "A" or "B" or "C" , and If any variable in Q1 through Q6= "D"

Body:
Using packages tidyr and dplyr:

dat %>%
  mutate(id = row_number()) %>%
  pivot_longer(cols=starts_with("Q"), names_to="Q", names_prefix="Q") %>%
  group_by(id) %>%
  mutate(newVar=case_when(Q %in% 1:6 & any(value == "A") ~ 1,
                          Q %in% 1:6 & any(value == "B") ~ 2,
                          Q %in% 1:6 & any(value == "C") ~ 3,
                          Q %in% 1:6 & any(value == "D") ~ 4)) %>%
  pivot_wider(names_from="Q", names_prefix="Q", names_sep="") %>%
  fill(everything(), .direction="down") %>%
  slice(2)

I'm not sure if I got your conditions right. And there are surely more tidy ways, but this one yields

# A tibble: 7 x 11
# Groups:   id [7]
     id newVar Q1    Q2    Q3    Q4    Q5    Q6    Q7    Q8    Q9
  <int>  <dbl> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1     1      1 A     C     B     A     C     D     5     T     X
2     2      1 D     A     D     C     D     B     1     U     T
3     3      1 B     B     D     A     D     A     2     O     V
4     4      1 A     A     A     D     A     A     2     O     P
5     5      1 D     C     B     B     A     C     4     Z     I
6     6      3 C     C     C     D     C     C     0     W     U
7     7      1 B     B     A     B     B     A     3     Y     Y


来源: stackexchange

问:
How to check if a variable is in specific range
I have a list of lists that looks like this:

```<code> mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]
</code>```

What I am trying to do is to take a number provided by the user and then check if the number provided is equal or in a range of +0.6 compared to the second element of each sublist. In other words I want to do the following: if user input is 3.4 then I want to check based on the example provided of list of lists these two numbers: 3.4207362518089726 and 2.9687393162393163 and if these numbers are in range of +0.6 from the input, then to save the whole sublist in another list.

So, user_input = 3.4, mylists[0][1] = 3.4207362518089726, mylists[1][1] = 2.9687393162393163 and I want to place in a new list each sublist that has 3.4 and above, till 4.0 (due to range of + 0.6)

What I thought was this:

```<code>for i in range(0, len(mylists)):
        if mylists[i][1] >= user_input + 0.6:
             new_list.append(mylists[i])
</code>```

But of course this did not work.

答:
Are you getting an error or just an unexpected output?

perhaps you can try:

```<code>new_list = list(filter(lambda x: user_input<= x[1] <= user_input + 0.6 , mylists))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a list of lists that looks like this:

 mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

What I am trying to do is to take a number provided by the user and then check if the number provided is equal or in a range of +0.6 compared to the second element of each sublist. In other words I want to do the following: if user input is 3.4 then I want to check based on the example provided of list of lists these two numbers: 3.4207362518089726 and 2.9687393162393163 and if these numbers are in range of +0.6 from the input, then to save the whole sublist in another list.

So, user_input = 3.4, mylists[0][1] = 3.4207362518089726, mylists[1][1] = 2.9687393162393163 and I want to place in a new list each sublist that has 3.4 and above, till 4.0 (due to range of + 0.6)

What I thought was this:

for i in range(0, len(mylists)):
        if mylists[i][1] >= user_input + 0.6:
             new_list.append(mylists[i])

But of course this did not work.

Body:
Are you getting an error or just an unexpected output?

perhaps you can try:

new_list = list(filter(lambda x: user_input<= x[1] <= user_input + 0.6 , mylists))


问:
Runtime.freeMemory() and company or early allocation to prevent late out of memory errors
I am writing a program which, depending on JVM, heap size and user settings, is likely to throw some OOM errors pretty often.

I do not want to give it some arbitrary limits, but since, when this errors are going to occur, the program will likely take a lot of time to run before producing some meaningfull output, I wanted it at least to quit as soon as possible if an OOM is going to happen. My first approach was to initialize the most memory consuming objects early, which probably is not a good practice.

Since some more memory can be needed later depending on user input, I also wanted to ensure some reasonably safe margin of free memory, and, after some awful ideas, I figured out that using methods from Runtime and giving the user some data  on the remaining memory, on what can be expected from that data and a warning if needed would be a more elegant solution.

One of the early initialized objects is an array used to write to an audio file, it is not used until the end of the program and I considered adding it's size to the free memory calculation and initializing it only when it is needed.

As far as I see the major flaws with calculating free memory before are the following:

It is not completely accurate

For some objects the actual size in heap memory cannot be predicted and depends on the implementation

In corner cases the program will still terminate at the end of the computation, when the objects are initialized, not as soon as there is not enough memory left to complete the program. Doing repeated checks can be a solution, but this can affect performance.

And the major problems with early initialization are the following:

It freezes some resources which aren't used, probably affecting performance.

May affect readability and maintainability of the code, especially if misused and/or in larger programs.

Causes the program to always exit with an error instead of preventing it and exiting in a graceful way.

What would be in most cases the best approach to this kind of problem, are there better solutions or other factors that should be considered or are some of the one I mentioned more or less important than I think?

PS I probably can and should improve memory management and this would mitigate or almost solve the problem in most cases and caring about memory management should be the priority, but I think it is still a valid question. I understand that Runtime.freeMemory() cannot be used as it seems at a first glance .

EDIT

I'll try to clarify what I mean by early OOM.

Chunk of memory A (used from the beginning, reasonably predictable by options)

Chunk of memory B (variable, depending on user input)

Chunk of memory C (used at the end, reasonably predictable by options)

Normal way: A ,B ,long computetion, C (the OOM will likely happen here)

Early initialization: A ,C ,B (the OOM will likely happen here), long computation

One important point that I missed (and probably outweights the others in most real world programs) is that some memory from A and B will likely be freed before C is used and early initialization will cause the program to fail even when there's no need for it.

答:
If you want your program to quit quickly when OutOfMemoryError is thrown use -XX:+ExitOnOutOfMemoryError or -XX:+CrashOnOutOfMemoryError option. This will ensure that when OOME is thrown in your program the JVM will exit. See this article to understand the difference between these options.

Do note that OutOfMemoryError is thrown in few situations: not enough memory to allocate an object, GC overhead limit reached, file descriptor limit reached, etc.


问:
C++ pointer problem : How to fix bugs in these codes?
```<code>#include <vector>
struct node{
    int x;
};
node* temp = new node();
std::vector<node*> ptrs;
for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
    std::cout << (*j)->x;
}
delete temp;
</code>```

This prints 999999999 as output. I want to have 123456789.

What is the best way to modify this? I mean, what is the best fashion?

答:
You are allocating only 1 node object and then storing 10 node* pointers into your vector that all point at that 1 node object.  So, in your 1st loop, all of the assignments to x are on that 1 node.  When that 1st loop is finished, whatever last value was assigned to the 1 node's x, that is what your 2nd loop prints out 10 times.

For what you are attempting, you need to allocate and free 10 separate node objects, eg:

#include <vector>
struct node{
    int x;
};
node* temp;
std::vector<node*> ptrs;
for (int i = 0; i < 10; ++i){
    temp = new node; // <-- MOVED HERE!!!
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>::iterator j;
for (j = ptrs.begin(); j != ptrs.end(); ++j){
    std::cout << (*j)->x;
}
for (j = ptrs.begin(); j != ptrs.end(); ++j){ // <-- ADD THIS LOOP!!!
    temp = *j;
    delete temp;
}
```

<p>But, why are you using pointers at all?  This is not a good example that warrants the use of pointers at all.  You should create a <code>vector</code> of <code>node</code> objects, not a <code>vector</code> of pointers to <code>node</code> objects, eg:</p>

<pre class="lang-cpp prettyprint-override"><code>#include <vector>
struct node{
    int x;
};
std::vector<node> nodes;
for (int i = 0; i < 10; ++i){
    node temp;
    temp.x = i;
    nodes.push_back(temp);
}
std::vector<node>::iterator j;
for (j = nodes.begin(); j != nodes.end(); ++j){
    std::cout << j->x; // or (*j).x
}
</code>```

Alternatively:

#include <vector>
struct node{
    int x;
};
std::vector<node> nodes(10);
std::vector<node>::iterator j;
for (j = nodes.begin(); j != nodes.end(); ++j){
    j->x = i; // or (*j).x
}
for (j = nodes.begin(); j != nodes.end(); ++j){
    std::cout << j->x; // or (*j).x
}
```

Body:
#include <vector>
struct node{
    int x;
};
node* temp = new node();
std::vector<node*> ptrs;
for (int i = 0; i < 10; i++){
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>:: iterator j;
for (j = ptrs.begin(); j != ptrs.end(); j++){
    std::cout << (*j)->x;
}
delete temp;

This prints 999999999 as output. I want to have 123456789.

What is the best way to modify this? I mean, what is the best fashion?

Body:
You are allocating only 1 node object and then storing 10 node* pointers into your vector that all point at that 1 node object.  So, in your 1st loop, all of the assignments to x are on that 1 node.  When that 1st loop is finished, whatever last value was assigned to the 1 node's x, that is what your 2nd loop prints out 10 times.

For what you are attempting, you need to allocate and free 10 separate node objects, eg:

#include <vector>
struct node{
    int x;
};
node* temp;
std::vector<node*> ptrs;
for (int i = 0; i < 10; ++i){
    temp = new node; // <-- MOVED HERE!!!
    temp->x = i;
    ptrs.push_back(temp);
}
std::vector<node*>::iterator j;
for (j = ptrs.begin(); j != ptrs.end(); ++j){
    std::cout << (*j)->x;
}
for (j = ptrs.begin(); j != ptrs.end(); ++j){ // <-- ADD THIS LOOP!!!
    temp = *j;
    delete temp;
}

But, why are you using pointers at all?  This is not a good example that warrants the use of pointers at all.  You should create a vector of node objects, not a vector of pointers to node objects, eg:

#include <vector>
struct node{
    int x;
};
std::vector<node> nodes;
for (int i = 0; i < 10; ++i){
    node temp;
    temp.x = i;
    nodes.push_back(temp);
}
std::vector<node>::iterator j;
for (j = nodes.begin(); j != nodes.end(); ++j){
    std::cout << j->x; // or (*j).x
}

Alternatively:

#include <vector>
struct node{
    int x;
};
std::vector<node> nodes(10);
std::vector<node>::iterator j;
for (j = nodes.begin(); j != nodes.end(); ++j){
    j->x = i; // or (*j).x
}
for (j = nodes.begin(); j != nodes.end(); ++j){
    std::cout << j->x; // or (*j).x
}


问:
Full range of options for respond_to format.*
I'm looking into rendering more complex responses.

Specifically, I am searching for options for formatting yaml and json responses with multiple levels, but right now I cannot locate any api information on options.

I've seen something about :include and :only in other sample controllers. I'm wondering what the full range of options are for more complex rendering of documents (specifically yaml, but I'd like to learn for all)

For example:

```<code> def index
    @people = Person.find(:all)

    respond_to do |format|
      format.*  ?????????????????????
    end
  end
</code>```

background: trying to assemble what is for me more complex yaml ouput and seeing what and how I can from the controller as opposed to having to build a specific view.

答:
After reading through the rails code, I can safely say that there isn't anything else that you don't know about. (Although the documentation for respond_to in block form seems to be missing from the API docs)

Basically there are two ways to use respond_to

Declarative

```<code>class WidgetsController
  respond_to :html, :xml, :json, only: [:index, :show]

  def index
    @widgets = Widget.all
    respond_with @widgets
  end
  …
end
</code>```

Block

```<code>class WidgetsController
  def index
    @widgets = Widget.all
    respond_to do |format|
      format.html #do default
      format.pdf {…} # handle in block
      format.any(:json, :xml) {…} # handle anything listed
    end
  end
  …
end
</code>```

You can't use the options on the block form (it is a different method definition entirely), and :only and :except are the only options that the declarative version accepts.

ContentLicense: CC BY-SA 3.0

Body:
I'm looking into rendering more complex responses.

Specifically, I am searching for options for formatting yaml and json responses with multiple levels, but right now I cannot locate any api information on options.

I've seen something about :include and :only in other sample controllers. I'm wondering what the full range of options are for more complex rendering of documents (specifically yaml, but I'd like to learn for all)

For example:

 def index
    @people = Person.find(:all)

    respond_to do |format|
      format.*  ?????????????????????
    end
  end

background: trying to assemble what is for me more complex yaml ouput and seeing what and how I can from the controller as opposed to having to build a specific view.

Body:
After reading through the rails code, I can safely say that there isn't anything else that you don't know about. (Although the documentation for respond_to in block form seems to be missing from the API docs)

Basically there are two ways to use respond_to

Declarative

class WidgetsController
  respond_to :html, :xml, :json, only: [:index, :show]

  def index
    @widgets = Widget.all
    respond_with @widgets
  end
  …
end

Block

class WidgetsController
  def index
    @widgets = Widget.all
    respond_to do |format|
      format.html #do default
      format.pdf {…} # handle in block
      format.any(:json, :xml) {…} # handle anything listed
    end
  end
  …
end

You can't use the options on the block form (it is a different method definition entirely), and :only and :except are the only options that the declarative version accepts.


问:
How to test validation errors throw exact error and message in laravel unit tests
How to test specific validation errors in php unit thrown in validation error ?
with below code we could check session has errors, but not the exact error</p>

```<code>$this->assertSessionHasErrors();
</code>```

答:
You can use $response->assertSessionHasErrors('key')

https://laravel.com/docs/7.x/http-tests#assert-session-has-errors

an example for required attribute will be

```<code>$response = $this->json('POST', '/api/courses', $this->data([
    'name' => '',
    'api_token' => $this->user->api_token
]));

$response->assertSessionHasErrors('name');
</code>```

You can add an extra assertion, to make sure that no entry was added to the database, in this case "assert no course was added"

```<code>$this->assertCount(0, Course::all());
</code>```

For multiple required attributes you may use a loop something like the following:

```<code>collect(['name', 'description', 'amount'])->each(function ($field) {
    $response = $this->json('POST', '/api/courses', $this->data([
        $field => '',
        'api_token' => $this->user->api_token
    ]));

    $response->assertSessionHasErrors($field);
    $this->assertCount(0, Course::all());
});
</code>```

Body:
How to test specific validation errors in php unit thrown in validation error ?
with below code we could check session has errors, but not the exact error

$this->assertSessionHasErrors();

Body:
You can use $response->assertSessionHasErrors('key')

https://laravel.com/docs/7.x/http-tests#assert-session-has-errors

an example for required attribute will be

$response = $this->json('POST', '/api/courses', $this->data([
    'name' => '',
    'api_token' => $this->user->api_token
]));

$response->assertSessionHasErrors('name');

You can add an extra assertion, to make sure that no entry was added to the database, in this case "assert no course was added"

$this->assertCount(0, Course::all());

For multiple required attributes you may use a loop something like the following:

collect(['name', 'description', 'amount'])->each(function ($field) {
    $response = $this->json('POST', '/api/courses', $this->data([
        $field => '',
        'api_token' => $this->user->api_token
    ]));

    $response->assertSessionHasErrors($field);
    $this->assertCount(0, Course::all());
});


问:
Angular 9 : Children routing inside lazy loaded component not working
I have app component in which i lazy load create-new-module with component profilecomponent. now in profile component i hit router.navigate and trying to load another children detail in place of profile but its not working also no error in console.

please help

// App component route

const routes: Routes = [
  {
    path: 'create-new-emp',
    loadChildren: () => import('./create-new-emp/create-new-emp.module').then(c => c.CreateNewEmpModule),
  },
  { path: '',  redirectTo: 'create-new-emp', pathMatch: 'full'},
  { path: '**',  redirectTo: 'create-new-emp'}
];

// Emp Module Route

const routes: Routes = [
  { path: '', component: ContainerComponent,
  children: [
    { path: '', component: ProfileComponent, outlet: 'form'},
    { path: 'profile', component: ProfileComponent, outlet: 'form'},
    { path: 'detail', component: DetailComponent, outlet: 'form' }] }
];

// Trying to hit below link but not working

this.router.navigate(['detail'])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><app-component>
<router-outlet>
<container-component>
<profile-component></profile-component>
</container-component>
</router-outlet>
</app-component></code>```

答:
Complicated with only these information to help. But  is the way angular navigates amount components/pages. I think what you are trying to do is navigate between components (according your router.ts). If you want to navigate, you only need router-outlet in your html code and not use component tag in the HTML code.

Change this:

```<code><app-component>
<router-outlet>
<container-component>
<profile-component></profile-component>
</container-component>
</router-outlet>
</app-component>
</code>```

To this:

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

Then, into ContainerComponent.html you need to repeat to navigate to details o profile because these are child routes.

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

That will give you more information about what you need.

Body:
I have app component in which i lazy load create-new-module with component profilecomponent. now in profile component i hit router.navigate and trying to load another children detail in place of profile but its not working also no error in console.

please help

// App component route

const routes: Routes = [
  {
    path: 'create-new-emp',
    loadChildren: () => import('./create-new-emp/create-new-emp.module').then(c => c.CreateNewEmpModule),
  },
  { path: '',  redirectTo: 'create-new-emp', pathMatch: 'full'},
  { path: '**',  redirectTo: 'create-new-emp'}
];

// Emp Module Route

const routes: Routes = [
  { path: '', component: ContainerComponent,
  children: [
    { path: '', component: ProfileComponent, outlet: 'form'},
    { path: 'profile', component: ProfileComponent, outlet: 'form'},
    { path: 'detail', component: DetailComponent, outlet: 'form' }] }
];

// Trying to hit below link but not working

this.router.navigate(['detail'])

<app-component>
<router-outlet>
<container-component>
<profile-component></profile-component>
</container-component>
</router-outlet>
</app-component>

Body:
Complicated with only these information to help. But  is the way angular navigates amount components/pages. I think what you are trying to do is navigate between components (according your router.ts). If you want to navigate, you only need router-outlet in your html code and not use component tag in the HTML code.

Change this:

<app-component>
<router-outlet>
<container-component>
<profile-component></profile-component>
</container-component>
</router-outlet>
</app-component>

To this:

<app-component>
<router-outlet>
</router-outlet>
</app-component>

Then, into ContainerComponent.html you need to repeat to navigate to details o profile because these are child routes.

<router-outlet></router-outlet>

That will give you more information about what you need.


问:
string representation of dictionary without quotes in values
I am trying to create a string that can be evaluated to a dictionary such as:

```<code>'{"key1": val1, "key2": val2}'
</code>```

I first tried:

str({key: "val%d" % i for i, key in enumerate(args)})
```

This mostly works except instead of val1 I get 'val1'. I might be able to do something with a for loop, but that felt awkward. Is there a better way of doing this?

Unfortunately I can't just pickle the dictionary, it needs to be a valid Python dictionary.

答:
For the sake of standardization, I would suggest using the builtin json library to encode and decode your info strings.

```<code>>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
</code>```

```<code>>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
</code>```

The json module plays nice with request, pickle, etc. and can help you avoid headache and mistakes by implementing the formatting protocols for you.

Body:
I am trying to create a string that can be evaluated to a dictionary such as:

'{"key1": val1, "key2": val2}'

I first tried:

str({key: "val%d" % i for i, key in enumerate(args)})

This mostly works except instead of val1 I get 'val1'. I might be able to do something with a for loop, but that felt awkward. Is there a better way of doing this?

Unfortunately I can't just pickle the dictionary, it needs to be a valid Python dictionary.

Body:
For the sake of standardization, I would suggest using the builtin json library to encode and decode your info strings.

>>> json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]

The json module plays nice with request, pickle, etc. and can help you avoid headache and mistakes by implementing the formatting protocols for you.


问:
How to automate creating models in django?
My models are generated from the shapefiles by using ogrinspect . But , after the creation of the model , lets say the user want to add an additional attribute . For this , the new attribute should be reflected in two tables . One should contain the name of the attribute , the other the attribute as a column . The name of the attribute doesnt need a change in model , and can be easily taken care of . But how to add an attribute to a table which was generated automatically ?</p>

答:
You may be able to use South to manage changes changes to your models. Whenever the model is changed you can run schemamigration --auto <appname> to create a migration and then migrate <appname> to apply it. This will create the tables in your model.

If you expect the models in your application to be changing a lot - particularly if it can be changed by end-users, you are probably thinking about it the wrong way. You may need to think about re-designing your information schema so it is more flexible!

If you have any more information about what you are trying to achieve, we may be able to offer suggestions!


问:
Select delete and insert at the same time PHP and SQL Server
What I want to do is first Select if the Cardindex Column has the values 0.1 and 2. with the same UserIndex (id) if those values exist (The 3 are mandatory), then we proceed to delete the 3 themselves and then Insert in the same table a new value. as long as the previous condition is met, if it is not met, it is not inserted.

In the query that I show the first query works well, it removes the data 0,1,2, until there everything is perfect, but then when inserting the new row it does it, but without respecting the previous condition. if in case it was not fulfilled it inserts it anyway.

It seems very easy but it has been impossible for me to continue moving forward,
Sorry for my bad English

Imagen Description

```<code>include('Login/Conexion.php');
$id = $_SESSION['id'];

$query = "with cte as (SELECT count(*) over() cnt FROM CardData where UserIndex = $id and CardIndex in (0, 1, 2)) delete from cte where cnt = 3";
$resultados = sqlsrv_query($conn,$query);

if($resultados){
    $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
    }
    else{
        echo 'Error';
        }
</code>```

答:
Solved:</p>

```<code>if($fila = sqlsrv_rows_affected($resultados)) {
 $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
}
else {
echo 'Error';
}
</code>```

Body:
What I want to do is first Select if the Cardindex Column has the values 0.1 and 2. with the same UserIndex (id) if those values exist (The 3 are mandatory), then we proceed to delete the 3 themselves and then Insert in the same table a new value. as long as the previous condition is met, if it is not met, it is not inserted.

In the query that I show the first query works well, it removes the data 0,1,2, until there everything is perfect, but then when inserting the new row it does it, but without respecting the previous condition. if in case it was not fulfilled it inserts it anyway.

It seems very easy but it has been impossible for me to continue moving forward,
Sorry for my bad English

Imagen Description

include('Login/Conexion.php');
$id = $_SESSION['id'];

$query = "with cte as (SELECT count(*) over() cnt FROM CardData where UserIndex = $id and CardIndex in (0, 1, 2)) delete from cte where cnt = 3";
$resultados = sqlsrv_query($conn,$query);

if($resultados){
    $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
    }
    else{
        echo 'Error';
        }

Body:
Solved:

if($fila = sqlsrv_rows_affected($resultados)) {
 $insert = sqlsrv_query($conn,"INSERT INTO CardData (UserIndex, CardIndex, Mode ) VALUES ('$id', '5' ,'1')");
}
else {
echo 'Error';
}


问:
HTTPTrigger Azure Function with CosmosDb input is not working after deployment
I have created below HttpTrigger function which takes CosmosDb item as input.  This code works perfectly fine on when run locally.  I am using Visual Studio Code to create function and deploying to Azure after successfully ran locally.  But it doesn't work on Azure, it doesn't give error or it seems it not getting any response.

```<code>public static class HttpTriggerWithCosmosDb
{
    [FunctionName("HttpTriggerWithCosmosDb")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerWithCosmosDb/{id}")] HttpRequest req,
        [CosmosDB(
            databaseName : "func-io-learn-db",
            collectionName : "Bookmarks",
            ConnectionStringSetting = "CosmosDBConnection",
            Id = "{id}",
            PartitionKey = "{id}"
        )] BookMarkItem item,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = item.Url;

        Console.Write( item.Id);

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}
</code>```

While publishing, in output I see below message:

HttpTriggerCSharp1:
  https://nps-func.azurewebsites.net/api/HttpTriggerCSharp1

  TestMessage: https://nps-func.azurewebsites.net/api/TestMessage
  5:33:02 PM nps-func: WARNING: Some http trigger urls cannot be
  displayed in the output window because they require an authentication
  token.

It is not showing This above function in response.

Update:
Full code can be found on Git

答:
I got the issue, what is happening here.  I had to manually add CosmosDBConnection to Azure with Azure Function:Add New Settings... command  before I publish the function.

I am new to function, I was not aware this is how app_settings need to be added.

Body:
I have created below HttpTrigger function which takes CosmosDb item as input.  This code works perfectly fine on when run locally.  I am using Visual Studio Code to create function and deploying to Azure after successfully ran locally.  But it doesn't work on Azure, it doesn't give error or it seems it not getting any response.

public static class HttpTriggerWithCosmosDb
{
    [FunctionName("HttpTriggerWithCosmosDb")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "HttpTriggerWithCosmosDb/{id}")] HttpRequest req,
        [CosmosDB(
            databaseName : "func-io-learn-db",
            collectionName : "Bookmarks",
            ConnectionStringSetting = "CosmosDBConnection",
            Id = "{id}",
            PartitionKey = "{id}"
        )] BookMarkItem item,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        string name = item.Url;

        Console.Write( item.Id);

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}

While publishing, in output I see below message:

HttpTriggerCSharp1:
  https://nps-func.azurewebsites.net/api/HttpTriggerCSharp1

  TestMessage: https://nps-func.azurewebsites.net/api/TestMessage
  5:33:02 PM nps-func: WARNING: Some http trigger urls cannot be
  displayed in the output window because they require an authentication
  token.

It is not showing This above function in response.

Update:
Full code can be found on Git


问:
Service crashes with exception: Faulting module name: MSVCR100.dll
For some reason service crashes with message in the event viewer saying "Faulting module name: MSVCR100.dll" no any other useful information. It kills the whole process. We can not find what causes this problem and can't catch this exception. We are not referencing this module in our source.
Service is running on Windows 7 64 bit .NET 4.</p>

答:
A quick Google search shows this to be a common error for a variety of applications. It also reveals this is a common underlying library.

I have a couple of potential suggestions, as a quick search revealed no firm answer that matches your issue exactly.

One possibility is this library is unregistered in Windows. This assumes it is COM based, of course. I don't think this is the first approach, but it is a possibility.

Another is a 64 bit issue. The most likely cause here would be a 32 bit service on a 64 bit OS. One potential method is to set up the service as 64 bit; the other would be ensure the DLL in question is being usable by WOW. This would most likely be plopping a copy of the DLL in SysWOW64.


问:
Reading a XML file in C++ with TinyXML2
I'm pretty new to using XML in C++ and i'm trying to parse a list of files to download.
THe XML file I'm using is generated via PHP and looks like this :

```<code><?xml version="1.0"?>
<FileList>
  <File Name="xxx" Path="xxx" MD5="xxx" SHA1="xxx"/>
</FileList>
</code>```

The code I'm using in C++ is the following, which I came up using some online tutorials (it's included in some global function):

```<code>tinyxml2::XMLDocument doc;

doc.LoadFile("file_listing.xml");
tinyxml2::XMLNode* pRoot = doc.FirstChild();
tinyxml2::XMLElement* pElement = pRoot->FirstChildElement("FileList");
if (pRoot == nullptr)
{
    QString text = QString::fromLocal8Bit("Error text in french");
    //other stuff
}
else
{
    tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");
    while (pListElement != nullptr)
    {
        QString pathAttr = QString::fromStdString(pListElement->Attribute("Path"));
        QString md5Attr = QString:: fromStdString(pListElement->Attribute("MD5"));
        QString sha1Attr = QString::fromStdString(pListElement->Attribute("SHA1"));

        QString currentPath = pathAttr.remove("path");
        QString currentMd5 = this->fileChecksum(currentPath, QCryptographicHash::Md5);
        QString currentSha1 = this->fileChecksum(currentPath, QCryptographicHash::Sha1);

        QFile currentFile(currentPath);

        if (md5Attr != currentMd5 || sha1Attr != currentSha1 || !currentFile.exists())
        {
            QString url = "url" + currentPath;
            this->downloadFile(url);
        }

        pListElement = pListElement->NextSiblingElement("File");
    }

</code>```

Problem is, I get an error like "Access violation, this was nullptr" on the following line :

tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");

Since I'm far from a pro when it comes to coding and I already searched the internet up and down, I hope that someone here can provide me some pointers.

Have a good day, folks.

答:
I don't know if you have C++17 available, but you can remove a lot of noise by using auto* and if-init-expressions (or rely on the fact that pointers can be implicitly converted to boolean values.)

The main issue with your code is you were not using XMLElement* but instead a XMLNode. The function tinyxml2::XMLDocument::RootElement() automatically gets the top-most element for you.

Because you have an xml declaration at the top, FirstChild returns that...which doesn't have any children, so the rest of the code fails.

By using RootElement tinyxml knows to skip any leading non-element nodes (comments, doctypes, etc.) and give you <FileList> instead.

    tinyxml2::XMLDocument doc;
    auto err = doc.LoadFile("file_listing.xml");
    if(err != tinyxml2::XML_SUCCESS) {
        //Could not load file. Handle appropriately.
    } else {
        if(auto* pRoot = doc.RootElement(); pRoot == nullptr) {
            QString text = QString::fromLocal8Bit("Error text in french");
            //other stuff
        } else {
            for(auto* pListElement = pRoot->FirstChildElement("File");
                pListElement != nullptr;
                pListElement = pListElement->NextSiblingElement("File"))
            {
                QString pathAttr = QString::fromStdString(pListElement->Attribute("Path"));
                QString md5Attr = QString:: fromStdString(pListElement->Attribute("MD5"));
                QString sha1Attr = QString::fromStdString(pListElement->Attribute("SHA1"));

                QString currentPath = pathAttr.remove("path");
                QString currentMd5 = this->fileChecksum(currentPath, QCryptographicHash::Md5);
                QString currentSha1 = this->fileChecksum(currentPath, QCryptographicHash::Sha1);

                QFile currentFile(currentPath);
                if(md5Attr != currentMd5 || sha1Attr != currentSha1 || !currentFile.exists()) {
                    QString url = "url" + currentPath;
                    this->downloadFile(url);
                }
            }
        }
    }

```

Title: Reading a XML file in C++ with TinyXML2

Body:
I'm pretty new to using XML in C++ and i'm trying to parse a list of files to download.
THe XML file I'm using is generated via PHP and looks like this :

<?xml version="1.0"?>
<FileList>
  <File Name="xxx" Path="xxx" MD5="xxx" SHA1="xxx"/>
</FileList>

The code I'm using in C++ is the following, which I came up using some online tutorials (it's included in some global function):

tinyxml2::XMLDocument doc;

doc.LoadFile("file_listing.xml");
tinyxml2::XMLNode* pRoot = doc.FirstChild();
tinyxml2::XMLElement* pElement = pRoot->FirstChildElement("FileList");
if (pRoot == nullptr)
{
    QString text = QString::fromLocal8Bit("Error text in french");
    //other stuff
}
else
{
    tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");
    while (pListElement != nullptr)
    {
        QString pathAttr = QString::fromStdString(pListElement->Attribute("Path"));
        QString md5Attr = QString:: fromStdString(pListElement->Attribute("MD5"));
        QString sha1Attr = QString::fromStdString(pListElement->Attribute("SHA1"));

        QString currentPath = pathAttr.remove("path");
        QString currentMd5 = this->fileChecksum(currentPath, QCryptographicHash::Md5);
        QString currentSha1 = this->fileChecksum(currentPath, QCryptographicHash::Sha1);

        QFile currentFile(currentPath);

        if (md5Attr != currentMd5 || sha1Attr != currentSha1 || !currentFile.exists())
        {
            QString url = "url" + currentPath;
            this->downloadFile(url);
        }

        pListElement = pListElement->NextSiblingElement("File");
    }

Problem is, I get an error like "Access violation, this was nullptr" on the following line :

tinyxml2::XMLElement* pListElement = pElement->FirstChildElement("File");

Since I'm far from a pro when it comes to coding and I already searched the internet up and down, I hope that someone here can provide me some pointers.

Have a good day, folks.


问:
Convert all the columns of a spark dataframe into a json format and then include the json formatted data as a column in another/parent dataframe
Converted dataframe(say child dataframe) into json using df.toJSON

After json conversion the schema looks like this :

```<code>root
 |-- value: string (nullable = true)
</code>```

I used the following suggestion to get child dataframe into the intermediate parent schema/dataframe:

```<code>scala> parentDF.toJSON.select(struct($"value").as("data")).printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
</code>```

Now I still need to build the parentDF schema further to make it look like:

```<code>root
 |-- id
 |-- version
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
</code>```

Q1) How can I build the id column using the id from value(i.e value.id needs to be represented as id)

Q2) I need to bring version from a different dataframe(say versionDF) where version is a constant(in all columns). Do I fetch one row from this versionDF to read value of version column and then populate it as literal in the parentDF ?

please help with any code snippets on this.

答:
Try this:</p>

```<code>scala> val versionDF = List((1.0)).toDF("version")
versionDF: org.apache.spark.sql.DataFrame = [version: double]

scala> versionDF.show
+-------+
|version|
+-------+
|    1.0|
+-------+

scala> val version = versionDF.first.get(0)
version: Any = 1.0

scala>

scala> val childDF = List((1,"a1","b1"),(2,"a2","b2"),(3,"a3","b3")).toDF("id","col1","col2")
childDF: org.apache.spark.sql.DataFrame = [id: int, col1: string ... 1 more field]

scala> childDF.show
+---+----+----+
| id|col1|col2|
+---+----+----+
|  1|  a1|  b1|
|  2|  a2|  b2|
|  3|  a3|  b3|
+---+----+----+

scala>

scala> val parentDF =  childDF.toJSON.select(struct($"value").as("data")).withColumn("id",from_json($"data.value",childDF.schema).getItem("id")).withColumn("version",lit(version))
parentDF: org.apache.spark.sql.DataFrame = [data: struct<value: string>, id: int ... 1 more field]

scala> parentDF.printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
 |-- id: integer (nullable = true)
 |-- version: double (nullable = false)

scala> parentDF.show(false)
+----------------------------------+---+-------+
|data                              |id |version|
+----------------------------------+---+-------+
|[{"id":1,"col1":"a1","col2":"b1"}]|1  |1.0    |
|[{"id":2,"col1":"a2","col2":"b2"}]|2  |1.0    |
|[{"id":3,"col1":"a3","col2":"b3"}]|3  |1.0    |
+----------------------------------+---+-------+
</code>```

Body:
Converted dataframe(say child dataframe) into json using df.toJSON

After json conversion the schema looks like this :

root
 |-- value: string (nullable = true)

I used the following suggestion to get child dataframe into the intermediate parent schema/dataframe:

scala> parentDF.toJSON.select(struct($"value").as("data")).printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)

Now I still need to build the parentDF schema further to make it look like:

root
 |-- id
 |-- version
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)

Q1) How can I build the id column using the id from value(i.e value.id needs to be represented as id)

Q2) I need to bring version from a different dataframe(say versionDF) where version is a constant(in all columns). Do I fetch one row from this versionDF to read value of version column and then populate it as literal in the parentDF ?

please help with any code snippets on this.

Body:
Try this:

scala> val versionDF = List((1.0)).toDF("version")
versionDF: org.apache.spark.sql.DataFrame = [version: double]

scala> versionDF.show
+-------+
|version|
+-------+
|    1.0|
+-------+

scala> val version = versionDF.first.get(0)
version: Any = 1.0

scala>

scala> val childDF = List((1,"a1","b1"),(2,"a2","b2"),(3,"a3","b3")).toDF("id","col1","col2")
childDF: org.apache.spark.sql.DataFrame = [id: int, col1: string ... 1 more field]

scala> childDF.show
+---+----+----+
| id|col1|col2|
+---+----+----+
|  1|  a1|  b1|
|  2|  a2|  b2|
|  3|  a3|  b3|
+---+----+----+

scala>

scala> val parentDF =  childDF.toJSON.select(struct($"value").as("data")).withColumn("id",from_json($"data.value",childDF.schema).getItem("id")).withColumn("version",lit(version))
parentDF: org.apache.spark.sql.DataFrame = [data: struct<value: string>, id: int ... 1 more field]

scala> parentDF.printSchema
root
 |-- data: struct (nullable = false)
 |    |-- value: string (nullable = true)
 |-- id: integer (nullable = true)
 |-- version: double (nullable = false)

scala> parentDF.show(false)
+----------------------------------+---+-------+
|data                              |id |version|
+----------------------------------+---+-------+
|[{"id":1,"col1":"a1","col2":"b1"}]|1  |1.0    |
|[{"id":2,"col1":"a2","col2":"b2"}]|2  |1.0    |
|[{"id":3,"col1":"a3","col2":"b3"}]|3  |1.0    |
+----------------------------------+---+-------+


问:
Write-Output inside Invoke-Command scriptblock
Below is a script I'm working on to get all SQL-jobs into a CSV-file.
The script itself is working great but I have trouble with the error-handling.
I can't figure out how to get the Out-File inside the Catch-block to print to the file on my local machine instead of the remote machine I'm running the Invoke-Command to.
How do I accomplish this?

Thanks

PS. The script is written out fully as much as possible for non experienced co-workers convenience

```<code>$sqlServers = @("TEST1","TEST2")

$filePath = [Environment]::GetFolderPath("Desktop")

$dateToday = Get-Date -Format “yyMMdd HH:mm"
$dateTodayFile = Get-Date -Format “yyMMdd"

Write-Output "$dateToday $sqlServers" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append

$output = Invoke-Command -ComputerName $sqlServers -ScriptBlock{

    Try
    {
        Import-Module sqlserver -ErrorAction Stop
    }
    Catch
    {
        Write-Output "$dateToday ERROR $env:computername" |
            Out-File "$filePath\Log$dateTodayFile.txt" -Append
        Exit
    }
    $instances = $env:computername | Foreach-Object {Get-ChildItem -Path "SQLSERVER:\SQL\$_"}

    ForEach ($instance in $instances){

        Try
        {
        $instanceName = $instance.InstanceName
        Get-SqlAgentJob -ServerInstance "$env:computername\$instanceName" -ErrorAction Stop |
            Where-Object {$_.IsEnabled -eq "True" -and $_.LastRunDate -gt [DateTime]::Today.AddDays(-2) -and $_.OwnerLoginName -match "TEST"} |
                Select-Object @{Name=‘Job name‘;Expression={$_.Name}},
                    @{Name=‘Description‘;Expression={$_.Description}},
                    @{Name=‘Instance‘;Expression={$_.Parent -Replace '[][]'}},
                    @{Name=‘Run outcome‘;Expression={$_.LastRunOutcome}},
                    @{Name=‘Run date‘;Expression={$_.LastRunDate}},
                    @{Name=‘Run duration‘;Expression={$_.LastRunDuration}},
                    @{Name=‘Job creator‘;Expression={$_.OwnerLoginName}},
                    @{Name=‘Runs on a schedule‘;Expression={$_.HasSchedule}},
                    @{Name='Schedule Type';Expression={$_.JobSchedules -join ','}}
        }
        Catch
        {
            Write-Output "$dateToday ERROR $env:computername\$instanceName" |
                Out-File "$filePath\Log$dateTodayFile.txt" -Append
            Exit
        }
    }
}
$output | Select-Object -Property * -ExcludeProperty PSComputerName,RunSpaceID,PSShowComputerName |
    Sort-Object "Job name" |
        Export-Csv $filePath\SQLJobInvent$dateTodayFile.csv -NoTypeInformation -Delimiter ";" -Encoding UTF8

Write-Output "$dateToday $filePath" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append
Write-Output "----------------------------------------" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append
</code>```

答:
Your primary issue is scope.

The $dateToday, $filePath and $dateTodayFile are all declared on the local machine, but you're trying to use them on the remote computer (script block) where they are undefined.

There are a few ways to get your variables passed to the remote computer, below are two:

# Add desired variable to ArgumentList and define it as a parameter
Invoke-Command -ComputerName $sqlServers -ArgumentList $dateToday,$filePath,$dateTodayFile -ScriptBlock {
  param(
    $folderPath,
    $filePath,
    $dateTodayFile
  )
  # Do something with our injected variables
  Write-Output "$dateToday ERROR $env:computername" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append
}
```

<p>OR</p>

<pre class="lang-bsh prettyprint-override"><code># In PS ver >= 3.0 we can use 'using'
Invoke-Command -ComputerName $serverName -ScriptBlock {Write-Output $using:dateToday}
</code>```

Body:
Below is a script I'm working on to get all SQL-jobs into a CSV-file.
The script itself is working great but I have trouble with the error-handling.
I can't figure out how to get the Out-File inside the Catch-block to print to the file on my local machine instead of the remote machine I'm running the Invoke-Command to.
How do I accomplish this?

Thanks

PS. The script is written out fully as much as possible for non experienced co-workers convenience

$sqlServers = @("TEST1","TEST2")

$filePath = [Environment]::GetFolderPath("Desktop")

$dateToday = Get-Date -Format “yyMMdd HH:mm"
$dateTodayFile = Get-Date -Format “yyMMdd"

Write-Output "$dateToday $sqlServers" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append

$output = Invoke-Command -ComputerName $sqlServers -ScriptBlock{

    Try
    {
        Import-Module sqlserver -ErrorAction Stop
    }
    Catch
    {
        Write-Output "$dateToday ERROR $env:computername" |
            Out-File "$filePath\Log$dateTodayFile.txt" -Append
        Exit
    }
    $instances = $env:computername | Foreach-Object {Get-ChildItem -Path "SQLSERVER:\SQL\$_"}

    ForEach ($instance in $instances){

        Try
        {
        $instanceName = $instance.InstanceName
        Get-SqlAgentJob -ServerInstance "$env:computername\$instanceName" -ErrorAction Stop |
            Where-Object {$_.IsEnabled -eq "True" -and $_.LastRunDate -gt [DateTime]::Today.AddDays(-2) -and $_.OwnerLoginName -match "TEST"} |
                Select-Object @{Name=‘Job name‘;Expression={$_.Name}},
                    @{Name=‘Description‘;Expression={$_.Description}},
                    @{Name=‘Instance‘;Expression={$_.Parent -Replace '[][]'}},
                    @{Name=‘Run outcome‘;Expression={$_.LastRunOutcome}},
                    @{Name=‘Run date‘;Expression={$_.LastRunDate}},
                    @{Name=‘Run duration‘;Expression={$_.LastRunDuration}},
                    @{Name=‘Job creator‘;Expression={$_.OwnerLoginName}},
                    @{Name=‘Runs on a schedule‘;Expression={$_.HasSchedule}},
                    @{Name='Schedule Type';Expression={$_.JobSchedules -join ','}}
        }
        Catch
        {
            Write-Output "$dateToday ERROR $env:computername\$instanceName" |
                Out-File "$filePath\Log$dateTodayFile.txt" -Append
            Exit
        }
    }
}
$output | Select-Object -Property * -ExcludeProperty PSComputerName,RunSpaceID,PSShowComputerName |
    Sort-Object "Job name" |
        Export-Csv $filePath\SQLJobInvent$dateTodayFile.csv -NoTypeInformation -Delimiter ";" -Encoding UTF8

Write-Output "$dateToday $filePath" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append
Write-Output "----------------------------------------" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append

Body:
Your primary issue is scope.

The $dateToday, $filePath and $dateTodayFile are all declared on the local machine, but you're trying to use them on the remote computer (script block) where they are undefined.

There are a few ways to get your variables passed to the remote computer, below are two:

# Add desired variable to ArgumentList and define it as a parameter
Invoke-Command -ComputerName $sqlServers -ArgumentList $dateToday,$filePath,$dateTodayFile -ScriptBlock {
  param(
    $folderPath,
    $filePath,
    $dateTodayFile
  )
  # Do something with our injected variables
  Write-Output "$dateToday ERROR $env:computername" |
    Out-File "$filePath\Log$dateTodayFile.txt" -Append
}

OR

# In PS ver >= 3.0 we can use 'using'
Invoke-Command -ComputerName $serverName -ScriptBlock {Write-Output $using:dateToday}


问:
PyCharm SonarLint How to view all issues across all files?
In Pycharm, you can view the SonarLint issues in a single file by opening the file and clicking on the SonarLint tab on the bottom of the IDE.

However, this only shows the issues for a single file.

How can you view all the SonarLint issues across all files within a single project?

答: In the project panel, right click on the root directory, then navigate through Sonar Lint>Analyze with Sonar Lint.</p>


问:
spying an array element with mockito returns wanted but not invoked when the method is invoked
**UPDATE : I have misunderstood the way spys function completely, I should be calling the spy version of a method in order for it to be verified NOT the real object method Ex : r.getPrice(); then verify(r).getPrice(); I still haven't figured the right way to get what i want but i thought i have to ask if i should delete this question ?

I'm spying an array element like this

```<code>@Test
public void testMakeCoffee_1() {
    Recipe r = spy(stubRecipies[0]);

    assertEquals(25,coffeeMaker.makeCoffee(0, 75)); // first index

            verify(r).getPrice();
});
</code>```

this is the implementation of the makeCoffee method

```<code>public synchronized int makeCoffee(int recipeToPurchase, int amtPaid) {
    int change = 0;

    if (getRecipes()[recipeToPurchase] == null) {
        change = amtPaid;
    } else if (getRecipes()[recipeToPurchase].getPrice() <= amtPaid) {
        if (inventory.useIngredients(getRecipes()[recipeToPurchase])) {
            change = amtPaid - getRecipes()[recipeToPurchase].getPrice();
        } else {
            change = amtPaid;
        }
    } else {
        change = amtPaid;
    }

    return change;
}
</code>```

getRecipes() implementation inside CoffeeMaker class

```<code>public synchronized Recipe[] getRecipes() {
    return recipeBook.getRecipes();
}
</code>```

RecipeBook is a mocked class, stubRecipies is an array that contains my custom recipes to test and getRecipes() of the RecipeBook class is stubbed like this

```<code>recipeBookStub = mock(RecipeBook.class);
stubRecipies = new Recipe [] {recipe1, recipe2, recipe3};
when(recipeBookStub.getRecipes()).thenReturn(stubRecipies);
</code>```

getRecipes() should return the list of recipes, hence replacing it with my array of recipes stubRecipies.

however when i call verify method of mockito on the getPrice() method of the spy object stubRecipies[0] i get a 'wanted but not invoked error' how is it possible that the method is not invoked, knowing that the usage above returns the correct value.

** edit : i tried manually calling recipe1.getPrice() and still i got 'wanted but not invoked error' , but when i called r.getPrice() the test passed which is weird because i thought a spy object is supposed to capture the interactions with the real object.

答:
So from looking at your question and the comments, there are a few things I would recommend to take this forward.

So without seeing the entire code, I can not 100% sure if this is returning the expected Recipe[]

```<code>public synchronized Recipe[] getRecipes() {
    return recipeBook.getRecipes();
}
</code>```

You should be injecting your mocked recipeBookStub into your CoffeeMaker.

Typically when writing code in a TDD style we start with the most basic case in this case I would try out the method until oyu can get your method passing:

```<code>public int makeCoffee(int recipeToPurchase, int amtPaid) {
   getRecipes()[recipeToPurchase]getPrice();
   return 25;
}
</code>```

Another good practice thing is to use as little logic in your test as possible.

rather the:

```<code>Recipe r = spy(stubRecipies[0]);
</code>```

try:

```<code>Recipe r = spy(recipe1);
</code>```

More significantly, the spied object is not being used in CoffeeMaker:

```<code>Recipe r = spy(stubRecipies[0]);
</code>```

r is the mock, and is not the same object as in your array, you can quickly prove this with:

```<code>Assert.assertEquals(stubRecipies[0], r);
Assert.assertTrue(stubRecipies[0]== r);
</code>```

the assertTrue will fail, meaning that stubRecipies[0] is not the same object as the spy (r)

if you set the first index in the array to equal your spied object you might find things work better

Body:
**UPDATE : I have misunderstood the way spys function completely, I should be calling the spy version of a method in order for it to be verified NOT the real object method Ex : r.getPrice(); then verify(r).getPrice(); I still haven't figured the right way to get what i want but i thought i have to ask if i should delete this question ?

I'm spying an array element like this

@Test
public void testMakeCoffee_1() {
    Recipe r = spy(stubRecipies[0]);

    assertEquals(25,coffeeMaker.makeCoffee(0, 75)); // first index

            verify(r).getPrice();
});

this is the implementation of the makeCoffee method

public synchronized int makeCoffee(int recipeToPurchase, int amtPaid) {
    int change = 0;

    if (getRecipes()[recipeToPurchase] == null) {
        change = amtPaid;
    } else if (getRecipes()[recipeToPurchase].getPrice() <= amtPaid) {
        if (inventory.useIngredients(getRecipes()[recipeToPurchase])) {
            change = amtPaid - getRecipes()[recipeToPurchase].getPrice();
        } else {
            change = amtPaid;
        }
    } else {
        change = amtPaid;
    }

    return change;
}

getRecipes() implementation inside CoffeeMaker class

public synchronized Recipe[] getRecipes() {
    return recipeBook.getRecipes();
}

RecipeBook is a mocked class, stubRecipies is an array that contains my custom recipes to test and getRecipes() of the RecipeBook class is stubbed like this

recipeBookStub = mock(RecipeBook.class);
stubRecipies = new Recipe [] {recipe1, recipe2, recipe3};
when(recipeBookStub.getRecipes()).thenReturn(stubRecipies);

getRecipes() should return the list of recipes, hence replacing it with my array of recipes stubRecipies.

however when i call verify method of mockito on the getPrice() method of the spy object stubRecipies[0] i get a 'wanted but not invoked error' how is it possible that the method is not invoked, knowing that the usage above returns the correct value.

** edit : i tried manually calling recipe1.getPrice() and still i got 'wanted but not invoked error' , but when i called r.getPrice() the test passed which is weird because i thought a spy object is supposed to capture the interactions with the real object.

Body:
So from looking at your question and the comments, there are a few things I would recommend to take this forward.

So without seeing the entire code, I can not 100% sure if this is returning the expected Recipe[]

public synchronized Recipe[] getRecipes() {
    return recipeBook.getRecipes();
}

You should be injecting your mocked recipeBookStub into your CoffeeMaker.

Typically when writing code in a TDD style we start with the most basic case in this case I would try out the method until oyu can get your method passing:

public int makeCoffee(int recipeToPurchase, int amtPaid) {
   getRecipes()[recipeToPurchase]getPrice();
   return 25;
}

Another good practice thing is to use as little logic in your test as possible.

rather the:

Recipe r = spy(stubRecipies[0]);

try:

Recipe r = spy(recipe1);

More significantly, the spied object is not being used in CoffeeMaker:

Recipe r = spy(stubRecipies[0]);

r is the mock, and is not the same object as in your array, you can quickly prove this with:

Assert.assertEquals(stubRecipies[0], r);
Assert.assertTrue(stubRecipies[0]== r);

the assertTrue will fail, meaning that stubRecipies[0] is not the same object as the spy (r)

if you set the first index in the array to equal your spied object you might find things work better


问:
Can the HWND from CreateWindow/CreateDialog be GetMessage'd from another thread?
Using the Win32 APIs, is it possible to create a Window or Dialog in one thread then collect events for it from another thread?

Are HWNDs tied to threads?

Trying the contrived example below I never see GetMessage() fire.

```
HWND g_hWnd;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}
```

But here, I do.

```
HWND g_hWnd;
HINSTANCE g_hInstance;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);

    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    g_hInstance = hInstance;
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}
```

Can somebody explain what I'm seeing?

答: Use AttachThreadInput.</p>

OwnerDisplayName: Joby Taffey

ContentLicense: CC BY-SA 2.5

Body:
Using the Win32 APIs, is it possible to create a Window or Dialog in one thread then collect events for it from another thread?

Are HWNDs tied to threads?

Trying the contrived example below I never see GetMessage() fire.

HWND g_hWnd;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

But here, I do.

HWND g_hWnd;
HINSTANCE g_hInstance;

DWORD WINAPI myThreadProc(LPVOID lpParam)
{
    hWnd = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_MYDIALOG), 0, myDlgProc);

    while(GetMessage(&msg, hWnd, 0, 0) > 0)
    {
       ...
    }

}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
    g_hInstance = hInstance;
    CreateThread(NULL, 0 myThreadProc, NULL, 0, NULL);
    ...
}

Can somebody explain what I'm seeing?

LastEditorDisplayName: Joby Taffey

Body: Use AttachThreadInput.

OwnerDisplayName: Valentin Galea


问:
How to access Bluetooth device after receiving ACTION_ACL_CONNECTED
I'm connecting to a Bluetooth device using connectGatt() with autoConnect=true. If the connection is lost and the device re-appears and re-connects, I get an ACL_CONNECTED intent from my BroadcastReceiver. However, I'm not clear on how I'm supposed to access the device to write/read data at this point.

Normally, I call connectGatt() with a BluetoothGattCallback. When the device is connected, the bluetooth stack gives me a BluetoothGatt which I can then use to access the device (e.g. BluetoothGatt.discoverServices()`.

But with autoconnect, when I receive ACTION_ACL_CONNECTED the device is already connected. If I call connectGatt() again, the stack ends up returning two copies of everything, so I think I shouldn't call connectGatt() again. However, if I don't, how I do get a BluetoothGatt object to access the device?

答: It turns out calling connectGatt() is the correct thing to do. The reason I was getting multiple copies is because the previous BluetoothGatt object lingered around. In order to allow auto-connect to work, that first BluetoothGatt object had to be kept. What worked for me is to keep that object until I get ACL_CONNECTED, close that object, and then create a new callback.


问:
How to check if a variable is in specific range
I have a list of lists that looks like this:

```<code> mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]
</code>```

What I am trying to do is to take a number provided by the user and then check if the number provided is equal or in a range of +0.6 compared to the second element of each sublist. In other words I want to do the following: if user input is 3.4 then I want to check based on the example provided of list of lists these two numbers: 3.4207362518089726 and 2.9687393162393163 and if these numbers are in range of +0.6 from the input, then to save the whole sublist in another list.

So, user_input = 3.4, mylists[0][1] = 3.4207362518089726, mylists[1][1] = 2.9687393162393163 and I want to place in a new list each sublist that has 3.4 and above, till 4.0 (due to range of + 0.6)

What I thought was this:

```<code>for i in range(0, len(mylists)):
        if mylists[i][1] >= user_input + 0.6:
             new_list.append(mylists[i])
</code>```

But of course this did not work.

答:
You can use this:

```<code>import re

mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

user_input = 3.4

st = str(user_input) #transform input from user to string

denom = '1'+len(st.split('.')[-1])*'0' #get how much decimals st have and create denominator to the decimal part

decimal_part = 1- int(st.split('.')[-1])/int(denom) #create decimal numbers  to reach upper bound

new_list = []

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= user_input + decimal_part:
         new_list.append(mylists[i])
</code>```

Another way is:

```<code>import numpy as np

mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

user_input = 3.4

new_list = []

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= np.ceil(user_input):
         new_list.append(mylists[i])
</code>```

Body:
I have a list of lists that looks like this:

 mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

What I am trying to do is to take a number provided by the user and then check if the number provided is equal or in a range of +0.6 compared to the second element of each sublist. In other words I want to do the following: if user input is 3.4 then I want to check based on the example provided of list of lists these two numbers: 3.4207362518089726 and 2.9687393162393163 and if these numbers are in range of +0.6 from the input, then to save the whole sublist in another list.

So, user_input = 3.4, mylists[0][1] = 3.4207362518089726, mylists[1][1] = 2.9687393162393163 and I want to place in a new list each sublist that has 3.4 and above, till 4.0 (due to range of + 0.6)

What I thought was this:

for i in range(0, len(mylists)):
        if mylists[i][1] >= user_input + 0.6:
             new_list.append(mylists[i])

But of course this did not work.

Body:
You can use this:

import re

mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

user_input = 3.4

st = str(user_input) #transform input from user to string

denom = '1'+len(st.split('.')[-1])*'0' #get how much decimals st have and create denominator to the decimal part

decimal_part = 1- int(st.split('.')[-1])/int(denom) #create decimal numbers  to reach upper bound

new_list = []

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= user_input + decimal_part:
         new_list.append(mylists[i])

Another way is:

import numpy as np

mylists =   [[['CS105', 'ENG101', 'MATH101', 'GER'], 3.4207362518089726, 0.2808766238976195], [['CS105', 'ENG101', 'GER', 'GER'], 2.9687393162393163, 0.3408964829117446]]

user_input = 3.4

new_list = []

for i in range(0, len(mylists)):
    if user_input <= mylists[i][1] <= np.ceil(user_input):
         new_list.append(mylists[i])


问:
AWS Appsync implementation using GraphQL-client library in .Net
I am trying to implement an app sync subscription similar to this python example but in .net https://aws.amazon.com/blogs/mobile/appsync-websockets-python/

I started this using the nuget package GraphQL.Client https://www.nuget.org/packages/GraphQL.Client
The execution of Query/Mutation is working fine like given in the readme of https://github.com/graphql-dotnet/graphql-client
But subscription is not working.

My code using the GraphQL.Client:

```<code>using var graphQLClient = new GraphQLHttpClient("https://<MY-API-PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql", new NewtonsoftJsonSerializer());

 graphQLClient.HttpClient.DefaultRequestHeaders.Add("host", "<API HOST without https or absolute path and 'realtime-' text in the api address>"); //As given in the python example

graphQLClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", "<API KEY>");
var req= new GraphQLRequest
{
    Query = @"subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}",
    Variables = new{}
};

IObservable<GraphQLResponse<Response>> subscriptionStream = graphQLClient.CreateSubscriptionStream<Response>(req, (Exception ex) =>
{
      Console.WriteLine("Error: {0}", ex.ToString());
});

var subscription = subscriptionStream.Subscribe(response =>
{
                Console.WriteLine($"Response'{Newtonsoft.Json.JsonConvert.SerializeObject(response)}' ");
},
ex =>
{
Console.WriteLine("Error{0}", ex.ToString());
});
</code>```

Its giving the exception "The remote party closed the WebSocket connection without completing the close handshake."

stack trace:

at System.Net.WebSockets.ManagedWebSocket.d__662.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at GraphQL.Client.Http.Websocket.GraphQLHttpWebSocket.d__40.MoveNext() in C:\Users\UserName\Source\repos\graphql-client\src\GraphQL.Client\Websocket\GraphQLHttpWebSocket.cs:line 546

Then I tried without this nuget and using standard websocket

Code without nuget:

```<code>static public async Task CallWebsocket()
        {
            try
            {
                _client = new ClientWebSocket();
                _client.Options.AddSubProtocol("graphql-ws");
                _client.Options.SetRequestHeader("host", "<HOST URL without wss but now with 'realtime' text in api url because otherwise we are getting SSL error>");
                _client.Options.SetRequestHeader("x-api-key", "<API KEY>");

                await _client.ConnectAsync(new Uri("https://<MY-APPSYNC_API_PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql"), CancellationToken.None);
                await SendCommand();
                var docList = await Receive();
            }
            catch(Exception ex)
            {

            }
        }

       static  private async Task SendCommand()
        {
            ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("'query' : 'subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}'"));
            await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
        }
        static private async Task<string> Receive()
        {
            var receiveBufferSize = 1536;
            byte[] buffer = new byte[receiveBufferSize];
            var result = await _client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            var resultJson = (new UTF8Encoding()).GetString(buffer);
            return resultJson;
        }
</code>```

I am getting below exception:

Inner exception: "An established connection was aborted by the software in your host machine."

Inner exception message: "Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.."

Message: "The remote party closed the WebSocket connection without completing the close handshake."

Could anyone please help with the correct implementation.

答:
For others who face same issues, I have created a nuget package now.
https://www.nuget.org/packages/DotNetCSharp.AWS.AppSync.Client/1.1.1
You can use it as below.</p>
```<code>//Create Client Specify eithen APIKey or AuthToken
var Client = new AppSyncClient("<Appsync URL>", new AuthOptions()
{
// APIKey = "<API Key>",
AuthToken = "<JWT Token>"
});

//To Subscribe an query
Guid newId = Guid.NewGuid();
await Client.CreateSubscriptionAsync<Message>(new QueryOptions()
{
Query = "subscription <Subscription Query>",
SubscriptionId = newId
},
(data) =>
{

});

//To unsubscribe an subscription
await Client.UnSubscribe(newId);

//To close the websocket
await Client.Close();
</code>```

Body:
I am trying to implement an app sync subscription similar to this python example but in .net https://aws.amazon.com/blogs/mobile/appsync-websockets-python/

I started this using the nuget package GraphQL.Client https://www.nuget.org/packages/GraphQL.Client
The execution of Query/Mutation is working fine like given in the readme of https://github.com/graphql-dotnet/graphql-client
But subscription is not working.

My code using the GraphQL.Client:

using var graphQLClient = new GraphQLHttpClient("https://<MY-API-PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql", new NewtonsoftJsonSerializer());

 graphQLClient.HttpClient.DefaultRequestHeaders.Add("host", "<API HOST without https or absolute path and 'realtime-' text in the api address>"); //As given in the python example

graphQLClient.HttpClient.DefaultRequestHeaders.Add("x-api-key", "<API KEY>");
var req= new GraphQLRequest
{
    Query = @"subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}",
    Variables = new{}
};

IObservable<GraphQLResponse<Response>> subscriptionStream = graphQLClient.CreateSubscriptionStream<Response>(req, (Exception ex) =>
{
      Console.WriteLine("Error: {0}", ex.ToString());
});

var subscription = subscriptionStream.Subscribe(response =>
{
                Console.WriteLine($"Response'{Newtonsoft.Json.JsonConvert.SerializeObject(response)}' ");
},
ex =>
{
Console.WriteLine("Error{0}", ex.ToString());
});

Its giving the exception "The remote party closed the WebSocket connection without completing the close handshake."

stack trace:

at System.Net.WebSockets.ManagedWebSocket.d__662.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at GraphQL.Client.Http.Websocket.GraphQLHttpWebSocket.d__40.MoveNext() in C:\Users\UserName\Source\repos\graphql-client\src\GraphQL.Client\Websocket\GraphQLHttpWebSocket.cs:line 546

Then I tried without this nuget and using standard websocket

Code without nuget:

static public async Task CallWebsocket()
        {
            try
            {
                _client = new ClientWebSocket();
                _client.Options.AddSubProtocol("graphql-ws");
                _client.Options.SetRequestHeader("host", "<HOST URL without wss but now with 'realtime' text in api url because otherwise we are getting SSL error>");
                _client.Options.SetRequestHeader("x-api-key", "<API KEY>");

                await _client.ConnectAsync(new Uri("https://<MY-APPSYNC_API_PATH>.appsync-realtime-api.<AWS-region>.amazonaws.com/graphql"), CancellationToken.None);
                await SendCommand();
                var docList = await Receive();
            }
            catch(Exception ex)
            {

            }
        }

       static  private async Task SendCommand()
        {
            ArraySegment<byte> outputBuffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes("'query' : 'subscription SubscribeToEventComments{ subscribeToEventComments(eventId: 'test'){  content }}'"));
            await _client.SendAsync(outputBuffer, WebSocketMessageType.Text, true, CancellationToken.None);
        }
        static private async Task<string> Receive()
        {
            var receiveBufferSize = 1536;
            byte[] buffer = new byte[receiveBufferSize];
            var result = await _client.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
            var resultJson = (new UTF8Encoding()).GetString(buffer);
            return resultJson;
        }

I am getting below exception:

Inner exception: "An established connection was aborted by the software in your host machine."

Inner exception message: "Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.."

Message: "The remote party closed the WebSocket connection without completing the close handshake."

Could anyone please help with the correct implementation.

Body:
For others who face same issues, I have created a nuget package now.
https://www.nuget.org/packages/DotNetCSharp.AWS.AppSync.Client/1.1.1
You can use it as below.

//Create Client Specify eithen APIKey or AuthToken
var Client = new AppSyncClient("<Appsync URL>", new AuthOptions()
{
// APIKey = "<API Key>",
AuthToken = "<JWT Token>"
});

//To Subscribe an query
Guid newId = Guid.NewGuid();
await Client.CreateSubscriptionAsync<Message>(new QueryOptions()
{
Query = "subscription <Subscription Query>",
SubscriptionId = newId
},
(data) =>
{

});

//To unsubscribe an subscription
await Client.UnSubscribe(newId);

//To close the websocket
await Client.Close();


问:
ActiveSupport::MessageVerifier::InvalidSignature: ActiveSupport::MessageVerifier::InvalidSignature Error in rails 5
Before migrating to rails 5 it was working nicely, but when I migrated to rails 5.1.1 it is giving me error like

ActiveSupport::MessageVerifier::InvalidSignature:
  ActiveSupport::MessageVerifier::InvalidSignature

I have used same key that we were using in the previous version of rails.

Ex.

```<code>crypt = ActiveSupport::MessageEncryptor.new(Rails.configuration.secret_key_base)
</code>```

After executing following line I am getting the mentioned error.

```<code>@password = crypt.decrypt_and_verify(User.last.encryptedpass)
</code>```

答: In my case I was using form_tag to send the image to the backend. Using form_with solved my problem.

Body:
Before migrating to rails 5 it was working nicely, but when I migrated to rails 5.1.1 it is giving me error like

ActiveSupport::MessageVerifier::InvalidSignature:
  ActiveSupport::MessageVerifier::InvalidSignature

I have used same key that we were using in the previous version of rails.

Ex.

crypt = ActiveSupport::MessageEncryptor.new(Rails.configuration.secret_key_base)

After executing following line I am getting the mentioned error.

@password = crypt.decrypt_and_verify(User.last.encryptedpass)


问:
From PowerShell Get Refresh History In Group from Power BI REST APIs and export do CSV
I'm trying to get the PowerBI update history through the API URL through Powershell and export do CSV, I don't know much about Powershell but I'm trying to learn, since it's being very useful in the BI area where I work, I've tried to run the code through this site POWERBI SCHEDULED REFRESHES IN YOUR ORGANIZATION and also tried to edit to extract but with no success.

The site script runs without errors but does not return any results in CSV, is it because the URL is wrong?

Website script:

```<code>$myCred = Get-Credential
Connect-PowerBIServiceAccount -Credential $myCred

$Workspaces = Get-PowerBIWorkspace
$ExportFile =  "D:\Users\F02579\Documents\PowerBIRefreshHistory.csv"
Remove-Item $ExportFile -Force -ErrorAction SilentlyContinue

foreach($workspace in $Workspaces)
{

    $DataSets = Get-PowerBIDataset -WorkspaceId $workspace.Id | where {$_.isRefreshable -eq $true}
    foreach($dataset in $DataSets)
    {

        $URI = "groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
        #$OutFile = $ExportFolder + '\' + $workspace.Name + '-' + $dataset.Name + '.json'
        $Results = Invoke-PowerBIRestMethod -Url $URI -Method Get | ConvertFrom-Json

        foreach($result in $Results.value)
        {
            $errorDetails = $result.serviceExceptionJson | ConvertFrom-Json -ErrorAction SilentlyContinue

            $row = New-Object psobject
            $row | Add-Member -Name "Workspace" -Value $workspace.Name -MemberType NoteProperty
            $row | Add-Member -Name "Dataset" -Value $dataset.Name -MemberType NoteProperty
            $row | Add-Member -Name "refreshType" -Value $result.refreshType -MemberType NoteProperty
            $row | Add-Member -Name "startTime" -Value $result.startTime -MemberType NoteProperty
            $row | Add-Member -Name "endTime" -Value $result.endTime -MemberType NoteProperty
            $row | Add-Member -Name "status" -Value $result.status -MemberType NoteProperty
            $row | Add-Member -Name "errorCode" -Value $errorDetails.errorCode -MemberType NoteProperty
            $row | Add-Member -Name "errorDescription" -Value $errorDetails.errorDescription -MemberType NoteProperty
            $row | Export-Csv -Path $ExportFile -Append -Delimiter ';' -NoTypeInformation
        }

    }

}
</code>```

I tried to put the URL that Microsoft provides in this link, but also without success.

My script:

```<code>Import-Module MicrosoftPowerBIMgmt.Admin

$myCred = Get-Credential
Connect-PowerBIServiceAccount -Credential $myCred

$Session = New-PSSession -ConfigurationName Microsoft.Exchange `
    -ConnectionUri https://outlook.office365.com/powershell-liveid/ `
    -Credential $credential `
    -Authentication Basic `
    -AllowRedirection

Import-PSSession $Session

$Workspaces = Get-PowerBIWorkspace -Scope Organization -All
#Remove-Item $ExportFile -Force -ErrorAction SilentlyContinue

$DataSets =
ForEach ($workspace in $Workspaces)
    {
    Write-Host $workspace.Name
    ForEach ($dataset in (Get-PowerBIDataset -Scope Organization -WorkspaceId $workspace.Id))
        {
            #$URI = "groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
            $URI = "https://api.powerbi.com/v1.0/myorg/groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
            #$OutFile = $ExportFolder + '\' + $workspace.Name + '-' + $dataset.Name + '.json'
            $Results = Invoke-PowerBIRestMethod -Url $URI -Method Get | ConvertFrom-Json

            foreach($result in $Results.value)
            {
                $errorDetails = $result.serviceExceptionJson | ConvertFrom-Json -ErrorAction SilentlyContinue

                $ItemResult = New-Object System.Object
                $ItemResult | Add-Member -type NoteProperty -name WorkspaceID           -value $workspace.Id
                $ItemResult | Add-Member -type NoteProperty -name DatasetID             -value $dataset.Id
                $ItemResult | Add-Member -type NoteProperty -name RefreshID             -value $result.Id
                $ItemResult | Add-Member -type NoteProperty -name RequestId             -value $result.requestId
                $ItemResult | Add-Member -type NoteProperty -name RefresheType          -Value $result.refreshType
                $ItemResult | Add-Member -type NoteProperty -name StartTime             -Value $result.startTime
                $ItemResult | Add-Member -type NoteProperty -name EndTime               -Value $result.endTime
                $ItemResult | Add-Member -type NoteProperty -name Status                -Value $result.status
                $ItemResult | Add-Member -type NoteProperty -name ErrorCode             -Value $errorDetails.errorCode
                $ItemResult | Add-Member -type NoteProperty -name ErrorDescription      -Value $errorDetails.errorDescription

                # Put the item result and append it to the result object
                $Result +=$ItemResult
            }
        }
    }
$DataSets | Export-Csv "D:\Users\F02579\Documents\PowerBIRefreshHistory.csv" -NoTypeInformation -Encoding UTF8

Remove-PSSession $Session

Disconnect-PowerBIServiceAccount
</code>```

Error on my scripp:

答:
After making some calls with Microsoft, with some engineers that works with PowerBI and Powershell conector, I'm now able to get those information.

Powershell script:

```<code>$authUrl = "https://login.windows.net/common/oauth2/token/"
$clientId = "Your clientID"
$pbiUsername = "Your user email"
$pbiPassword = "Your password"

$body = @{
    "resource" = “https://analysis.windows.net/powerbi/api";
    "client_id" = $clientId;
    "grant_type" = "password";
    "username" = $pbiUsername;
    "password" = $pbiPassword;
    "scope" = "openid"
}
$authResponse = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body

$DatasetID = "Your datasetID"
$restURL = "https://api.powerbi.com/v1.0/myorg/datasets/$DatasetID/refreshes"

$headers = @{
    "Content-Type" = "application/json";
    "Authorization" = $authResponse.token_type + " " + $authResponse.access_token
}

$restResponse = Invoke-RestMethod -Uri $restURL –Method GET -Headers $headers | Select-Object -ExpandProperty value
$restResponse
</code>```

Body:
I'm trying to get the PowerBI update history through the API URL through Powershell and export do CSV, I don't know much about Powershell but I'm trying to learn, since it's being very useful in the BI area where I work, I've tried to run the code through this site POWERBI SCHEDULED REFRESHES IN YOUR ORGANIZATION and also tried to edit to extract but with no success.

The site script runs without errors but does not return any results in CSV, is it because the URL is wrong?

Website script:

$myCred = Get-Credential
Connect-PowerBIServiceAccount -Credential $myCred

$Workspaces = Get-PowerBIWorkspace
$ExportFile =  "D:\Users\F02579\Documents\PowerBIRefreshHistory.csv"
Remove-Item $ExportFile -Force -ErrorAction SilentlyContinue

foreach($workspace in $Workspaces)
{

    $DataSets = Get-PowerBIDataset -WorkspaceId $workspace.Id | where {$_.isRefreshable -eq $true}
    foreach($dataset in $DataSets)
    {

        $URI = "groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
        #$OutFile = $ExportFolder + '\' + $workspace.Name + '-' + $dataset.Name + '.json'
        $Results = Invoke-PowerBIRestMethod -Url $URI -Method Get | ConvertFrom-Json

        foreach($result in $Results.value)
        {
            $errorDetails = $result.serviceExceptionJson | ConvertFrom-Json -ErrorAction SilentlyContinue

            $row = New-Object psobject
            $row | Add-Member -Name "Workspace" -Value $workspace.Name -MemberType NoteProperty
            $row | Add-Member -Name "Dataset" -Value $dataset.Name -MemberType NoteProperty
            $row | Add-Member -Name "refreshType" -Value $result.refreshType -MemberType NoteProperty
            $row | Add-Member -Name "startTime" -Value $result.startTime -MemberType NoteProperty
            $row | Add-Member -Name "endTime" -Value $result.endTime -MemberType NoteProperty
            $row | Add-Member -Name "status" -Value $result.status -MemberType NoteProperty
            $row | Add-Member -Name "errorCode" -Value $errorDetails.errorCode -MemberType NoteProperty
            $row | Add-Member -Name "errorDescription" -Value $errorDetails.errorDescription -MemberType NoteProperty
            $row | Export-Csv -Path $ExportFile -Append -Delimiter ';' -NoTypeInformation
        }

    }

}

I tried to put the URL that Microsoft provides in this link, but also without success.

My script:

Import-Module MicrosoftPowerBIMgmt.Admin

$myCred = Get-Credential
Connect-PowerBIServiceAccount -Credential $myCred

$Session = New-PSSession -ConfigurationName Microsoft.Exchange `
    -ConnectionUri https://outlook.office365.com/powershell-liveid/ `
    -Credential $credential `
    -Authentication Basic `
    -AllowRedirection

Import-PSSession $Session

$Workspaces = Get-PowerBIWorkspace -Scope Organization -All
#Remove-Item $ExportFile -Force -ErrorAction SilentlyContinue

$DataSets =
ForEach ($workspace in $Workspaces)
    {
    Write-Host $workspace.Name
    ForEach ($dataset in (Get-PowerBIDataset -Scope Organization -WorkspaceId $workspace.Id))
        {
            #$URI = "groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
            $URI = "https://api.powerbi.com/v1.0/myorg/groups/" + $workspace.id + "/datasets/" + $dataset.id + "/refreshes"
            #$OutFile = $ExportFolder + '\' + $workspace.Name + '-' + $dataset.Name + '.json'
            $Results = Invoke-PowerBIRestMethod -Url $URI -Method Get | ConvertFrom-Json

            foreach($result in $Results.value)
            {
                $errorDetails = $result.serviceExceptionJson | ConvertFrom-Json -ErrorAction SilentlyContinue

                $ItemResult = New-Object System.Object
                $ItemResult | Add-Member -type NoteProperty -name WorkspaceID           -value $workspace.Id
                $ItemResult | Add-Member -type NoteProperty -name DatasetID             -value $dataset.Id
                $ItemResult | Add-Member -type NoteProperty -name RefreshID             -value $result.Id
                $ItemResult | Add-Member -type NoteProperty -name RequestId             -value $result.requestId
                $ItemResult | Add-Member -type NoteProperty -name RefresheType          -Value $result.refreshType
                $ItemResult | Add-Member -type NoteProperty -name StartTime             -Value $result.startTime
                $ItemResult | Add-Member -type NoteProperty -name EndTime               -Value $result.endTime
                $ItemResult | Add-Member -type NoteProperty -name Status                -Value $result.status
                $ItemResult | Add-Member -type NoteProperty -name ErrorCode             -Value $errorDetails.errorCode
                $ItemResult | Add-Member -type NoteProperty -name ErrorDescription      -Value $errorDetails.errorDescription

                # Put the item result and append it to the result object
                $Result +=$ItemResult
            }
        }
    }
$DataSets | Export-Csv "D:\Users\F02579\Documents\PowerBIRefreshHistory.csv" -NoTypeInformation -Encoding UTF8

Remove-PSSession $Session

Disconnect-PowerBIServiceAccount

Error on my scripp:

Body:
After making some calls with Microsoft, with some engineers that works with PowerBI and Powershell conector, I'm now able to get those information.

Powershell script:

$authUrl = "https://login.windows.net/common/oauth2/token/"
$clientId = "Your clientID"
$pbiUsername = "Your user email"
$pbiPassword = "Your password"

$body = @{
    "resource" = “https://analysis.windows.net/powerbi/api";
    "client_id" = $clientId;
    "grant_type" = "password";
    "username" = $pbiUsername;
    "password" = $pbiPassword;
    "scope" = "openid"
}
$authResponse = Invoke-RestMethod -Uri $authUrl –Method POST -Body $body

$DatasetID = "Your datasetID"
$restURL = "https://api.powerbi.com/v1.0/myorg/datasets/$DatasetID/refreshes"

$headers = @{
    "Content-Type" = "application/json";
    "Authorization" = $authResponse.token_type + " " + $authResponse.access_token
}

$restResponse = Invoke-RestMethod -Uri $restURL –Method GET -Headers $headers | Select-Object -ExpandProperty value
$restResponse


问:
Cannot return array and use in another method
I am trying to call my array in my printmessage method. I am getting an error as if I cannot access it outside my method getSum(). Any help? Thanks</p>

```<code>    public int getSum(int input) {
        int empty[] = new int[input] ;

        for (int i =0;i < input;i++) {
            int num = scan.nextInt();
            empty[i] = num;
            sum = num +sum;
        }
        return sum && empty[];
    }

    public void Printmessage(){
        for(int j = 0; j< empty.length; j++) {
            System.out.print(empty[j]+ " ");
        }
    }
}
</code>```

答:
I'd go further than some answers.

The array empty is a local variable of the getsum method.  Therefore it does not exist except when getsum is executing. It is created on entry to getsum and destroyed on exit.

You can't use something (in printMessage) that does not exist.

(Secondarily, of course, sum && empty[] is not even legal, since firstly && is defined only for boolean operands, and secondly empty[] isn't a valid expression)

Body:
I am trying to call my array in my printmessage method. I am getting an error as if I cannot access it outside my method getSum(). Any help? Thanks

    public int getSum(int input) {
        int empty[] = new int[input] ;

        for (int i =0;i < input;i++) {
            int num = scan.nextInt();
            empty[i] = num;
            sum = num +sum;
        }
        return sum && empty[];
    }

    public void Printmessage(){
        for(int j = 0; j< empty.length; j++) {
            System.out.print(empty[j]+ " ");
        }
    }
}


问:
GoogleAutocompleteViewController: Cancel method from delegate does not working
Recently I'm using the google's autocomplete places picker, but the following method does not being triggered:

//extension ServicesViewController: GMSAutocompleteViewControllerDelegate
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
  viewController.dismiss(animated: true, completion: nil)
}```

What could be happening?

Best Regards

答:
You should conform the delegate of the GMSAutocompleteViewController.

let controller = GMSAutocompleteViewController()
controller.delegate = self // <-- Set the delegate
present(controller, animated: true)
```

<p>Then you should call delegate methods</p>

<pre class="lang-swift prettyprint-override"><code>// MARK: - GMSAutocompleteViewControllerDelegate

extension ServicesViewController: GMSAutocompleteViewControllerDelegate {

  public func wasCancelled(_ viewController: GMSAutocompleteViewController) {
    viewController.dismiss(animated: true)
  }
}
</code>```

Body:
Recently I'm using the google's autocomplete places picker, but the following method does not being triggered:

//extension ServicesViewController: GMSAutocompleteViewControllerDelegate
func wasCancelled(_ viewController: GMSAutocompleteViewController) {
  viewController.dismiss(animated: true, completion: nil)
}

What could be happening?

Best Regards

Body:
You should conform the delegate of the GMSAutocompleteViewController.

let controller = GMSAutocompleteViewController()
controller.delegate = self // <-- Set the delegate
present(controller, animated: true)

Then you should call delegate methods

// MARK: - GMSAutocompleteViewControllerDelegate

extension ServicesViewController: GMSAutocompleteViewControllerDelegate {

  public func wasCancelled(_ viewController: GMSAutocompleteViewController) {
    viewController.dismiss(animated: true)
  }
}