问:
How to remove dupes and replace column variables
I'm working with a data set named CCCrn on candidates in a local election with some duplicate values. Here's a sample:

```<code>Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Democratic     4          5

Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Republican     4          5
</code>```

As you can see, this candidate cross listed and was on both parties' ballots. I'd like to remove one of the rows, and then edit the Party variable to say "Cross Listed.

Obviously unique and distinct haven't been much help. I tried
test <- CCCrn[!duplicated(CCCrn$Name), ] which succeeded in removing the duplicate canidates, but now I'm not sure how I would go back and edit the "Party" variable.

答:
One way, using dplyr, would be to group_by all fields other than the party, and then summarise to "CrossListed" if the number of rows in the group is bigger than 1, i.e. if n()>1.

Something like this...

```<code>library(dplyr)
df2 <- df %>% group_by(-Party) %>%
      summarise(Party = ifelse(n() > 1, "CrossListed", first(Party))
</code>```

or an alternative to the last line would be to paste all the party names together so that you can see where they are cross-listed (which might be useful if there are lots of parties - less so if there are only two!)... summarise(Party = paste(sort(Party), collapse=", "))

Body:
I'm working with a data set named CCCrn on candidates in a local election with some duplicate values. Here's a sample:

Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Democratic     4          5

Adam Hill         4100 New Texas Rd.            Pittsburgh 15239 School Director   PLUM       Republican     4          5

As you can see, this candidate cross listed and was on both parties' ballots. I'd like to remove one of the rows, and then edit the Party variable to say "Cross Listed.

Obviously unique and distinct haven't been much help. I tried
test <- CCCrn[!duplicated(CCCrn$Name), ] which succeeded in removing the duplicate canidates, but now I'm not sure how I would go back and edit the "Party" variable.

Body:
One way, using dplyr, would be to group_by all fields other than the party, and then summarise to "CrossListed" if the number of rows in the group is bigger than 1, i.e. if n()>1.

Something like this...

library(dplyr)
df2 <- df %>% group_by(-Party) %>%
      summarise(Party = ifelse(n() > 1, "CrossListed", first(Party))

or an alternative to the last line would be to paste all the party names together so that you can see where they are cross-listed (which might be useful if there are lots of parties - less so if there are only two!)... summarise(Party = paste(sort(Party), collapse=", "))


来源: stackexchange

问:
CORS policy when deleting an item
error message in google chromeWhen I try to delete an item I am getting an error.

When I added spring security to my backend i faced problem with csrf and could not event display my data from database in Angular. So, I made some steps:
I have added @WebSecurityConfigurerAdapter into my backend. Later set Interceptor in Angular and after this I was able to load my data using spring security in background.

```<code>@EnableWebSecurity
@Configuration
public class SpringSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //.formLogin().and()
                .httpBasic();
    }
}
</code>```

Angular part my service with Interceptor

```<code>import { Injectable } from '@angular/core';
import {HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const username = 'damian';
    const password = 'damian';
    const basicAutHeaderString = 'Basic ' + window.btoa(username + ':' + password);

    request = request.clone(
      {
        setHeaders: {
          Authorization: basicAutHeaderString
        }
      }
    );
    return next.handle(request);
  }

  constructor() { }

}
</code>```

Getting single item from backend:

```<code>  deleteSingleTodo(id) {
    return this.http.delete<Todo>(`http://localhost:8081/${id}`);
  }
</code>```

My delete method which is triggered by (click) button:

```<code>  deleteTodo(id) {
    console.log(`delete todo ${id}` )
    this.getDataService.deleteSingleTodo( id).subscribe (
      response => {
        console.log(response);
        this.message = `Delete of Todo ${id} Successful!`;
        this.refreshTodos();
      }
    );
  }

I also provided HTTP_INTERCEPTORS in app.module.ts
 providers: [
    { provide: HTTP_INTERCEPTORS, `useClass: HttpInterceptorService, multi:` true}
</code>```

],[my error message in google][1]

答:
You just have to add below class as CORS configurations

How it works?

CORS requests are automatically dispatched to the various HandlerMappings that are registered. They handle CORS preflight requests and intercept CORS simple and actual requests by means of a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (such as Access-Control-Allow-Origin).

CorsConfiguration allows one to specify how the CORS requests should be processed: allowed origins, headers and methods among others. This may be provided in various ways

CORS Doc  CORS with Spring Boot

```<code>import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
          "USERID"+"ROLE"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }

}
</code>```

ContentLicense: CC BY-SA 4.0

Title: CORS policy when deleting an item

Body:
error message in google chromeWhen I try to delete an item I am getting an error.

When I added spring security to my backend i faced problem with csrf and could not event display my data from database in Angular. So, I made some steps:
I have added @WebSecurityConfigurerAdapter into my backend. Later set Interceptor in Angular and after this I was able to load my data using spring security in background.

@EnableWebSecurity
@Configuration
public class SpringSecurity extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                .anyRequest().authenticated()
                .and()
                //.formLogin().and()
                .httpBasic();
    }
}

Angular part my service with Interceptor

import { Injectable } from '@angular/core';
import {HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {

  intercept(request: HttpRequest<any>, next: HttpHandler) {
    const username = 'damian';
    const password = 'damian';
    const basicAutHeaderString = 'Basic ' + window.btoa(username + ':' + password);

    request = request.clone(
      {
        setHeaders: {
          Authorization: basicAutHeaderString
        }
      }
    );
    return next.handle(request);
  }

  constructor() { }

}

Getting single item from backend:

  deleteSingleTodo(id) {
    return this.http.delete<Todo>(`http://localhost:8081/${id}`);
  }

My delete method which is triggered by (click) button:

  deleteTodo(id) {
    console.log(`delete todo ${id}` )
    this.getDataService.deleteSingleTodo( id).subscribe (
      response => {
        console.log(response);
        this.message = `Delete of Todo ${id} Successful!`;
        this.refreshTodos();
      }
    );
  }

I also provided HTTP_INTERCEPTORS in app.module.ts
 providers: [
    { provide: HTTP_INTERCEPTORS, `useClass: HttpInterceptorService, multi:` true}

],[my error message in google][1]

Body:
You just have to add below class as CORS configurations

How it works?

CORS requests are automatically dispatched to the various HandlerMappings that are registered. They handle CORS preflight requests and intercept CORS simple and actual requests by means of a CorsProcessor implementation (DefaultCorsProcessor by default) in order to add the relevant CORS response headers (such as Access-Control-Allow-Origin).

CorsConfiguration allows one to specify how the CORS requests should be processed: allowed origins, headers and methods among others. This may be provided in various ways

CORS Doc  CORS with Spring Boot

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter,WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type," +
          "USERID"+"ROLE"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    }

}


问:
Hide option when selected by another Select
I have two select's who uses the same list. When i choose the option "Foo" from select A the same option "Foo" must be hidden on select B. Any ideia how to do it with AngularJS ? I'm trying something like this

```<code><div class="col-md-6">
    <label>
        Testemunha 1 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha1"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha">
        <option></option>
    </select>
</div>

<div class="col-md-6">
    <label>
        Testemunha 2 :
    </label>
    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha2"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha ">
        <option></option>
    </select>
</div>
</code>```

```<code>  $scope.esconderTestemunhaSelecionada = function(obj){
    if($scope.lstTestemunha.includes(obj)){
      $scope.lstTestemunha.style.display = "none";
      return $scope.lstTestemunha;
    }
  }
</code>```

答:
You could use a filter on your second select. This will filter the items in the second select such that the item selected in the first does not appear. If you need it to be more complex (for example, this will cause the second select to not have any options until something is selected in the first select which may be an undesirable side effect) you can always write your own custom filter.

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.selectItems = [];
    $scope.selectedItemA = {};
    $scope.selectedItemB = {};
    for (let i = 1; i <= 10; i++) {
      $scope.selectItems.push({
        id: i,
        name: 'Item #' + i
      });
    }
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div>
    Select Item A:
    <select ng-model="selectedItemA" ng-options="item as item.name for item in selectItems"></select>
  </div>
  <div>
    Select Item B:
    <select ng-model="selectedItemB" ng-options="item as item.name for item in selectItems | filter: { id: '!' + selectedItemA.id }"></select>
  </div>
</div></code>```

Body:
I have two select's who uses the same list. When i choose the option "Foo" from select A the same option "Foo" must be hidden on select B. Any ideia how to do it with AngularJS ? I'm trying something like this

        Testemunha 1 :

    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha1"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha">
        <option></option>
    </select>

        Testemunha 2 :

    <select select-normal data-placeholder="..." ng-model="notificacaoOrientativa.testemunha2"
            ng-options="obj as obj.pessoa.nome for obj in lstTestemunha ">
        <option></option>
    </select>

  $scope.esconderTestemunhaSelecionada = function(obj){
    if($scope.lstTestemunha.includes(obj)){
      $scope.lstTestemunha.style.display = "none";
      return $scope.lstTestemunha;
    }
  }

Body:
You could use a filter on your second select. This will filter the items in the second select such that the item selected in the first does not appear. If you need it to be more complex (for example, this will cause the second select to not have any options until something is selected in the first select which may be an undesirable side effect) you can always write your own custom filter.

angular.module('app', [])
  .controller('ctrl', function($scope) {
    $scope.selectItems = [];
    $scope.selectedItemA = {};
    $scope.selectedItemB = {};
    for (let i = 1; i <= 10; i++) {
      $scope.selectItems.push({
        id: i,
        name: 'Item #' + i
      });
    }
  });

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div>
    Select Item A:
    <select ng-model="selectedItemA" ng-options="item as item.name for item in selectItems"></select>
  </div>
  <div>
    Select Item B:
    <select ng-model="selectedItemB" ng-options="item as item.name for item in selectItems | filter: { id: '!' + selectedItemA.id }"></select>
  </div>
</div>


问:
Entity Framework Where method parameters
The following EF statement does not compile as it is expecting 2 additional parameters, an int and a bool. I can't figure out how to supply them or what they are used for.

```<code>Dim L2 = Db.SecurityLogs.Where(Function(x) x.OrderId = OrderId)
</code>```

The compile error is;

```<code>Error   27  Overload resolution failed because no accessible 'Where' can be called with these arguments:
'Public Function Where(predicate As String, ParamArray parameters() As System.Data.Objects.ObjectParameter) As System.Data.Objects.ObjectQuery(Of SecurityLog)': Lambda expression cannot be converted to 'String' because 'String' is not a delegate type.
Extension method 'Public Function Where(predicate As System.Func(Of SecurityLog, Integer, Boolean)) As System.Collections.Generic.IEnumerable(Of SecurityLog)' defined in 'System.Linq.Enumerable': Nested function does not have a signature that is compatible with delegate 'System.Func(Of SecurityLog, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Func(Of SecurityLog, Boolean)) As System.Collections.Generic.IEnumerable(Of SecurityLog)' defined in 'System.Linq.Enumerable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of SecurityLog, Integer, Boolean))) As System.Linq.IQueryable(Of SecurityLog)' defined in 'System.Linq.Queryable': Nested function does not have a signature that is compatible with delegate 'System.Func(Of SecurityLog, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of SecurityLog, Boolean))) As System.Linq.IQueryable(Of SecurityLog)' defined in 'System.Linq.Queryable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'.  D:\Projects\OutdoorAndCountry\trunk\Source\Server\DataModel\SecurityLogDb.vb    24  22  DataModel
</code>```

I thought I understood how to use the Where method so I must be calling it differently to the way I normally do and MSDN only seems to refer to the passing of the function without parameters.

What am I missing?

Thanks in advance,

Ryan

答:
I think the last line in the compiler error message (which represents the relevant overload which should be applied) is the important hint:

Extension method 'Public Function
  Where(predicate As
  System.Linq.Expressions.Expression(Of
  System.Func(Of SecurityLog, Boolean)))
  As System.Linq.IQueryable(Of
  SecurityLog)' defined in
  'System.Linq.Queryable': Option Strict
  On disallows implicit conversions from
  'Boolean?' to 'Boolean'.

It indicates that in your expression x.OrderId = OrderId either the left side (OrderId property of your SecurityLog class) is a nullable int (Integer?) or the type on the right side is a nullable int. Comparison of the a nullable and a non-nullable integer results in a nullable bool (Boolean?). The compiler complains that it cannot convert this Boolean? to the non-nullable Boolean which the lambda expression requires.

To solve the problem you could convert the possible Nothing value in the nullable type to 0 (or some other integer):

```<code>' If x.OrderId is the nullable Integer
Dim L2 = Db.SecurityLogs.Where(Function(x) If(x.OrderId, 0) = OrderId)
</code>```

or

```<code>' If OrderId is the nullable Integer
Dim L2 = Db.SecurityLogs.Where(Function(x) x.OrderId = If(OrderId, 0))
</code>```

(If not 100% sure about the VB syntax but If(x, y) should correspond here to x ?? y in C#, so: if x is Nothing then return y, otherwise return the value of x.)

You could also turn off the option Strict On in your VB compiler or project settings as this error only appears if the option is switched on. (But there might be some other reasons, I guess, to have this option on in your project, since it is non-default.)

ContentLicense: CC BY-SA 3.0

Body:
The following EF statement does not compile as it is expecting 2 additional parameters, an int and a bool. I can't figure out how to supply them or what they are used for.

Dim L2 = Db.SecurityLogs.Where(Function(x) x.OrderId = OrderId)

The compile error is;

Error   27  Overload resolution failed because no accessible 'Where' can be called with these arguments:
'Public Function Where(predicate As String, ParamArray parameters() As System.Data.Objects.ObjectParameter) As System.Data.Objects.ObjectQuery(Of SecurityLog)': Lambda expression cannot be converted to 'String' because 'String' is not a delegate type.
Extension method 'Public Function Where(predicate As System.Func(Of SecurityLog, Integer, Boolean)) As System.Collections.Generic.IEnumerable(Of SecurityLog)' defined in 'System.Linq.Enumerable': Nested function does not have a signature that is compatible with delegate 'System.Func(Of SecurityLog, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Func(Of SecurityLog, Boolean)) As System.Collections.Generic.IEnumerable(Of SecurityLog)' defined in 'System.Linq.Enumerable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of SecurityLog, Integer, Boolean))) As System.Linq.IQueryable(Of SecurityLog)' defined in 'System.Linq.Queryable': Nested function does not have a signature that is compatible with delegate 'System.Func(Of SecurityLog, Integer, Boolean)'.
Extension method 'Public Function Where(predicate As System.Linq.Expressions.Expression(Of System.Func(Of SecurityLog, Boolean))) As System.Linq.IQueryable(Of SecurityLog)' defined in 'System.Linq.Queryable': Option Strict On disallows implicit conversions from 'Boolean?' to 'Boolean'.  D:\Projects\OutdoorAndCountry\trunk\Source\Server\DataModel\SecurityLogDb.vb    24  22  DataModel

I thought I understood how to use the Where method so I must be calling it differently to the way I normally do and MSDN only seems to refer to the passing of the function without parameters.

What am I missing?

Thanks in advance,

Ryan

Body:
I think the last line in the compiler error message (which represents the relevant overload which should be applied) is the important hint:

Extension method 'Public Function
  Where(predicate As
  System.Linq.Expressions.Expression(Of
  System.Func(Of SecurityLog, Boolean)))
  As System.Linq.IQueryable(Of
  SecurityLog)' defined in
  'System.Linq.Queryable': Option Strict
  On disallows implicit conversions from
  'Boolean?' to 'Boolean'.

It indicates that in your expression x.OrderId = OrderId either the left side (OrderId property of your SecurityLog class) is a nullable int (Integer?) or the type on the right side is a nullable int. Comparison of the a nullable and a non-nullable integer results in a nullable bool (Boolean?). The compiler complains that it cannot convert this Boolean? to the non-nullable Boolean which the lambda expression requires.

To solve the problem you could convert the possible Nothing value in the nullable type to 0 (or some other integer):

' If x.OrderId is the nullable Integer
Dim L2 = Db.SecurityLogs.Where(Function(x) If(x.OrderId, 0) = OrderId)

or

' If OrderId is the nullable Integer
Dim L2 = Db.SecurityLogs.Where(Function(x) x.OrderId = If(OrderId, 0))

(If not 100% sure about the VB syntax but If(x, y) should correspond here to x ?? y in C#, so: if x is Nothing then return y, otherwise return the value of x.)

You could also turn off the option Strict On in your VB compiler or project settings as this error only appears if the option is switched on. (But there might be some other reasons, I guess, to have this option on in your project, since it is non-default.)


问:
Check is the structure is empty (python)
I use a special class of objects and some method which returns me structures such as:

```<code>{'items': [{'_from': 12,
            'bla': 3713,
            'ff': 0.0,
            'd': 45755,
            'fdef': 1536},
           {'_from': None,
            'bla': 3712,
            'ff': 0.0,
            'd': 45838,
            'fdef': 1536}]}
</code>```

Sometimes this structure is empty and then I get the following;

```<code>{'items': []}
</code>```

How can I check in my program if the returning structure is empty? It has no such attributes as length. It seems that I can access single elements of the structure only via the Loop (so nothing like structure['items']['bla'] is possible):

```<code>for k in myStructure.items:
         idd=k.bla
</code>```

How can I perform such a check in an elegant way?

答:
You can iterate directly over values. As I show below, you can  get the length of the empty list, which is 0, or you can simply use if i which will be True if the list is not empty.

```<code>myStructure = {'items': []}

for i in myStructure.values():
    if not i:
        print ("list is empty")
    print (len(i))
</code>```

Body:
I use a special class of objects and some method which returns me structures such as:

{'items': [{'_from': 12,
            'bla': 3713,
            'ff': 0.0,
            'd': 45755,
            'fdef': 1536},
           {'_from': None,
            'bla': 3712,
            'ff': 0.0,
            'd': 45838,
            'fdef': 1536}]}

Sometimes this structure is empty and then I get the following;

{'items': []}

How can I check in my program if the returning structure is empty? It has no such attributes as length. It seems that I can access single elements of the structure only via the Loop (so nothing like structure['items']['bla'] is possible):

for k in myStructure.items:
         idd=k.bla

How can I perform such a check in an elegant way?

Body:
You can iterate directly over values. As I show below, you can  get the length of the empty list, which is 0, or you can simply use if i which will be True if the list is not empty.

myStructure = {'items': []}

for i in myStructure.values():
    if not i:
        print ("list is empty")
    print (len(i))


问:
npx create react-app command doesn't work
When I run create react-app in terminal it display some errors.

npx create react-app sample

```<code>Error: EPERM: operation not permitted, mkdir 'C:\Users\Yasiru'
TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js:77:20
    at cb (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:225:22)
    at C:\Program Files\nodejs\node_modules\npm\lib\npm.js:263:24
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:83:7
    at Array.forEach (<anonymous>)
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:82:13
    at f (C:\Program Files\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:173:20)
C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98
  var doExit = npm.config.loaded ? npm.config.get('_exit') : true
                          ^

TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at process.errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at process.emit (events.js:196:13)
    at process._fatalException (internal/process/execution.js:142:25)
Install for [ 'create@latest' ] failed with code 7
</code>```

答:
When you install create-react-app globally, you do not need to run the command with npm/npx/yarn. It is its own binary, so all you should have to type is "create-react-app directory" where 'directory' is the directory you want to create the react app within.

Also, it looks like the command you're running is "create react-app" rather than "create-react-app", make sure you do not miss the first dash or you will not be running the correct command.

Body:
When I run create react-app in terminal it display some errors.

npx create react-app sample

Error: EPERM: operation not permitted, mkdir 'C:\Users\Yasiru'
TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js:77:20
    at cb (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:225:22)
    at C:\Program Files\nodejs\node_modules\npm\lib\npm.js:263:24
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:83:7
    at Array.forEach (<anonymous>)
    at C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:82:13
    at f (C:\Program Files\nodejs\node_modules\npm\node_modules\once\once.js:25:25)
    at afterExtras (C:\Program Files\nodejs\node_modules\npm\lib\config\core.js:173:20)
C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98
  var doExit = npm.config.loaded ? npm.config.get('_exit') : true
                          ^

TypeError: Cannot read property 'loaded' of undefined
    at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:98:27)
    at process.errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:216:3)
    at process.emit (events.js:196:13)
    at process._fatalException (internal/process/execution.js:142:25)
Install for [ 'create@latest' ] failed with code 7


问:
Python: 'ValueError: too many values to unpack (expected 2)' for a username password system
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

```<code>database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse
</code>```

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

答:
Your code opens the file, then iterates over it line by line.
If it is exactly as you say in your comment to your original question, then the first line is:

```<code> {"name" : "hello", "man" : "mane"}
</code>```

That can't be parsed in your code.

If your file was instead of this form:

```<code>"name":"hello"
"man":"mane"
</code>```

(the newline is implicit) then it would work fine.

The mistake appears to be that you are thinking that a text file that looks like a Python dictionary will be automagically parsed by Python as a dictionary: It won't, which is why you have got other answers here that suggest using eval() or similar to parse it for you.

You might want to consider using the json module to read and write dictionary-like files.

hth

Body:
I am getting this error 'ValueError: too many values to unpack (expected 2)' when I am making a dictionary from a text file when there is more than 1 key and value in the text file.

database = {}  #creates an empty dictionary
with open("file.txt", "r") as infile:  #opens the dictionary
    for line in infile: #for each line
        name, ask = line.strip().split(':')
        database[name] = (ask)

name = input('Enter username: ')
ask = input('Enter pin: ')
if name in database:
    if ask in database[name]:
        print('Welcome', name)

    else:
        database.update( {name : ask} )
        print(database)
else:
    database.update( {name : ask} )
    print(database)

with open('file.txt', 'w') as file:
    file.write(json.dumps(database)) #updates the text file with the new databse

I expect when the program runs and there is more than 1 key and value in the text file to run no matter which key is input. However if there is more than 1 key/value in the file, the text file can't be unpacked

Body:
Your code opens the file, then iterates over it line by line.
If it is exactly as you say in your comment to your original question, then the first line is:

 {"name" : "hello", "man" : "mane"}

That can't be parsed in your code.

If your file was instead of this form:

"name":"hello"
"man":"mane"

(the newline is implicit) then it would work fine.

The mistake appears to be that you are thinking that a text file that looks like a Python dictionary will be automagically parsed by Python as a dictionary: It won't, which is why you have got other answers here that suggest using eval() or similar to parse it for you.

You might want to consider using the json module to read and write dictionary-like files.

hth


问:
How to install Angular CLI locally (without the -g flag)
I've just started working with Angular and with Angular-CLI and I've seen that, according to the documentation, I need to install $ npm install -g @angular/cli with the -g (global) flag.

However I would like to have Angular-CLI installed locally with the rest of my node_modules packages. This way, when I've download my project from git, I could simply run $ npm install (for installing all the dependencies in my package.json).

I try to create a new project by running $ npm init and then run $ npm i @angular/cli -D (-D is the same as --save-dev). But then when I run $ ng new project-name a new sub directory was created with a separate node_modules directory.

答:
Short Answer / TLTR

Start your project by specifying the package -p @angular/cli, so node can find the program:

```<code>npx -p @angular/cli ng new <project-name>
</code>```

Long Answer

The npm ecosystem has been moving more and more towards installing tools as project-local devDependencies, instead of requiring users to install them globally. This is considered a good practice. As it allows to use multiple versions (one per project), instead of having one unique global version.

In order to start the project from scratch, you need to point to the package with -p flag (otherwise npx will not find it):

```<code>npx -p @angular/cli ng new <project-name>
</code>```

- npx

npx is a command that is installed together with node and npm, starting version 5.2 (July 2017). Most probably you already have it installed.

npx allows you to run that npm command without having it installed locally. npx will look for the latest version of the specified package (in this case @angular/cli) and run the command ng from the bin folder.

- specific versions

You could also install a specific version of Angular CLI. For example, let's say we need to install version 9.1. We could run:

```<code>npx -p @angular/cli@9.1 ng new <project-name>
</code>```

- once it is installed

After the Angular CLI installs the project, go to the folder and use the npx ng directly. For example:

```<code>npx ng serve
</code>```

This will search inside the node_modules/.bin/ folder for the ng command, which is a soft link pointing to ../@angular/cli/bin/ng, the locally installed ng command.

Links

npx

Angular CLI

Body:
Short Answer / TLTR

Start your project by specifying the package -p @angular/cli, so node can find the program:

npx -p @angular/cli ng new <project-name>

Long Answer

The npm ecosystem has been moving more and more towards installing tools as project-local devDependencies, instead of requiring users to install them globally. This is considered a good practice. As it allows to use multiple versions (one per project), instead of having one unique global version.

In order to start the project from scratch, you need to point to the package with -p flag (otherwise npx will not find it):

npx -p @angular/cli ng new <project-name>

- npx

npx is a command that is installed together with node and npm, starting version 5.2 (July 2017). Most probably you already have it installed.

npx allows you to run that npm command without having it installed locally. npx will look for the latest version of the specified package (in this case @angular/cli) and run the command ng from the bin folder.

- specific versions

You could also install a specific version of Angular CLI. For example, let's say we need to install version 9.1. We could run:

npx -p @angular/cli@9.1 ng new <project-name>

- once it is installed

After the Angular CLI installs the project, go to the folder and use the npx ng directly. For example:

npx ng serve

This will search inside the node_modules/.bin/ folder for the ng command, which is a soft link pointing to ../@angular/cli/bin/ng, the locally installed ng command.

Links

npx

Angular CLI


问:
react native chat render the username
I'm creating a react native chat app and I cant get the username in the messages</p>

```<code>  // retrieve the messages from the Backend
  loadMessages(callback) {
    this.messagesRef = firebase.database().ref("messages");
    this.messagesRef.off();
    const onReceive = data => {
      const message = data.val();
      callback({
        id: data.key,
        text: message.text,
        createdAt: message.createdAt,
        user: {
          _id: message.user._id,
          name: message.user.Uemail,
          avatar: 'https://placeimg.com/140/140/any',
        }

      });
    };
    this.messagesRef.limitToLast(20).on("child_added", onReceive);
  }
</code>```

Title: react native chat render the username

Body:
I'm creating a react native chat app and I cant get the username in the messages

  // retrieve the messages from the Backend
  loadMessages(callback) {
    this.messagesRef = firebase.database().ref("messages");
    this.messagesRef.off();
    const onReceive = data => {
      const message = data.val();
      callback({
        id: data.key,
        text: message.text,
        createdAt: message.createdAt,
        user: {
          _id: message.user._id,
          name: message.user.Uemail,
          avatar: 'https://placeimg.com/140/140/any',
        }

      });
    };
    this.messagesRef.limitToLast(20).on("child_added", onReceive);
  }

Body: renderUsernameOnMessage={true}


问:
Dart: cancelable post delay / future
I am new to flutter and I want to translate some text from an InputField by calling an API. However I don't want to call it on every key stroke, but instead only when the user paused typing.

On Android I would just use the Handler class with postDelay() with beforehand calling removeAllCallbacksAndMessages(null). Is there a way to do something similar on Dart?

Here is my current code:

```<code>Future<String> getTranslation(String query, Language from, Language to) async {
    // cancel here if a call to this function was less than 500 millis ago.
    return Future.delayed(const Duration(milliseconds: 500), () {
      return _translator.translate(query, from: from.code, to: to.code)
    });
  }
</code>```

Edit 1

I'm calling the code from my Bloc like so:

```<code>@override
  Stream<State> mapEventToState(Event event) async* {
    if (event is QueryChangeEvent) {
      yield TextTranslationChangeState(
          query: event.query ?? "",
          translation: await _repo.getTranslation(event.query, currentState.fromLang, currentState.toLang));
  }
</code>```

This is why I cannot call .then() on the future because I wouldn't be able to yield the new state from the block of the nested function.

Any help is appreciated!

答:
Assuming that you're using a TextField for your input, you can call getTranslation()
on the onSubmitted, which will be called when the user finishes editing :

```<code> TextField(
   onSubmitted: (value) {
     getTranslation(value, 'en', 'ru');
   },
 );
</code>```

Title: Dart: cancelable post delay / future

Body:
I am new to flutter and I want to translate some text from an InputField by calling an API. However I don't want to call it on every key stroke, but instead only when the user paused typing.

On Android I would just use the Handler class with postDelay() with beforehand calling removeAllCallbacksAndMessages(null). Is there a way to do something similar on Dart?

Here is my current code:

Future<String> getTranslation(String query, Language from, Language to) async {
    // cancel here if a call to this function was less than 500 millis ago.
    return Future.delayed(const Duration(milliseconds: 500), () {
      return _translator.translate(query, from: from.code, to: to.code)
    });
  }

Edit 1

I'm calling the code from my Bloc like so:

@override
  Stream<State> mapEventToState(Event event) async* {
    if (event is QueryChangeEvent) {
      yield TextTranslationChangeState(
          query: event.query ?? "",
          translation: await _repo.getTranslation(event.query, currentState.fromLang, currentState.toLang));
  }

This is why I cannot call .then() on the future because I wouldn't be able to yield the new state from the block of the nested function.

Any help is appreciated!

Body:
Assuming that you're using a TextField for your input, you can call getTranslation()
on the onSubmitted, which will be called when the user finishes editing :

 TextField(
   onSubmitted: (value) {
     getTranslation(value, 'en', 'ru');
   },
 );


问:
Spring MVC - clearing fields
I have a domain object which I am presenting on a typical form.  Here is a simplified example:

```<code>public class Name implements Keyed {

    private String firstName;
    private String middleName;
    private String lastName;
    private Number key;

    //Getters and Setters
}
</code>```

Let's say I have two type of users whom can each modify these Name objects.  For some silly reason one group is not allowed to see / edit the middle names of the users.  So I leave that field off of the form (no hidden field either).

Is there anyway to keep Spring from clearing that middle name field?  I could create a new object for this, but it seems like duplication which shouldn't be needed.

Is there a way to keep data which hasn't been modified (i.e. it wasn't displayed to the user, hence couldn't have been changed)?

答: It seems that with spring binding this is simply not possible.  You are basically forced into creating a near copy of your domain object, and remove fields which are not to be displayed on the page itself.  While unfortunate, it is simply how spring binding works, as a new instance will be created by spring for you before your method is invoked.</p>

ContentLicense: CC BY-SA 2.5

Title: Spring MVC - clearing fields

Body:
I have a domain object which I am presenting on a typical form.  Here is a simplified example:

public class Name implements Keyed {

    private String firstName;
    private String middleName;
    private String lastName;
    private Number key;

    //Getters and Setters
}

Let's say I have two type of users whom can each modify these Name objects.  For some silly reason one group is not allowed to see / edit the middle names of the users.  So I leave that field off of the form (no hidden field either).

Is there anyway to keep Spring from clearing that middle name field?  I could create a new object for this, but it seems like duplication which shouldn't be needed.

Is there a way to keep data which hasn't been modified (i.e. it wasn't displayed to the user, hence couldn't have been changed)?


问:
List prime numbers
I am an amateur java student, and my teacher gave me this assignment which is to write a code that list the first 100 prime numbers. Here is what I have I tried so far.

```<code>for(int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0){
            k ++;
        }

        if(k == 2) {
            System.out.println(i);
        }
    }
}
</code>```

The problem I encountered is I couldn't not stop the console to stop after a count of 100, even if I used possible mechanisms I am familiar with. for instance:

```<code>for( int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0) {
            k ++;
        }

        int m = 0;
        if(k == 2) {
            System.out.println(i);
            m++;
            if(m==100) {
                break;
            }
        }
    }
}
</code>```

Can I get help in terminating the loop after a count of 100 primes ?

答:
You code runs to infinity because you have placed your break at wrong point. Your break exits the inner loop which is for(int j = 1; j <= i; j++) although you should be targeting the outer-loop for( int i =1; true; i++) since that is what is deciding how many numbers will be printing inner-loop is just to check if the number is prime.

I have corrected your approach in this code (The explanation is in the comments)

```<code>int numbersPrinted = 0; // To keep track of how many numbers have been printed
for (int i = 2; true; i++) {
    boolean isPrime = true; // Assuming the number is prime
    for (int j = 2; j < i; j++) {
        // Checking if any number from 2 to i-1 completely divides i
        if (i % j == 0) {
            // If a number completely divides (gives 0 remainder)
            // The number is not prime
            isPrime = false;
            // You can use break here. I don't think it matters anyways.
        }
    }
    if (isPrime) {
        // Printing i only if it is prime
        System.out.print(i + ", ");
        numbersPrinted++; // Updating the numbersPrinted
    }
    // Checking if the numbers printed is grater than or equal to 100
    if (numbersPrinted >= 100)
        // This will break the outermost loop
        // This is where you messed up
        break;
}
</code>```

Output (Exactly 100 prime numbers)

```<code>2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
</code>```

Title: List prime numbers

Body:
I am an amateur java student, and my teacher gave me this assignment which is to write a code that list the first 100 prime numbers. Here is what I have I tried so far.

for(int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0){
            k ++;
        }

        if(k == 2) {
            System.out.println(i);
        }
    }
}

The problem I encountered is I couldn't not stop the console to stop after a count of 100, even if I used possible mechanisms I am familiar with. for instance:

for( int i =1; true; i++) {
    int k = 0;
    for(int j = 1; j <= i; j++) {
        if(i % j == 0) {
            k ++;
        }

        int m = 0;
        if(k == 2) {
            System.out.println(i);
            m++;
            if(m==100) {
                break;
            }
        }
    }
}

Can I get help in terminating the loop after a count of 100 primes ?

Body:
You code runs to infinity because you have placed your break at wrong point. Your break exits the inner loop which is for(int j = 1; j <= i; j++) although you should be targeting the outer-loop for( int i =1; true; i++) since that is what is deciding how many numbers will be printing inner-loop is just to check if the number is prime.

I have corrected your approach in this code (The explanation is in the comments)

int numbersPrinted = 0; // To keep track of how many numbers have been printed
for (int i = 2; true; i++) {
    boolean isPrime = true; // Assuming the number is prime
    for (int j = 2; j < i; j++) {
        // Checking if any number from 2 to i-1 completely divides i
        if (i % j == 0) {
            // If a number completely divides (gives 0 remainder)
            // The number is not prime
            isPrime = false;
            // You can use break here. I don't think it matters anyways.
        }
    }
    if (isPrime) {
        // Printing i only if it is prime
        System.out.print(i + ", ");
        numbersPrinted++; // Updating the numbersPrinted
    }
    // Checking if the numbers printed is grater than or equal to 100
    if (numbersPrinted >= 100)
        // This will break the outermost loop
        // This is where you messed up
        break;
}

Output (Exactly 100 prime numbers)

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541,


问:
Add or modify values in a shapeless HMap
Does anyone know how I might add or modify values in a shapeless HMap? The only functions I see on the HMap definition are:

get

+ (which looks like it's creating a new map and adding the (k,v) tuple)

- (same as above)

My suspicion is that I will need to use lens?

答:
shapeless.HMap is immutable. It's a wrapper (with type-level enhancements) of scala.collection.immutable.Map.

+ adds or modifies a pair (returning new HMap).

Lenses also create a copy. Immutability/persistence is typical for FP.


问:
Limit up to 10 ids from table 1 and get all the records from table 2 which matches the ids of table 1
I have a table1 for example:

```<code>orderID userId orderName orderTime...
1         11
2.        12
3.        11
4.        14
5.        11
6.        13
7.        11
8.        15
9.        16
10.       11
...      ...
</code>```

I have another table table2:

```<code>table2ID orderID item    price ....
101       1       Apple   1.99
102       1       Banana  2.99
103       1       Grapes  0.99
104       4       pizza   6.99
105       4       drink   0.99
105.      3       chicken 1.99
106.      3       apple   1.99
</code>```

I have tried this :

```<code>SELECT a.*, b.* FROM `table1` a
    RIGHT JOIN table2 b on a.orderID = b.orderID
    WHERE a.userID = 11 order by a.`orderTime` DESC LIMIT 25;
</code>```

I want to get upto 10 unique orderIDs from table 1 of user 11 and all the details of that 10 ids from table 2. If I do LIMIT 25 then I don't get all the information.
I want my output as:

```<code>orderID userId orderName orderTime... table2ID orderID item    price
 1        11                            101       1    Apple   1.99
 1        11                            102       1    Banana 2.99
 1        11                            103       1    Grapes  0.99
 3        11                            105       3    chicken 1.99
 3        11                            106       3     apple   1.99
</code>```

答:
```<code>SELECT a.*, b.*
FROM ( SELECT *
       FROM a
       WHERE a.userID = 11
       LIMIT 10) as a
JOIN b
  ON a.orderID = b.orderID
</code>```

Body:
I have a table1 for example:

orderID userId orderName orderTime...
1         11
2.        12
3.        11
4.        14
5.        11
6.        13
7.        11
8.        15
9.        16
10.       11
...      ...

I have another table table2:

table2ID orderID item    price ....
101       1       Apple   1.99
102       1       Banana  2.99
103       1       Grapes  0.99
104       4       pizza   6.99
105       4       drink   0.99
105.      3       chicken 1.99
106.      3       apple   1.99

I have tried this :

SELECT a.*, b.* FROM `table1` a
    RIGHT JOIN table2 b on a.orderID = b.orderID
    WHERE a.userID = 11 order by a.`orderTime` DESC LIMIT 25;

I want to get upto 10 unique orderIDs from table 1 of user 11 and all the details of that 10 ids from table 2. If I do LIMIT 25 then I don't get all the information.
I want my output as:

orderID userId orderName orderTime... table2ID orderID item    price
 1        11                            101       1    Apple   1.99
 1        11                            102       1    Banana 2.99
 1        11                            103       1    Grapes  0.99
 3        11                            105       3    chicken 1.99
 3        11                            106       3     apple   1.99


问:
Function not working even though variable looks fine
Function should end up doing like this and running the command:

```<code>Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'
</code>```

However variable gets messed up like this with current working directory added and backslashes:

```<code>Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist
</code>```

ECHO looks fine and also redirect to file is fine as well:

```<code>Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'
</code>```

Sample run:

```<code>PS C:\temp> Get-Check-Func2 "webcA" "mode" "system.web/customErrors"
'MACHINE/WEBROOT/APPHOST/Default Web Site'
system.web/customErrors
mode

Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist.
At line:10 char:16
+ ...             Get-WebConfigurationProperty -pspath ` $mypspath ` -filte ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\usern...fault Web Site':String) [Get-WebConfigurationProperty
   ], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.IIs.PowerShell.Provider.GetConfigurationPropertyCommand

Get-WebConfigurationProperty -pspath  'MACHINE/WEBROOT/APPHOST/Default Web Site' -filter  'system.web/customErrors'  -name  'mode'
</code>```

Please be kind as I am a newbie to PowerShell.

Coming from korn/bash background.

```<code>function Get-Check-Func2 {
$a = Get-Website
$myws = $a.Name
$mypspath = 'MACHINE/WEBROOT/APPHOST/' + "$myws"
$mypspath = '''' + $mypspath + ''''
$myfilter = '''' +  $args[2] + ''''
$myname = '''' +  $args[1] + ''''
 echo "$mypspath"
 echo $args[2]
           Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname
     echo "Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname"
     }
</code>```

Expect  Get-WebConfigurationProperty to run but seems like variable gets messed up.

答:
Your backticks might be causing the issue. Instead of this:

```<code>Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname
</code>```

Just do this:

```<code>Get-WebConfigurationProperty -pspath $mypspath -filter $myfilter -name $myname
</code>```

Or if you're trying to multiline it, only put the backtick after each parameter / input pair, e.g:

```<code>Get-WebConfigurationProperty -pspath $mypspath `
                             -filter $myfilter `
                             -name $myname
</code>```

Another popular option for providing lots of parameters to a cmdlet in a way that doesn't end up with a very long single line is to use a concept called splatting. For example:

```<code>$GetWebConfigPropertyParams = @{
    PSPath = $mypspath
    Filter = $myfilter
    Name = $myname
}
Get-WebConfigProperty @GetWebConfigPropertyParams
</code>```

Body:
Function should end up doing like this and running the command:

Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'

However variable gets messed up like this with current working directory added and backslashes:

Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist

ECHO looks fine and also redirect to file is fine as well:

Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site'  -filter  'system.web/customErrors'  -name  'mode'

Sample run:

PS C:\temp> Get-Check-Func2 "webcA" "mode" "system.web/customErrors"
'MACHINE/WEBROOT/APPHOST/Default Web Site'
system.web/customErrors
mode

Get-WebConfigurationProperty : Cannot find path 'C:\Users\username\'MACHINE\WEBROOT\APPHOST\Default Web Site''
because it does not exist.
At line:10 char:16
+ ...             Get-WebConfigurationProperty -pspath ` $mypspath ` -filte ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (C:\Users\usern...fault Web Site':String) [Get-WebConfigurationProperty
   ], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.IIs.PowerShell.Provider.GetConfigurationPropertyCommand

Get-WebConfigurationProperty -pspath  'MACHINE/WEBROOT/APPHOST/Default Web Site' -filter  'system.web/customErrors'  -name  'mode'

Please be kind as I am a newbie to PowerShell.

Coming from korn/bash background.

function Get-Check-Func2 {
$a = Get-Website
$myws = $a.Name
$mypspath = 'MACHINE/WEBROOT/APPHOST/' + "$myws"
$mypspath = '''' + $mypspath + ''''
$myfilter = '''' +  $args[2] + ''''
$myname = '''' +  $args[1] + ''''
 echo "$mypspath"
 echo $args[2]
           Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname
     echo "Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname"
     }

Expect  Get-WebConfigurationProperty to run but seems like variable gets messed up.

Body:
Your backticks might be causing the issue. Instead of this:

Get-WebConfigurationProperty -pspath ` $mypspath ` -filter ` $myfilter ` -name ` $myname

Just do this:

Get-WebConfigurationProperty -pspath $mypspath -filter $myfilter -name $myname

Or if you're trying to multiline it, only put the backtick after each parameter / input pair, e.g:

Get-WebConfigurationProperty -pspath $mypspath `
                             -filter $myfilter `
                             -name $myname

Another popular option for providing lots of parameters to a cmdlet in a way that doesn't end up with a very long single line is to use a concept called splatting. For example:

$GetWebConfigPropertyParams = @{
    PSPath = $mypspath
    Filter = $myfilter
    Name = $myname
}
Get-WebConfigProperty @GetWebConfigPropertyParams


问:
why exceptions are not catched in the errorChannel of spring integration when the messages are sent using the control bus
I have a spring integration message stored in database. this message was stored after an exception occurred and  catched by the errorChannel.

now when i try to replay this message using the control bus, if an exception occurred, i see an error in my logs but no exception was catched by the errorChannel.

here is the code i used:

```<code>    @Qualifier("control-bus.replay.channel")
    MessageChannel controlBus;

    public void redo(Message<?> msg){
      controlBus.send(
      MessageBuilder.withPayload(
      "@mybean.transform(headers['myMessage'])")
      .setHeader("myMessage", msg).build());
   }
</code>```

i tried to add the errorChannel in the header of the message but did not work.

so i'm wondering if this is the default behavior of the control bus and how can i override it.

答:
There is nothing to do with the Control Bus per se. It is a behavior dictated by the MessageChannel type you use to send that message.

By default a DirectChannel is used to wire endpoints. When you send a message directly into that channel (as you do in your code snippet), the exception is thrown directly to this caller ignoring all the possible error handling configuration. Imagining you do a regular Java call stack without any thread shifting. So, exception is just thrown to you.
That works well, of course, if your entire flow on that channel is direct: no any queue or an executor channels configuration in between.

From here it would be great to see your control-bus.replay.channel and Control Bus configuration.

Body:
I have a spring integration message stored in database. this message was stored after an exception occurred and  catched by the errorChannel.

now when i try to replay this message using the control bus, if an exception occurred, i see an error in my logs but no exception was catched by the errorChannel.

here is the code i used:

    @Qualifier("control-bus.replay.channel")
    MessageChannel controlBus;

    public void redo(Message<?> msg){
      controlBus.send(
      MessageBuilder.withPayload(
      "@mybean.transform(headers['myMessage'])")
      .setHeader("myMessage", msg).build());
   }

i tried to add the errorChannel in the header of the message but did not work.

so i'm wondering if this is the default behavior of the control bus and how can i override it.


问:
EOF in scipy.io.wavfile.read
I was trying to get data of a wav file using scipy.io.wavfile.read but it always returns this error message: ValueError: Unexpected end of file.

I went through all the related questions on this site (I guess). But none of them worked. I have also tried writing filename as r'Mozart 40 Allegro.wav'.

```<code>import scipy.io.wavfile

sample,data=scipy.io.wavfile.read('Mozart 40 Allegro.wav')
print(data)
</code>```

Note: Others have mentioned that my wav file may be corrupt, so I downloaded a sample wav file. And this was the result.  WavFileWarning: Chunk (non-data) not understood, skipping it.
WavFileWarning)

But is there any way to get the wav file I require which is not corrupt and doesn't give the second error message I mentioned?

Thank You

Thanks: Initially I used some online converter but they do a very bad job in keeping the file intact with the precise format, vlc can handle such errors but these can't. Always use sox to convert and other stuff and don't forget to include the required extra files (lame files) if you are working with mp3.

答:
Use underscore for spaces:

```<code>sample,data=scipy.io.wavfile.read('Mozart_40_Allegro.wav')
</code>```

Try:

```<code>import soundfile as sf
audio = sf.read("file")
</code>```

Title: EOF in scipy.io.wavfile.read

Body:
I was trying to get data of a wav file using scipy.io.wavfile.read but it always returns this error message: ValueError: Unexpected end of file.

I went through all the related questions on this site (I guess). But none of them worked. I have also tried writing filename as r'Mozart 40 Allegro.wav'.

import scipy.io.wavfile

sample,data=scipy.io.wavfile.read('Mozart 40 Allegro.wav')
print(data)

Note: Others have mentioned that my wav file may be corrupt, so I downloaded a sample wav file. And this was the result.  WavFileWarning: Chunk (non-data) not understood, skipping it.
WavFileWarning)

But is there any way to get the wav file I require which is not corrupt and doesn't give the second error message I mentioned?

Thank You

Thanks: Initially I used some online converter but they do a very bad job in keeping the file intact with the precise format, vlc can handle such errors but these can't. Always use sox to convert and other stuff and don't forget to include the required extra files (lame files) if you are working with mp3.

Body:
Use underscore for spaces:

sample,data=scipy.io.wavfile.read('Mozart_40_Allegro.wav')

Try:

import soundfile as sf
audio = sf.read("file")


问:
Ansible - using json imported from Consul
I have a json content on Consul that I import to my playbook. The json contains account names and passwords:

```<code>{
    "account_1": "password_1",
    "account_2": "password_2",
    "account_3": "password_3"
}
</code>```

After registering it to variable I wish to be able to use every user name and password. Since these jsons may contain different numbers of entries, I was hoping I could use with_items for this. Can someone help me out?

Debugging the whole json works with no issues:

```<code>TASK [debug] **************************************************************************
ok: [localhost] => {
    "accountsDataFromConsul.data.Value": {
        "account_1": "password_1",
        "account_2": "password_2",
        "account_3": "password_3"
    }
}
</code>```

I try to get to individual entries (user names and passwords). I tried the below code, but it returned only user names:

```<code>- debug:
    var: item
  with_items: "{{accountsDataFromConsul.data.Value}}"
</code>```

```<code>TASK [debug] ******************************************************************************
ok: [localhost] => (item=account_1) => {
    "item": "account_1"
}
ok: [localhost] => (item=account_2) => {
    "item": "account_2"
}
ok: [localhost] => (item=account_3) => {
    "item": "account_3"
}
</code>```

答:
to use every user name and password

The play below

```<code>vars:
  accountsDataFromConsul:
    data:
      Value:
        account_1: password_1
        account_2: password_2
        account_3: password_3
tasks:
  - debug:
      msg: "key: {{ item.key }} value: {{ item.value }}"
    loop: "{{ accountsDataFromConsul.data.Value|dict2items }}"
</code>```

gives (abridged):

```<code>"msg": "key: account_1 value: password_1"
"msg": "key: account_3 value: password_3"
"msg": "key: account_2 value: password_2"
</code>```

Body:
I have a json content on Consul that I import to my playbook. The json contains account names and passwords:

{
    "account_1": "password_1",
    "account_2": "password_2",
    "account_3": "password_3"
}

After registering it to variable I wish to be able to use every user name and password. Since these jsons may contain different numbers of entries, I was hoping I could use with_items for this. Can someone help me out?

Debugging the whole json works with no issues:

TASK [debug] **************************************************************************
ok: [localhost] => {
    "accountsDataFromConsul.data.Value": {
        "account_1": "password_1",
        "account_2": "password_2",
        "account_3": "password_3"
    }
}

I try to get to individual entries (user names and passwords). I tried the below code, but it returned only user names:

- debug:
    var: item
  with_items: "{{accountsDataFromConsul.data.Value}}"

TASK [debug] ******************************************************************************
ok: [localhost] => (item=account_1) => {
    "item": "account_1"
}
ok: [localhost] => (item=account_2) => {
    "item": "account_2"
}
ok: [localhost] => (item=account_3) => {
    "item": "account_3"
}

Body:
to use every user name and password

The play below

vars:
  accountsDataFromConsul:
    data:
      Value:
        account_1: password_1
        account_2: password_2
        account_3: password_3
tasks:
  - debug:
      msg: "key: {{ item.key }} value: {{ item.value }}"
    loop: "{{ accountsDataFromConsul.data.Value|dict2items }}"

gives (abridged):

"msg": "key: account_1 value: password_1"
"msg": "key: account_3 value: password_3"
"msg": "key: account_2 value: password_2"


问:
LinkedIn Reshare ugcPost using API
I am trying to reshare a ugcPost using V2 API.

I have used v2/shares to get this done. I am getting Internal Server Error.

Anybody tried this, please let me know if this is feasible at all?

答: You should add X-Restli-Protocol-Version: 2.0.0 in your headers</p>

Title: LinkedIn Reshare ugcPost using API


问:
How to replace regex patterns with the length of the matched pattern?
I want to analyse some databases which are not well structured.
So I try to complete the following code to analyse it by adding of the number of numeric characters.

```<code>TRACA2 <- data.frame("CAT"=rep("GEN1", 20), "ARTICLE"=rep(c("PRODUCT  V29000655B","PRODUCT  V29000658A","T172560088"),c(10,2,8)), "SERIAL"=rep(c("172560082","T172560088","PRODUCT  V29000658A"),c(10,2,8)), "LIGNE"="ISG3B51",stringsAsFactors = FALSE)

library(dplyr)
analyseData <- function (x, na.rm=FALSE) {
    remplacement <- function(x, na.rm = FALSE) (if_else(is.na(sapply(x,as.numeric)),gsub("[0-9\\.]+","",x),as.character(paste0("<",nchar(as.numeric(x)),">"))))
    x <- x %>% mutate_all(funs(recode=remplacement)) %>% select(ends_with("recode")) %>% group_by_all() %>% summarise(nb = n())
    return (as.data.frame(x))
}
analyseData(TRACA2)

#  CAT_recode ARTICLE_recode SERIAL_recode LIGNE_recode nb
#1        GEN    PRODUCT  VA             T         ISGB  2
#2        GEN    PRODUCT  VB           <9>         ISGB 10
#3        GEN              T   PRODUCT  VA         ISGB  8
</code>```

Now I want to get the following

```<code>#     CAT_recode    ARTICLE_recode    SERIAL_recode       LIGNE_recode nb
#1        GEN<1>    PRODUCT  V<8>A             T<9>         ISG<1>B<2>  2
#2        GEN<1>    PRODUCT  V<8>B              <9>         ISG<1>B<2> 10
#3        GEN<1>              T<9>   PRODUCT  V<8>A         ISG<1>B<2>  8
</code>```

I'd appreciate any help.

Thanks

答:
Try this!

str_replace_all has an argument, replacement, that can take a function; it'll then run that function over each match, and insert the result in in place of the original match.

Should be exactly what you need!

library(dplyr)
library(stringr)

TRACA2 %>%
  mutate_all(funs(recode = str_replace_all(
      .,
      "[0-9\\.]+",
      function(x) paste0("<", nchar(x), ">")
    )
  )) %>%
  select(ends_with("recode")) %>%
  group_by_all() %>%
  summarise(nb = n())
```

<p>PS It looks like <code>funs</code> is soft-deprecated; to use <code>list</code> instead, write the second line like this:</p>

<pre class="lang-r prettyprint-override"><code>mutate_all(list(recode = ~ str_replace_all(
</code>```

Body:
I want to analyse some databases which are not well structured.
So I try to complete the following code to analyse it by adding of the number of numeric characters.

TRACA2 <- data.frame("CAT"=rep("GEN1", 20), "ARTICLE"=rep(c("PRODUCT  V29000655B","PRODUCT  V29000658A","T172560088"),c(10,2,8)), "SERIAL"=rep(c("172560082","T172560088","PRODUCT  V29000658A"),c(10,2,8)), "LIGNE"="ISG3B51",stringsAsFactors = FALSE)

library(dplyr)
analyseData <- function (x, na.rm=FALSE) {
    remplacement <- function(x, na.rm = FALSE) (if_else(is.na(sapply(x,as.numeric)),gsub("[0-9\\.]+","",x),as.character(paste0("<",nchar(as.numeric(x)),">"))))
    x <- x %>% mutate_all(funs(recode=remplacement)) %>% select(ends_with("recode")) %>% group_by_all() %>% summarise(nb = n())
    return (as.data.frame(x))
}
analyseData(TRACA2)

#  CAT_recode ARTICLE_recode SERIAL_recode LIGNE_recode nb
#1        GEN    PRODUCT  VA             T         ISGB  2
#2        GEN    PRODUCT  VB           <9>         ISGB 10
#3        GEN              T   PRODUCT  VA         ISGB  8

Now I want to get the following

#     CAT_recode    ARTICLE_recode    SERIAL_recode       LIGNE_recode nb
#1        GEN<1>    PRODUCT  V<8>A             T<9>         ISG<1>B<2>  2
#2        GEN<1>    PRODUCT  V<8>B              <9>         ISG<1>B<2> 10
#3        GEN<1>              T<9>   PRODUCT  V<8>A         ISG<1>B<2>  8

I'd appreciate any help.

Thanks

Body:
Try this!

str_replace_all has an argument, replacement, that can take a function; it'll then run that function over each match, and insert the result in in place of the original match.

Should be exactly what you need!

library(dplyr)
library(stringr)

TRACA2 %>%
  mutate_all(funs(recode = str_replace_all(
      .,
      "[0-9\\.]+",
      function(x) paste0("<", nchar(x), ">")
    )
  )) %>%
  select(ends_with("recode")) %>%
  group_by_all() %>%
  summarise(nb = n())

PS It looks like funs is soft-deprecated; to use list instead, write the second line like this:

mutate_all(list(recode = ~ str_replace_all(


问:
Facebook: any way to monitor when user clicks on Like button?
writing my first facebook webapp and i have some questions. I'm using their new Graph API + JS library.

The idea is that in order to use my webapp, user has to 'Like' facebook page A.

Suppose user is logged in. I have to check if he 'likes' page A. If user doesn't like that page, i display 'fan box' via

FB.XFBML.parse('<fb:fan profile_id="A's id" stream="0" connections="0" width="450"></fb:fan>');

Now, this fan box with 'Like' button is rendered in iframe that has src set to facebook domain.

Problem: i want to know when user clicks on 'Like' button so that i can display the rest of my webapp. The only possible solution that i can think of is polling every second facebook graph server which is really bad.

i can't attach 'onClick' event on that button cause it's inside iframe pointed to facebook domain  (can't access it at all using JS)

i tried getting the contents of this iframe from my server and display it in iframe with empty src property so that i can access its elements - doesn't work, fan box is messed up.

There is no way that i know of to send 'i want to like that page' request to Graph server on behalf of the user.

I'm stumped. I really doubt that polling is the right way to solve this problem :)

答:
You can get the onclick event by using the fbml code of like button instead of iframe code.

Facebook provides FB.event.subscribe which triggers when somebody clicks like button.

A complete tutorial is here.In your case you can write the code to refresh the page on like button click. and check for like condition on page load. so that if current user has liked the page you can redirect him to application page.


问:
Waiting query result
I can't succeed into waiting an sql query result

This is what my Code looks like

socket.on('new', async function(information) {
  console.log("check no offer en cours");
  var checkOffer = "SELECT COUNT(*) as total FROM app__offer WHERE status_id = 1 AND profile_id = " + user.idUser;
  doInsert = false;
  con.query(checkOffer, function(err, result) {
    if (err) throw err;
    console.log(result[0].total);
    if (result[0].total == 0) {
      console.log("can insert");
      doInsert = true;
    }
  }).then(function() {
    console.log(doInsert);
    if (doInsert) {
      console.log("create offer");
      var sql = "INSERT INTO app__offer (createdAt,updatedAt, startAt, programmed, startLatitude, startLongitude, commune_id, point_id, status_id,device,profile_id) " +
        "VALUES ('" + todayDateTime + "','" + todayDateTime + "','" + todayDateTime + "'," + false + "," + user.latitude + "," + user.longitude + "," + user.idCommuneDestination + "," + user.idPoint + "," + 1 + "," + 'device' + "," + user.idUser + ")";
      console.log(sql);
      con.query(sql, function(err, result) {
        if (err) throw err;
        socket.emit('new', result);
      });
    } else {
      console.log("Cet user a déjà une offre en cours");
    }
  });
```

Issue is the doInsert Log is executed before the canInsert Log.

答:
I would do like :-</p>

```<code>try{
  let result = await con.query(checkOffer);
    if (result) {
      let resultFromAnotherQuery = await con.query(sql);
      if (resultFromAnotherQuery){
        console.log("done");
      }
    }
}catch(err) {
   console.log(err);
}
</code>```

Title: Waiting query result

Body:
I can't succeed into waiting an sql query result

This is what my Code looks like

socket.on('new', async function(information) {
  console.log("check no offer en cours");
  var checkOffer = "SELECT COUNT(*) as total FROM app__offer WHERE status_id = 1 AND profile_id = " + user.idUser;
  doInsert = false;
  con.query(checkOffer, function(err, result) {
    if (err) throw err;
    console.log(result[0].total);
    if (result[0].total == 0) {
      console.log("can insert");
      doInsert = true;
    }
  }).then(function() {
    console.log(doInsert);
    if (doInsert) {
      console.log("create offer");
      var sql = "INSERT INTO app__offer (createdAt,updatedAt, startAt, programmed, startLatitude, startLongitude, commune_id, point_id, status_id,device,profile_id) " +
        "VALUES ('" + todayDateTime + "','" + todayDateTime + "','" + todayDateTime + "'," + false + "," + user.latitude + "," + user.longitude + "," + user.idCommuneDestination + "," + user.idPoint + "," + 1 + "," + 'device' + "," + user.idUser + ")";
      console.log(sql);
      con.query(sql, function(err, result) {
        if (err) throw err;
        socket.emit('new', result);
      });
    } else {
      console.log("Cet user a déjà une offre en cours");
    }
  });

Issue is the doInsert Log is executed before the canInsert Log.

Body:
I would do like :-

try{
  let result = await con.query(checkOffer);
    if (result) {
      let resultFromAnotherQuery = await con.query(sql);
      if (resultFromAnotherQuery){
        console.log("done");
      }
    }
}catch(err) {
   console.log(err);
}


问:
changing object keys acording to an array
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

```<code>    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]
</code>```

expected outcome

```<code>    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}
</code>```

答:
You can one line this via Array.map and then Object.fromEntries:

  const object = {
    name1: "some value A",
    name3: "some value B",
    name2: "some value C"
  }
  const old = ["name1", "name2", "name3"]
  const keys = ["Name1", "Name2", "Name3"]

let result = Object.fromEntries(old.map((x,i) => [keys[i], object[x]]))

console.log(result)```

Body:
i have an object and 2 arrays. i want to change object keys according to arr2, object keys and arr1 values are identical while arr1 and arr2 placement of values in arrays are identical but not values themselves, while i don't want to ask how to solve it want to know how should i approach this problem, thank you for your time

    const object = {
        name1: "some value",
        name3: "some value",
        name2: "some value",
        etc...}
    const arr1 = ["name1", "name2", "name3"]
    const arr2 = ["Name1", "Name2", "Name3"]

expected outcome

    const newObject = {
        Name1: "some value",
        Name3: "some value",
        Name2: "some value",
        etc...}


问:
How to send keys started hidden CMD process
How to send character key to hidden CMD window?
My code:

```<code>[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);

public void SendText(IntPtr hwnd, string keys)
{
    if (hwnd != IntPtr.Zero)
    {
        if (SetForegroundWindow(hwnd))
        {
            System.Windows.Forms.SendKeys.Send(keys);
        }
    }
}

Process p;
int pid;
</code>```

Start Hidden process:

```<code>private void button1_Click(object sender, EventArgs e)
{
    p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = true;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    p.Start();
    pid = p.Id;
}
</code>```

Send key:

```<code>private void button4_Click(object sender, EventArgs e)
{
    var proc1 = Process.GetProcessById(pid);
    SetForegroundWindow(proc1.Handle);
    SendKeys.Send("q");
}
</code>```

How to send key the my process? (But my code starting ffmpeg.exe and send "q" key the stop encode)
Thanks the answer.

答:
During creation of hidden process you have to set RedirectStandardInput = true, otherwise your process will not accept incoming keys.

So if you created your process like this:

```<code>var startInfo = new ProcessStartInfo
{
    FileName = "cmd.exe",
    CreateNoWindow = true,
    UseShellExecute = false,
    WindowStyle = ProcessWindowStyle.Hidden,
    RedirectStandardInput = true
};

var process = Process.Start(startInfo);
</code>```

You can send message to this process via StandardInput

```<code>if (!process.HasExited)
{
    using (var streamWriter = process.StandardInput)
    {
        // write your message here
        var message = "q";
        streamWriter.WriteLine(message);
        streamWriter.Close();
    }

    process.WaitForExit();
    process.Close();
    process.Dispose();
}
</code>```

For more details go to https://learn.microsoft.com/pl-pl/dotnet/api/system.diagnostics.processstartinfo.redirectstandardinput?view=netframework-4.8

Body:
How to send character key to hidden CMD window?
My code:

[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);

public void SendText(IntPtr hwnd, string keys)
{
    if (hwnd != IntPtr.Zero)
    {
        if (SetForegroundWindow(hwnd))
        {
            System.Windows.Forms.SendKeys.Send(keys);
        }
    }
}

Process p;
int pid;

Start Hidden process:

private void button1_Click(object sender, EventArgs e)
{
    p = new Process();
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.UseShellExecute = true;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    p.Start();
    pid = p.Id;
}

Send key:

private void button4_Click(object sender, EventArgs e)
{
    var proc1 = Process.GetProcessById(pid);
    SetForegroundWindow(proc1.Handle);
    SendKeys.Send("q");
}

How to send key the my process? (But my code starting ffmpeg.exe and send "q" key the stop encode)
Thanks the answer.

Body:
During creation of hidden process you have to set RedirectStandardInput = true, otherwise your process will not accept incoming keys.

So if you created your process like this:

var startInfo = new ProcessStartInfo
{
    FileName = "cmd.exe",
    CreateNoWindow = true,
    UseShellExecute = false,
    WindowStyle = ProcessWindowStyle.Hidden,
    RedirectStandardInput = true
};

var process = Process.Start(startInfo);

You can send message to this process via StandardInput

if (!process.HasExited)
{
    using (var streamWriter = process.StandardInput)
    {
        // write your message here
        var message = "q";
        streamWriter.WriteLine(message);
        streamWriter.Close();
    }

    process.WaitForExit();
    process.Close();
    process.Dispose();
}

For more details go to https://learn.microsoft.com/pl-pl/dotnet/api/system.diagnostics.processstartinfo.redirectstandardinput?view=netframework-4.8


问:
flash effect with jquery
I want fadeIn and fadeout backgroud-color using jQuery, I tried below code, It's affect the full div content , I need to add flash effect only for backgroud-color.

```<code>   $('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800)
    .fadeout("fast");
<div class="countbox">checkout</div>
</code>```

I tried this on also but it's not working!

```<code>$('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800).css("background-color","#FFFFFF");
</code>```

What's the problem anyone can help me !

Edit

oops!
my answer not applying to all window. Which one only giving flash effect for current window but I need to get the flash effect for all window.
for example :-
When I click on button, it should give me flash effect for div  for all windows, exactly like in this website.

答:
This should work. Jquery has an animate function of its own you don't have to use any plugin.

```<code>$(".countbox").animate({backgroundColor: "#ff0000"}, 1000);
</code>```

This should animate your background color from its initial value to #ff0000 in 1000 ms(1 second). I think you should include the animation package from jQueryUI.

Hope it helps

Title: flash effect with jquery

Body:
I want fadeIn and fadeout backgroud-color using jQuery, I tried below code, It's affect the full div content , I need to add flash effect only for backgroud-color.

   $('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800)
    .fadeout("fast");

checkout

I tried this on also but it's not working!

$('.countbox').css("background-color","#FF0000").fadeIn("fast").delay(800).css("background-color","#FFFFFF");

What's the problem anyone can help me !

Edit

oops!
my answer not applying to all window. Which one only giving flash effect for current window but I need to get the flash effect for all window.
for example :-
When I click on button, it should give me flash effect for div  for all windows, exactly like in this website.

Body:
This should work. Jquery has an animate function of its own you don't have to use any plugin.

$(".countbox").animate({backgroundColor: "#ff0000"}, 1000);

This should animate your background color from its initial value to #ff0000 in 1000 ms(1 second). I think you should include the animation package from jQueryUI.

Hope it helps


问:
Lodash debounce doesn't work when called from setInterval
I'm trying to call a debounced function from setInterval but for some reason it doesn't works and the function doesn't invoke, any idea why?

```<code>const _ = require('lodash');

const debouncedFunction = _.debounce(() => console.log('test'), 4000);

setInterval(() => {
    console.log('tick');
    debouncedFunction();
}, 1000);
</code>```

It is worth to mention that if I replace the setInterval with setTimeout it works

https://repl.it/@ShahafMango/CheeryKaleidoscopicOffice

答:
The purpose of wrapping a function with debounce is to delay the execution of the function as long as it's called repeatedly. The wait parameter states the time that should elapse after the last call of the debounced function, before the inner function is invoked. If the the interval calls the function once every 1000ms, and the wait is 4000ms, the wrapped function would never be called.

Changing the interval to something less than 1000 will call the function (and probably defeat the original purpose of wrapping with debounce):

const debouncedFunction = _.debounce(() => console.log('test'), 500);

setInterval(() => {
  console.log('tick');
  debouncedFunction();
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script></code>```

If you want to limit the function to work once every 4000ms use _.throttle() instead. Throttle will limit the invocation of the inner function to once per the wait time, no matter how many times the wrapped function was called.

const debouncedFunction = _.throttle(() => console.log('test'), 4000);

setInterval(() => {
  console.log('tick');
  debouncedFunction();
}, 1000);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script></code>```

Body:
I'm trying to call a debounced function from setInterval but for some reason it doesn't works and the function doesn't invoke, any idea why?

const _ = require('lodash');

const debouncedFunction = _.debounce(() => console.log('test'), 4000);

setInterval(() => {
    console.log('tick');
    debouncedFunction();
}, 1000);

It is worth to mention that if I replace the setInterval with setTimeout it works

https://repl.it/@ShahafMango/CheeryKaleidoscopicOffice

Body:
The purpose of wrapping a function with debounce is to delay the execution of the function as long as it's called repeatedly. The wait parameter states the time that should elapse after the last call of the debounced function, before the inner function is invoked. If the the interval calls the function once every 1000ms, and the wait is 4000ms, the wrapped function would never be called.

Changing the interval to something less than 1000 will call the function (and probably defeat the original purpose of wrapping with debounce):

const debouncedFunction = _.debounce(() => console.log('test'), 500);

setInterval(() => {
  console.log('tick');
  debouncedFunction();
}, 1000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

If you want to limit the function to work once every 4000ms use _.throttle() instead. Throttle will limit the invocation of the inner function to once per the wait time, no matter how many times the wrapped function was called.

const debouncedFunction = _.throttle(() => console.log('test'), 4000);

setInterval(() => {
  console.log('tick');
  debouncedFunction();
}, 1000);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>


问:
How to open a file with with ruby?
I am trying to open a file on rails user model with ruby and call it from user controller but it kept throwing me back wrong number of arguments (given 0, expected 1..3).

This is my file directory 'app' ,'assets', 'files', 'test_list.txt'
'app' ,'controllers', 'users controller'

can you help?thanks

class User < ApplicationRecord
  def self.my_method
    my_array = []

    file = File.join(Rails.root, 'app' 'models','assets', 'files', 'test_list.txt')
    File.open.each do |line|
      my_array << line.gsub!(/\n?/, "")
    end

    return my_array.to_s
  end
end
```

```class UsersController < ApplicationController
  require 'open-uri'
  require 'net/http'

  def show
    # uri = URI('https://gist.githubusercontent.com/Kalagan/3b26be21cbf65b62cf05ab549433314e/raw')
    #   data = Net::HTTP.get(uri)
    #   anagrams = data.split(/\n/)

    @vari = User.my_method
    @query = params[:query]
    @results = anagrams.select { |word| @query.split('').sort.join == word.split('').sort.join }
  end
end

```

答:
I think you missed a comma.You can write the below code.

file = File.join(Rails.root, 'app', 'models','assets', 'files', 'test_list.txt')

and for reading the content

```<code>File.read(file) do |file|
  file.each do |line|
    p line
  end
end
</code>```

Title: How to open a file with with ruby?

Body:
I am trying to open a file on rails user model with ruby and call it from user controller but it kept throwing me back wrong number of arguments (given 0, expected 1..3).

This is my file directory 'app' ,'assets', 'files', 'test_list.txt'
'app' ,'controllers', 'users controller'

can you help?thanks

class User < ApplicationRecord
  def self.my_method
    my_array = []

    file = File.join(Rails.root, 'app' 'models','assets', 'files', 'test_list.txt')
    File.open.each do |line|
      my_array << line.gsub!(/\n?/, "")
    end

    return my_array.to_s
  end
end

class UsersController < ApplicationController
  require 'open-uri'
  require 'net/http'

  def show
    # uri = URI('https://gist.githubusercontent.com/Kalagan/3b26be21cbf65b62cf05ab549433314e/raw')
    #   data = Net::HTTP.get(uri)
    #   anagrams = data.split(/\n/)

    @vari = User.my_method
    @query = params[:query]
    @results = anagrams.select { |word| @query.split('').sort.join == word.split('').sort.join }
  end
end

Body:
I think you missed a comma.You can write the below code.

file = File.join(Rails.root, 'app', 'models','assets', 'files', 'test_list.txt')

and for reading the content

File.read(file) do |file|
  file.each do |line|
    p line
  end
end