问:
Spring Security @PreAuthorize annotation with AuthenticationSuccessEvent
I have basic authentication and i want to log/do something on succesfull log in but AuthenticationSuccessEvent is firing up even if that ROLE dont have permission i need to access that HTTP method. How can i log/do something ONLY if i can access that HTTP method with permission.</p>

```<code>@Component("authorization")
public class AuthorizationUtils {

    public boolean hasPermission(final String permission) {
        Collection<? extends GrantedAuthority> authorities = getUserDetails().getAuthorities();
        return authorities.contains(new SimpleGrantedAuthority(permission));
    }

    public static UserDetails getUserDetails() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            return (UserDetails) authentication.getPrincipal();
        }
        return null;
    }

}
</code>```

```<code>public class AuthenticationEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

  @Autowired
  private HttpServletRequest request;

  @Override
  public void onApplicationEvent(AuthenticationSuccessEvent event) {

    String username = ((UserAccountDetails) event.getAuthentication().getPrincipal()).getUsername();

    log.trace("Account with username : {} successfully log in!", username);

    System.out.println(request.getHeader("Authorization"));
  }
</code>```

```<code>  @GetMapping("/permission")
  @PreAuthorize("@authorization.hasPermission('edit.helloworld123')")
  public String editHelloWorld(){
    return "Welcome to permission edit.helloWorld!";
  }
</code>```

答:
Authorization is not the same as Authentication .Authentication is about whether an user can login successfully or not.  Authorization is about if the login user have enough permission to execute a method. So even an user is successfully login (i.e AuthenticationSuccessEvent happens) , if he does not have enough permission to execute a method, the method still fail to execute.

What you are really want is to detect the authorization success event , but you are now detecting the authentication success event , which are totally different things.

To enable spring-security to publish the authorization success event after an user who has enough permission execute a protected method successfully , you have to enable setPublishAuthorizationSuccess of the MethodInterceptor.

From the docs to override the default settings related to method security, you can extend GlobalMethodSecurityConfiguration :

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Override
    public MethodInterceptor methodSecurityInterceptor(MethodSecurityMetadataSource methodSecurityMetadataSource) {
        MethodInterceptor result = super.methodSecurityInterceptor(methodSecurityMetadataSource);
        ((MethodSecurityInterceptor) result).setPublishAuthorizationSuccess(true);
        return result;
    }
}
```

<p>And <code>AuthorizedEvent</code> will be published after the user has enough permission to execute a protected method .So create a <code>ApplicationListener</code> to listen and handle it :</p>

<pre class="lang-java prettyprint-override"><code>@Component
public class MyEventListener implements ApplicationListener<AuthorizedEvent> {

    @Override
    public void onApplicationEvent(AuthorizedEvent event) {
        //Handle the AuthorizedEvent event here......
    }
}
</code>```

Body:
I have basic authentication and i want to log/do something on succesfull log in but AuthenticationSuccessEvent is firing up even if that ROLE dont have permission i need to access that HTTP method. How can i log/do something ONLY if i can access that HTTP method with permission.

@Component("authorization")
public class AuthorizationUtils {

    public boolean hasPermission(final String permission) {
        Collection<? extends GrantedAuthority> authorities = getUserDetails().getAuthorities();
        return authorities.contains(new SimpleGrantedAuthority(permission));
    }

    public static UserDetails getUserDetails() {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            return (UserDetails) authentication.getPrincipal();
        }
        return null;
    }

}

public class AuthenticationEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

  @Autowired
  private HttpServletRequest request;

  @Override
  public void onApplicationEvent(AuthenticationSuccessEvent event) {

    String username = ((UserAccountDetails) event.getAuthentication().getPrincipal()).getUsername();

    log.trace("Account with username : {} successfully log in!", username);

    System.out.println(request.getHeader("Authorization"));
  }

  @GetMapping("/permission")
  @PreAuthorize("@authorization.hasPermission('edit.helloworld123')")
  public String editHelloWorld(){
    return "Welcome to permission edit.helloWorld!";
  }

Body:
Authorization is not the same as Authentication .Authentication is about whether an user can login successfully or not.  Authorization is about if the login user have enough permission to execute a method. So even an user is successfully login (i.e AuthenticationSuccessEvent happens) , if he does not have enough permission to execute a method, the method still fail to execute.

What you are really want is to detect the authorization success event , but you are now detecting the authentication success event , which are totally different things.

To enable spring-security to publish the authorization success event after an user who has enough permission execute a protected method successfully , you have to enable setPublishAuthorizationSuccess of the MethodInterceptor.

From the docs to override the default settings related to method security, you can extend GlobalMethodSecurityConfiguration :

@EnableGlobalMethodSecurity(prePostEnabled = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {

    @Override
    public MethodInterceptor methodSecurityInterceptor(MethodSecurityMetadataSource methodSecurityMetadataSource) {
        MethodInterceptor result = super.methodSecurityInterceptor(methodSecurityMetadataSource);
        ((MethodSecurityInterceptor) result).setPublishAuthorizationSuccess(true);
        return result;
    }
}

And AuthorizedEvent will be published after the user has enough permission to execute a protected method .So create a ApplicationListener to listen and handle it :

@Component
public class MyEventListener implements ApplicationListener<AuthorizedEvent> {

    @Override
    public void onApplicationEvent(AuthorizedEvent event) {
        //Handle the AuthorizedEvent event here......
    }
}


来源: stackexchange

问:
Proper way to structure a program formed by 3 sub-programs
I'm building a system formed by 3 programs, lets call them A, B and C. Right now I think that my file structure is a disaster.

Inside my root folder I have some shortcuts to .bat files that run the programs and a folder called programs_data. Inside that folder I have 4 separate folders, one for each program plus a common folder.
The issue is that I need each program and the sub-scripts in those programs to be able to import from the common folder and I need program C and B to be able to call program A API.

As it is right now, I have a mess of appending to sys.path in the sub files to import functions from upper levels.

What's the correct way to structure something like this?

Current structure:

```<code>root
├── Configuration.lnk
├── Documentation.lnk
├── Program A.lnk
├── Program B.lnk
├── Program C.lnk
├── programs_data
│   ├── Program A
│   │   ├── Program A API.py
│   │   ├── Program A.bat
│   │   ├── Program A.py
│   │   ├── src
│   │   │   ├── server.py
│   │   │   ├── test_functions.py
│   │   │   └── validation.py
│   │   └── targets
│   │       ├── sql_querys
│   │       │   ├── query1.sql
│   │       │   ├── query2.sql
│   │       │   └── queryn.sql
│   │       ├── target1.py
│   │       ├── target2.py
│   │       ├── target3.py
│   │       └── targetn.py
│   ├── Program B
│   │   ├── Program B.bat
│   │   ├── Program B.py
│   │   ├── classifiers
│   │   │   ├── classifier1.py
│   │   │   ├── classifier2.py
│   │   │   └── classifiern.py
│   │   ├── events.log
│   │   ├── o365_token.txt
│   │   └── src
│   │       ├── batchECImport.py
│   │       ├── classifier.py
│   │       └── logger.py
│   ├── Program C
│   │   ├── Program C.bat
│   │   ├── Program C.py
│   │   ├── Reports
│   │   │   ├── report 1
│   │   │   │   └── report.py
│   │   │   └── report 2
│   │   │       └── report.py
│   │   ├── o365_token.txt
│   │   ├── schedule.xlsx
│   │   └── src
│   │       └── report.py
│   └── common
│       ├── APIMailboxManager.py
│       ├── Documentation
│       │   └── Documentation.pdf
│       ├── FlexibleProcess.py
│       ├── config.py
│       ├── misc.py
│       ├── print_functions.py
│       ├── production_support_passwords.py
│       ├── reports_log.db
│       └── reports_log.py
└── schedule spreadsheet.Ink
</code>```

Thanks!

答:
I would suggest to put your root folder to the PYTHONPATH environment variable (https://www.tutorialspoint.com/What-is-PYTHONPATH-environment-variable-in-Python) so that you don't have to append to the sys.path.

That way you can easily write code like this

from root.programs_data.src import server

ContentLicense: CC BY-SA 4.0

Body:
I'm building a system formed by 3 programs, lets call them A, B and C. Right now I think that my file structure is a disaster.

Inside my root folder I have some shortcuts to .bat files that run the programs and a folder called programs_data. Inside that folder I have 4 separate folders, one for each program plus a common folder.
The issue is that I need each program and the sub-scripts in those programs to be able to import from the common folder and I need program C and B to be able to call program A API.

As it is right now, I have a mess of appending to sys.path in the sub files to import functions from upper levels.

What's the correct way to structure something like this?

Current structure:

root
├── Configuration.lnk
├── Documentation.lnk
├── Program A.lnk
├── Program B.lnk
├── Program C.lnk
├── programs_data
│   ├── Program A
│   │   ├── Program A API.py
│   │   ├── Program A.bat
│   │   ├── Program A.py
│   │   ├── src
│   │   │   ├── server.py
│   │   │   ├── test_functions.py
│   │   │   └── validation.py
│   │   └── targets
│   │       ├── sql_querys
│   │       │   ├── query1.sql
│   │       │   ├── query2.sql
│   │       │   └── queryn.sql
│   │       ├── target1.py
│   │       ├── target2.py
│   │       ├── target3.py
│   │       └── targetn.py
│   ├── Program B
│   │   ├── Program B.bat
│   │   ├── Program B.py
│   │   ├── classifiers
│   │   │   ├── classifier1.py
│   │   │   ├── classifier2.py
│   │   │   └── classifiern.py
│   │   ├── events.log
│   │   ├── o365_token.txt
│   │   └── src
│   │       ├── batchECImport.py
│   │       ├── classifier.py
│   │       └── logger.py
│   ├── Program C
│   │   ├── Program C.bat
│   │   ├── Program C.py
│   │   ├── Reports
│   │   │   ├── report 1
│   │   │   │   └── report.py
│   │   │   └── report 2
│   │   │       └── report.py
│   │   ├── o365_token.txt
│   │   ├── schedule.xlsx
│   │   └── src
│   │       └── report.py
│   └── common
│       ├── APIMailboxManager.py
│       ├── Documentation
│       │   └── Documentation.pdf
│       ├── FlexibleProcess.py
│       ├── config.py
│       ├── misc.py
│       ├── print_functions.py
│       ├── production_support_passwords.py
│       ├── reports_log.db
│       └── reports_log.py
└── schedule spreadsheet.Ink

Thanks!


问:
how to make json web service in asp.net?
I m making web service for the first time. and i need to make that using json in c#. I m not getting how to code the methods that fetch data from database
Any suggessions.</p>

答: Try this How To Create A JSON Web Service In ASP.NET</p>

ContentLicense: CC BY-SA 3.0


问:
View Serializable and conflict serializable
I was reading about serializability in schedules of transactions and therefore read about conflict serializable and view serializable schedules.

Now because conflict serializable is more stringent than view serializable , it is obvious that there will be schedules that are view serializable but not conflict serializable.In the book I read the following:

Blind writes appear in any schedule that is view serializable but not
  conflict seralizable.

I have been trying to come up with a proof of the above statement but could not do it.

My question is : Is there a formal proof of the above mentioned statement?

答:
Main idea of a view serializable schedule is that each read operation of a transaction should read the result of the same write operation in all schedules, thereby having the same "view" of the database. </p>

<p>For a schedule that is not conflict serializable but is view serializable, there exists a conflict in the schedules but the "view" of the DB is maintained. This would imply that each read operation reads the same results/values across schedules, and that the conflicting operations are writes. As the conflicting operations do not change the view of the database, it must mean that the write operations are blind, as they are not writing a new or different value by reading an updated or old value from the database. Thus, these operations must be blind writes. </p>

Body:
Main idea of a view serializable schedule is that each read operation of a transaction should read the result of the same write operation in all schedules, thereby having the same "view" of the database.

For a schedule that is not conflict serializable but is view serializable, there exists a conflict in the schedules but the "view" of the DB is maintained. This would imply that each read operation reads the same results/values across schedules, and that the conflicting operations are writes. As the conflicting operations do not change the view of the database, it must mean that the write operations are blind, as they are not writing a new or different value by reading an updated or old value from the database. Thus, these operations must be blind writes.


问:
`$request->ajax()` does not detect ajax request when using Fetch API to pull data in Laravel
In my Laravel app, I am using Fetch API to load data on scroll. Below is my JS code in blade file

let route = '{{ route("load") }}' + '?q=' + encodeURI('{{ $para }}');
fetch(route)
.then(response => {
   if(!response.ok) {
       throw new Error('Network response was not ok');
   }
   return response.text();
})
.then(data => {
   console.log(data);
})
.catch((error) => {
   console.error('Error:', error);
})
```

<p>And in my controller</p>

<pre class="lang-php prettyprint-override"><code>public function loadData( Request $request )
{
    if( $request->ajax() ) {

       return $request->query('q');

     }
     return 'Not Ajax!';
}
</code>```

It always return 'Not Ajax!';

I am not sure why this is happening. It was not a problem with other libraries like jQuery or Axios

答:
Be careful when using "return" in your methods. Try enclosing return 'Not Ajax!'; in else</p>

```<code>else{
    return 'Not Ajax!';
}
</code>```

Body:
In my Laravel app, I am using Fetch API to load data on scroll. Below is my JS code in blade file

let route = '{{ route("load") }}' + '?q=' + encodeURI('{{ $para }}');
fetch(route)
.then(response => {
   if(!response.ok) {
       throw new Error('Network response was not ok');
   }
   return response.text();
})
.then(data => {
   console.log(data);
})
.catch((error) => {
   console.error('Error:', error);
})

And in my controller

public function loadData( Request $request )
{
    if( $request->ajax() ) {

       return $request->query('q');

     }
     return 'Not Ajax!';
}

It always return 'Not Ajax!';

I am not sure why this is happening. It was not a problem with other libraries like jQuery or Axios

Body:
Be careful when using "return" in your methods. Try enclosing return 'Not Ajax!'; in else

else{
    return 'Not Ajax!';
}


答:
Request::ajax() checks for the existance of the X-Requested-With header.

Since you're using fetch, you have to manually add this header to the options object:

```<code>fetch(route, {
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  },
})
</code>```

Axios, for example, uses this by default due to how the bootstrap.js file is set up. jQuery adds it automatically for every request but cross-domain requests.

Title: `$request->ajax()` does not detect ajax request when using Fetch API to pull data in Laravel

Body:
Request::ajax() checks for the existance of the X-Requested-With header.

Since you're using fetch, you have to manually add this header to the options object:

fetch(route, {
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  },
})

Axios, for example, uses this by default due to how the bootstrap.js file is set up. jQuery adds it automatically for every request but cross-domain requests.


问:
Azure APIM with logic app: definition ignored?
I have a logic app as API (via APIM) with a HTTP Request trigger for posts.
In APIM I have created a schema definition for requests

Simplified example:

```<code>{
"properties": {
    "id": {
        "type": "string"
    },
    "email": {
        "type": "string"
    }
},
"required": [
    "id",
    "email"
],
"type": "object"
}
</code>```

However, when I test, the post isn't validated. I can input numbers instead of strings or send a completely empty message.

If I set up the same schema inside the logic app trigger the validation is fine but I would prefer to keep the definition in APIM so I won't have to manage schemas for both logic app and APIM for front end.

I think this has worked before, I remember having a similar logic app API where schema validation in APIM was possible.

Is there something I'm missing?

答:
After importing logic app to Azure APIM, the wizard will expose for you the Logic App under a POST operation. By default, the operation name will always be “request-invoke”.

To test the Logic App exposed to Azure API Management you need to:

Under the API top options menu, select Test option, and in this case, there is only one operation which will automatically get selected;

On the Request body section, select Raw option and insert a valid and expected request to be sent to the Logic App;

And finally, press “Send”.

And after that, you will see an expected response from the Logic App.

For more details about how to expose and protect Logic App using Azure API Management, you can refer to this article.

Body:
I have a logic app as API (via APIM) with a HTTP Request trigger for posts.
In APIM I have created a schema definition for requests

Simplified example:

{
"properties": {
    "id": {
        "type": "string"
    },
    "email": {
        "type": "string"
    }
},
"required": [
    "id",
    "email"
],
"type": "object"
}

However, when I test, the post isn't validated. I can input numbers instead of strings or send a completely empty message.

If I set up the same schema inside the logic app trigger the validation is fine but I would prefer to keep the definition in APIM so I won't have to manage schemas for both logic app and APIM for front end.

I think this has worked before, I remember having a similar logic app API where schema validation in APIM was possible.

Is there something I'm missing?


问:
How does a Git repository works with a develop and master branch?
I'm new to Git and this is really confusing. I wanted to start off developing a web application on Git and so far I've been dealing with troubles that have kept me behind.

I've read this blog post on a successful branching model for Git. I was really interested in setting up something similar to this.

It says that the repository has 2 main branches called master and develop. So I went ahead and created a repository. However, to my surprise, the repository itself was the default master branch. How was I supposed to create a develop branch? Do I create it in the parent of the master branch? That would mean that the develop branch is outside the repository.

Am I getting something totally wrong here? Do I just ignore the fact that I'm creating two branches inside the master branch?

答:
The master branch is created by default; you can think of it like the "trunk" in other VCS systems. The develop branch used in the nvie branching model branches from master, presumably from the first commit.

The develop branch is a normal branch off of master.

git branch develop creates the develop branch.

In the nvie branching model, all development work is done on the develop branch and only merged to master and tagged there when the code is ready to be released. The typical workflow that many people use is just to commit all development to master and tag when the code is ready to be released.


问:
How to make a checkbox into a button
I am trying to achieve this with only css, and make it clickable/ active the answers have not been so helpful, what will the css specificity part be?

#ck-button {
  margin-bottom: 1rem;
}

#ck-button label {
  width: 85%;
  border: 2px solid #eaf2fd;
  padding: 15px;
  border-radius: 3px;
  display: flex;
}

#ck-button label span {
  padding: 3px 0px;
}
#ck-button .title {
  color: #304256;
  font-weight: 600;
  font-size: 1em;
}
#ck-button .description {
  color: #6984a3;
  font-weight: 400;
  margin-left: 7px;
  font-size: 15px;
}
#ck-button label input {
  position: absolute;
  top: -20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="ck-button">
    <label id="label">
        <input id="checkbox" type="checkbox" value="1" />
        <span className="title">Respirators</span>
        <span className="description">
            Surgical N95 or equivalent
        </span>
    </label>
</div></code>```

this is the link on js fiddle for a proper look
https://jsfiddle.net/oLa4162h/

答:
You can have it like this using + CSS Adjacent sibling combinator combined with :checked CSS selector for checkbox, note that I did a small change to the HTML and css, I added a container div right next to the <input> and applied the CSS to it:

#ck-button {
  margin-bottom: 1rem;
}

#ck-button .container {
  width: 85%;
  border: 2px solid #eaf2fd;
  padding: 15px;
  border-radius: 3px;
  display: flex;
}

#ck-button label span {
  padding: 3px 0px;
}
#ck-button .title {
  color: #304256;
  font-weight: 600;
  font-size: 1em;
}
#ck-button .description {
  color: #6984a3;
  font-weight: 400;
  margin-left: 7px;
  font-size: 15px;
}
#ck-button label input {
  position: absolute;
  top: -20px;
}

#checkbox:checked + .container {
  border: 2px solid #2F81ED;
  color: #2F81ED;
  background-color: #F5F8FD;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="ck-button">
  <label id="label">
    <input id="checkbox" type="checkbox" value="1" />
    <div class="container">
      <span className="title">Respirators </span>
      <span className="description">
        Surgical N95 or equivalent
      </span>
    </div>
  </label>
</div></code>```

Title: How to make a checkbox into a button

Body:
I am trying to achieve this with only css, and make it clickable/ active the answers have not been so helpful, what will the css specificity part be?

#ck-button {
  margin-bottom: 1rem;
}

#ck-button label {
  width: 85%;
  border: 2px solid #eaf2fd;
  padding: 15px;
  border-radius: 3px;
  display: flex;
}

#ck-button label span {
  padding: 3px 0px;
}
#ck-button .title {
  color: #304256;
  font-weight: 600;
  font-size: 1em;
}
#ck-button .description {
  color: #6984a3;
  font-weight: 400;
  margin-left: 7px;
  font-size: 15px;
}
#ck-button label input {
  position: absolute;
  top: -20px;
}

        <input id="checkbox" type="checkbox" value="1" />
        Respirators

            Surgical N95 or equivalent

this is the link on js fiddle for a proper look
https://jsfiddle.net/oLa4162h/

Body:
You can have it like this using + CSS Adjacent sibling combinator combined with :checked CSS selector for checkbox, note that I did a small change to the HTML and css, I added a container div right next to the <input> and applied the CSS to it:

#ck-button {
  margin-bottom: 1rem;
}

#ck-button .container {
  width: 85%;
  border: 2px solid #eaf2fd;
  padding: 15px;
  border-radius: 3px;
  display: flex;
}

#ck-button label span {
  padding: 3px 0px;
}
#ck-button .title {
  color: #304256;
  font-weight: 600;
  font-size: 1em;
}
#ck-button .description {
  color: #6984a3;
  font-weight: 400;
  margin-left: 7px;
  font-size: 15px;
}
#ck-button label input {
  position: absolute;
  top: -20px;
}

#checkbox:checked + .container {
  border: 2px solid #2F81ED;
  color: #2F81ED;
  background-color: #F5F8FD;
}

<div id="ck-button">
  <label id="label">
    <input id="checkbox" type="checkbox" value="1" />
    <div class="container">
      <span className="title">Respirators </span>
      <span className="description">
        Surgical N95 or equivalent
      </span>
    </div>
  </label>
</div>


问:
Get non-overlapping distinct intervals from a set of intervals Python
Given a set of intervals, I would like to find non-overlapping distinct intervals from a set of intervals.

For example:

Input: [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

Output: [[1,5], [21,22], [23,24], [25,30], [50,55], [60,70]]

How can I do that?

What I have currently tried:

```<code>gene_bounds_list = [[1,10],[5,20], [6,21],[17,25],[22,23], [24,50],[30,55],[60,70]]
overlap_list = []
nonoverlap_list = []
nonoverlap_list.append(gene_bounds_list[0])

for i in range(1, len(gene_bounds_list)):
    curr_gene_bounds = gene_bounds_list[i]
    prev_gene_bounds = nonoverlap_list[-1]

    if curr_gene_bounds[0]<prev_gene_bounds[0]:
        if curr_gene_bounds[1]<prev_gene_bounds[0]: #case1
            continue
        if curr_gene_bounds[1] < prev_gene_bounds[1]:  #case2
            nonoverlap_list[-1][0] = curr_gene_bounds[1]
        if curr_gene_bounds[1]>prev_gene_bounds[1]:
            # previous gene was completely overlapping within current gene,
            # so replace previous gene by current (bigger) gene and put previous gene into overlap list
            overlap_list.append(nonoverlap_list[-1])
            new_bound = [gene_bounds_list[i][0], gene_bounds_list[i][1]]
            nonoverlap_list.pop()
            nonoverlap_list.append([new_bound[0], new_bound[1]])

    elif curr_gene_bounds[0] > prev_gene_bounds[0] and curr_gene_bounds[1] < prev_gene_bounds[1]:
        # completely within another gene
        overlap_list.append([curr_gene_bounds[0], curr_gene_bounds[1]])

    elif curr_gene_bounds[0] < prev_gene_bounds[1]:
        # partially overlapping with another gene
        new_bound = [nonoverlap_list[-1][1], curr_gene_bounds[1]]
        nonoverlap_list[-1][1] = curr_gene_bounds[0]
        nonoverlap_list.append([new_bound[0], new_bound[1]])

    else:
        # not overlapping with another gene
        nonoverlap_list.append([gene_bounds_list[i][0], gene_bounds_list[i][1]])

unique_data = [list(x) for x in set(tuple(x) for x in gene_bounds_list)]
within_overlapping_intervals = []

for small in overlap_list:
    for master in unique_data:
        if (small[0]==master[0] and small[1]==master[1]):
            continue
        if (small[0]>master[0] and small[1]<master[1]):
            if(small not in within_overlapping_intervals):
                within_overlapping_intervals.append([small[0], small[1]])

for o in within_overlapping_intervals:
    nonoverlap_list.append(o)  # append the overlapping intervals

nonoverlap_list.sort(key=lambda tup: tup[0])
flat_data = sorted([x for sublist in nonoverlap_list for x in sublist])
new_gene_intervals = [flat_data[i:i + 2] for i in range(0, len(flat_data), 2)]
print(new_gene_intervals)
</code>```

However, this gives me an output of: [[1, 5], [6, 10], [17, 20], [21, 22], [23, 24], [25, 30], [50, 55], [60, 70]]

Any ideas of how I can remove the unwanted intervals?

答:
Here is a way to do it. The idea is to keep track of the number of layers of intervals at any point. For this, we add one layer when entering an interval, and remove one when exiting.

We start by building sorted lists of starts and ends.  In order to identify the if a value is a start or an end, we create tuples (start, 1) or (end, -1).

Then, we  merge these two lists, sorting by value, and iterate over the resulting list (using heapq.merge makes this easy).
Each time the number of layers changes to 1, we have the start of a non-overlapping interval. When it changes again, it's the end of it.

```<code>from heapq import merge

def non_overlapping(data):
    out = []
    starts = sorted([(i[0], 1) for i in data])  # start of interval adds a layer of overlap
    ends = sorted([(i[1], -1) for i in data])   # end removes one
    layers = 0
    current = []
    for value, event in merge(starts, ends):    # sorted by value, then ends (-1) before starts (1)
        layers += event
        if layers ==1:  # start of a new non-overlapping interval
            current.append(value)
        elif current:  # we either got out of an interval, or started an overlap
            current.append(value)
            out.append(current)
            current = []
    return out

data = [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

non_overlapping(data)
# [[1, 5], [21, 22], [23, 24], [25, 30], [50, 55], [60, 70]]
</code>```

Note that the expected answer you put in your question is wrong (for example, it contains a 45 that isn't part of the input data)

Body:
Given a set of intervals, I would like to find non-overlapping distinct intervals from a set of intervals.

For example:

Input: [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

Output: [[1,5], [21,22], [23,24], [25,30], [50,55], [60,70]]

How can I do that?

What I have currently tried:

gene_bounds_list = [[1,10],[5,20], [6,21],[17,25],[22,23], [24,50],[30,55],[60,70]]
overlap_list = []
nonoverlap_list = []
nonoverlap_list.append(gene_bounds_list[0])

for i in range(1, len(gene_bounds_list)):
    curr_gene_bounds = gene_bounds_list[i]
    prev_gene_bounds = nonoverlap_list[-1]

    if curr_gene_bounds[0]<prev_gene_bounds[0]:
        if curr_gene_bounds[1]<prev_gene_bounds[0]: #case1
            continue
        if curr_gene_bounds[1] < prev_gene_bounds[1]:  #case2
            nonoverlap_list[-1][0] = curr_gene_bounds[1]
        if curr_gene_bounds[1]>prev_gene_bounds[1]:
            # previous gene was completely overlapping within current gene,
            # so replace previous gene by current (bigger) gene and put previous gene into overlap list
            overlap_list.append(nonoverlap_list[-1])
            new_bound = [gene_bounds_list[i][0], gene_bounds_list[i][1]]
            nonoverlap_list.pop()
            nonoverlap_list.append([new_bound[0], new_bound[1]])

    elif curr_gene_bounds[0] > prev_gene_bounds[0] and curr_gene_bounds[1] < prev_gene_bounds[1]:
        # completely within another gene
        overlap_list.append([curr_gene_bounds[0], curr_gene_bounds[1]])

    elif curr_gene_bounds[0] < prev_gene_bounds[1]:
        # partially overlapping with another gene
        new_bound = [nonoverlap_list[-1][1], curr_gene_bounds[1]]
        nonoverlap_list[-1][1] = curr_gene_bounds[0]
        nonoverlap_list.append([new_bound[0], new_bound[1]])

    else:
        # not overlapping with another gene
        nonoverlap_list.append([gene_bounds_list[i][0], gene_bounds_list[i][1]])

unique_data = [list(x) for x in set(tuple(x) for x in gene_bounds_list)]
within_overlapping_intervals = []

for small in overlap_list:
    for master in unique_data:
        if (small[0]==master[0] and small[1]==master[1]):
            continue
        if (small[0]>master[0] and small[1]<master[1]):
            if(small not in within_overlapping_intervals):
                within_overlapping_intervals.append([small[0], small[1]])

for o in within_overlapping_intervals:
    nonoverlap_list.append(o)  # append the overlapping intervals

nonoverlap_list.sort(key=lambda tup: tup[0])
flat_data = sorted([x for sublist in nonoverlap_list for x in sublist])
new_gene_intervals = [flat_data[i:i + 2] for i in range(0, len(flat_data), 2)]
print(new_gene_intervals)

However, this gives me an output of: [[1, 5], [6, 10], [17, 20], [21, 22], [23, 24], [25, 30], [50, 55], [60, 70]]

Any ideas of how I can remove the unwanted intervals?

Body:
Here is a way to do it. The idea is to keep track of the number of layers of intervals at any point. For this, we add one layer when entering an interval, and remove one when exiting.

We start by building sorted lists of starts and ends.  In order to identify the if a value is a start or an end, we create tuples (start, 1) or (end, -1).

Then, we  merge these two lists, sorting by value, and iterate over the resulting list (using heapq.merge makes this easy).
Each time the number of layers changes to 1, we have the start of a non-overlapping interval. When it changes again, it's the end of it.

from heapq import merge

def non_overlapping(data):
    out = []
    starts = sorted([(i[0], 1) for i in data])  # start of interval adds a layer of overlap
    ends = sorted([(i[1], -1) for i in data])   # end removes one
    layers = 0
    current = []
    for value, event in merge(starts, ends):    # sorted by value, then ends (-1) before starts (1)
        layers += event
        if layers ==1:  # start of a new non-overlapping interval
            current.append(value)
        elif current:  # we either got out of an interval, or started an overlap
            current.append(value)
            out.append(current)
            current = []
    return out

data = [[1,10], [5,20], [6,21], [17,25], [22,23], [24,50] ,[30,55], [60,70]]

non_overlapping(data)
# [[1, 5], [21, 22], [23, 24], [25, 30], [50, 55], [60, 70]]

Note that the expected answer you put in your question is wrong (for example, it contains a 45 that isn't part of the input data)


问:
Using a template with lambda function pointer
I'm playing around with some C++11 features, and I encountered the following:

```<code>#include <iostream>
#include <vector>

template <class T>
void map(std::vector<T>& values, T(*func)(T)) {
    for (int &value : values) {
        value = func(value);
    }
}

int mul2(int x) {
    return 2*x;
}

auto mul3 = [](int value) {
    return value * 3;
};

int main() {
    std::vector<int> v = { 1,2,3,4,5 };
    map(v, mul3);
    for (auto value : v) {
        std::cout << value << std::endl;
    }
}
</code>```

using map with mul2 works as expected, but when I use the mul3 function it gives a compilation error. I expected that auto in this case would give me a int function pointer, but it seems that is not the case here. Anybody could explain this behaviour?

答:
The lambda can implicitly be converted to a function pointer, but that's not what's failing here.  Rather, the compiler is failing to deduce T because the lambda-to-function-pointer conversion doesn't happen during deduction.

```<code>main.cpp:5:6: note:   template argument deduction/substitution failed:
main.cpp:21:16: note:   mismatched types 'T (*)(T)' and '<lambda(int)>'
   21 |     map(v, mul3);
      |                ^
</code>```

The compiler can make the connection between T(*)(T) and int(*)(int) and it can make the connection between int(*)(int) and the lambda type, but it can't make the connection between T(*)(T) and the lambda type.

You can fix this by making one of the two connections for it: explicitly specifying the function's template argument, or casting the lambda to the function pointer type.  The first skips the deduction step an then the implicit lambda-to-function-pointer conversion succeeds.  The second allows deduction to succeed because the second parameter is a compatible function pointer type.

```<code>// Option 1: Specifying T allows implicit conversion of the lambda to fnptr
map<int>(v, mul3);

// Option 2a: Cast of lambda to fnptr allows T to be deduced
map(v, static_cast<int(*)(int)>(mul3));

// Option 2b: Converting lambda to fnptr at mul3 initialization allows T to be deduced
int (*mul3)(int) = [](int value) {
    return value * 3;
};
</code>```

However, I would recommend fixing the issue a different way -- there's no reason the function has to work with vectors, function pointers, and ints.  Why can't it work with linked lists, functors, and doubles?  There's really no reason to constrain the types like this; just let them be whatever they are and see if the instantiation succeeds:

```<code>template <class TContainer, TFunction>
void map(TContainer & values, TFunction const & func) {
    for (auto &value : values) {
        value = func(value);
    }
}
</code>```

Body:
I'm playing around with some C++11 features, and I encountered the following:

#include <iostream>
#include <vector>

template <class T>
void map(std::vector<T>& values, T(*func)(T)) {
    for (int &value : values) {
        value = func(value);
    }
}

int mul2(int x) {
    return 2*x;
}

auto mul3 = [](int value) {
    return value * 3;
};

int main() {
    std::vector<int> v = { 1,2,3,4,5 };
    map(v, mul3);
    for (auto value : v) {
        std::cout << value << std::endl;
    }
}

using map with mul2 works as expected, but when I use the mul3 function it gives a compilation error. I expected that auto in this case would give me a int function pointer, but it seems that is not the case here. Anybody could explain this behaviour?

Body:
The lambda can implicitly be converted to a function pointer, but that's not what's failing here.  Rather, the compiler is failing to deduce T because the lambda-to-function-pointer conversion doesn't happen during deduction.

main.cpp:5:6: note:   template argument deduction/substitution failed:
main.cpp:21:16: note:   mismatched types 'T (*)(T)' and '<lambda(int)>'
   21 |     map(v, mul3);
      |                ^

The compiler can make the connection between T(*)(T) and int(*)(int) and it can make the connection between int(*)(int) and the lambda type, but it can't make the connection between T(*)(T) and the lambda type.

You can fix this by making one of the two connections for it: explicitly specifying the function's template argument, or casting the lambda to the function pointer type.  The first skips the deduction step an then the implicit lambda-to-function-pointer conversion succeeds.  The second allows deduction to succeed because the second parameter is a compatible function pointer type.

// Option 1: Specifying T allows implicit conversion of the lambda to fnptr
map<int>(v, mul3);

// Option 2a: Cast of lambda to fnptr allows T to be deduced
map(v, static_cast<int(*)(int)>(mul3));

// Option 2b: Converting lambda to fnptr at mul3 initialization allows T to be deduced
int (*mul3)(int) = [](int value) {
    return value * 3;
};

However, I would recommend fixing the issue a different way -- there's no reason the function has to work with vectors, function pointers, and ints.  Why can't it work with linked lists, functors, and doubles?  There's really no reason to constrain the types like this; just let them be whatever they are and see if the instantiation succeeds:

template <class TContainer, TFunction>
void map(TContainer & values, TFunction const & func) {
    for (auto &value : values) {
        value = func(value);
    }
}


问:
How can I use lambda expression here?
I have my custom GetVolley Class

class GetVolley(private val mContext: Context, private val url: String, private val onVolleySuccess: OnVolleySuccess?, private val mOnVolleyError: OnVolleyError?, private val mOnVolleyEnd: OnVolleyEnd?) {
    private fun getDataVolley() {
        Log.d("GetVolleyUrl", url)
        val request = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response: JSONObject ->
            Log.d("GetVolleyResult", response.toString())
            if (response.has("result") && response.getBoolean("result")) {
                onVolleySuccess?.onSuccess(response)
            } else if (response.has("message")) {
                if (mOnVolleyError != null) mOnVolleyError.onError(response.getString("message"))
                else Toast.makeText(mContext, response.getString("message"), Toast.LENGTH_LONG).show()
            }
            mOnVolleyEnd?.onEnd()
        }, Response.ErrorListener { volleyError: VolleyError ->
            Log.d("GetVolleyError", volleyError.message.toString())
            val errorMessage: String = if (volleyError is NetworkError || volleyError is AuthFailureError) {
                "No Internet…"
            } else {
                "Undefinded error"
            }
            if (mOnVolleyError != null) mOnVolleyError.onError(errorMessage)
            else Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show()
            mOnVolleyEnd?.onEnd()
        })
        Volley.newRequestQueue(mContext).add(request)
    }

    init {
        getDataVolley()
    }
}
```

<p>Interfaces in different files:</p>

```interface OnVolleySuccess {
    fun onSuccess(response: JSONObject)
}
______________________________________
interface OnVolleyError {
    fun onError(error: String)
}
______________________________________
interface OnVolleyEnd {
    fun onEnd()
}
```

<p>When I use my custom GetVolley request. My code look like:</p>

```GetVolley(this, url, object : OnVolleySuccess {
    override fun onSuccess(response: JSONObject) {
        parseResponse(response)
    }
}, object : OnVolleyError {
    override fun onError(error: String) {
        showError(error)
    }
}, null)
```

<p>I want it to look like this:</p>

```GetVolley(this, url, response -> {
    parseResponse(response)
}, error -> {
    showError(error)
}, null)
```

All my callbacks is nullable, so I can set null onVolleySuccess, onVolleyError, onVolleyEnd.

答:
Note: Use Nicolas solution if you want, as it uses lambda natively if you don't want to use these classes in Java

SAM conversion, i.e. interfaces to callbacks conversion using lambda is only available since Kotlin 1.4, which is in EAP (Early Access Program).

If you have Kotlin 1.4-M1 which is currently being released a few months ago, you can declare your interface with a fun keyword which will make it available to be used as lambda.

fun interface OnVolleySuccess {
    fun onSuccess(response: JSONObject)
}
fun interface OnVolleyError {
    fun onError(error: String)
}
fun interface OnVolleyEnd {
    fun onEnd()
}
```

<p>Now you can use it like this:</p>

<pre class="lang-kotlin prettyprint-override"><code>GetVolley(this, url, { response ->
    parseResponse(response)
}, { error ->
    showError(error)
}, null)

// or simply
GetVolley(this, url, { parseResponse(it) }, { showError(it) }, null)
</code>```

If you are having difficulties in adopting Kotlin 1.4, here's the catch:

```<code>// add/change these in build.gradle:
plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.4-M1'
    // ...
}

repositories {
    // ...
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}

// add these in settings.gradle
pluginManagement {
    repositories {
        mavenCentral()
        maven { "https://dl.bintray.com/kotlin/kotlin-eap" }
        maven { "https://plugins.gradle.org/m2/" }
    }
}
</code>```

Title: How can I use lambda expression here?

Body:
I have my custom GetVolley Class

class GetVolley(private val mContext: Context, private val url: String, private val onVolleySuccess: OnVolleySuccess?, private val mOnVolleyError: OnVolleyError?, private val mOnVolleyEnd: OnVolleyEnd?) {
    private fun getDataVolley() {
        Log.d("GetVolleyUrl", url)
        val request = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response: JSONObject ->
            Log.d("GetVolleyResult", response.toString())
            if (response.has("result") && response.getBoolean("result")) {
                onVolleySuccess?.onSuccess(response)
            } else if (response.has("message")) {
                if (mOnVolleyError != null) mOnVolleyError.onError(response.getString("message"))
                else Toast.makeText(mContext, response.getString("message"), Toast.LENGTH_LONG).show()
            }
            mOnVolleyEnd?.onEnd()
        }, Response.ErrorListener { volleyError: VolleyError ->
            Log.d("GetVolleyError", volleyError.message.toString())
            val errorMessage: String = if (volleyError is NetworkError || volleyError is AuthFailureError) {
                "No Internet…"
            } else {
                "Undefinded error"
            }
            if (mOnVolleyError != null) mOnVolleyError.onError(errorMessage)
            else Toast.makeText(mContext, errorMessage, Toast.LENGTH_LONG).show()
            mOnVolleyEnd?.onEnd()
        })
        Volley.newRequestQueue(mContext).add(request)
    }

    init {
        getDataVolley()
    }
}

Interfaces in different files:

interface OnVolleySuccess {
    fun onSuccess(response: JSONObject)
}
______________________________________
interface OnVolleyError {
    fun onError(error: String)
}
______________________________________
interface OnVolleyEnd {
    fun onEnd()
}

When I use my custom GetVolley request. My code look like:

GetVolley(this, url, object : OnVolleySuccess {
    override fun onSuccess(response: JSONObject) {
        parseResponse(response)
    }
}, object : OnVolleyError {
    override fun onError(error: String) {
        showError(error)
    }
}, null)

I want it to look like this:

GetVolley(this, url, response -> {
    parseResponse(response)
}, error -> {
    showError(error)
}, null)

All my callbacks is nullable, so I can set null onVolleySuccess, onVolleyError, onVolleyEnd.

Body:
Note: Use Nicolas solution if you want, as it uses lambda natively if you don't want to use these classes in Java

SAM conversion, i.e. interfaces to callbacks conversion using lambda is only available since Kotlin 1.4, which is in EAP (Early Access Program).

If you have Kotlin 1.4-M1 which is currently being released a few months ago, you can declare your interface with a fun keyword which will make it available to be used as lambda.

fun interface OnVolleySuccess {
    fun onSuccess(response: JSONObject)
}
fun interface OnVolleyError {
    fun onError(error: String)
}
fun interface OnVolleyEnd {
    fun onEnd()
}

Now you can use it like this:

GetVolley(this, url, { response ->
    parseResponse(response)
}, { error ->
    showError(error)
}, null)

// or simply
GetVolley(this, url, { parseResponse(it) }, { showError(it) }, null)

If you are having difficulties in adopting Kotlin 1.4, here's the catch:

// add/change these in build.gradle:
plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.4-M1'
    // ...
}

repositories {
    // ...
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
}

// add these in settings.gradle
pluginManagement {
    repositories {
        mavenCentral()
        maven { "https://dl.bintray.com/kotlin/kotlin-eap" }
        maven { "https://plugins.gradle.org/m2/" }
    }
}


问:
View contents of a dll
I am looking for a tool to view contents of a C# dll, preferably a free one. .Net Reflector used to be free but not anymore. It is an awesome tool and you can easily see all code down to the line. PE Explorer is another one I looked at but the Disassembler in it does not seem to output C# code. If you know any other tools, please share.
.Net reflector is the best one I know for the job, but just curious if there are any other options.</p>

答:
Telerik just came out with one:

http://www.telerik.com/products/decompiling.aspx

They said that it will ALWAYS be free.  They released it in response to .Net Reflector's change to a pay model.  Right now it is in an open beta (free to download now) and it works great

Edit: as of June 2014, "free" means you must use their bootstrap installer that attempts to bundle other (nonfree) applications. Also, you must register with their "Support System" to complete the install.

Title: View contents of a dll


答:
What you what is called SAM conversions (Single Abstract Method). It's only available to Java interfaces, but will be available to Kotlin interface from Kotlin 1.4. (see this article). Now if you want lambdas, use lambdas:

```<code>class GetVolley(
    private val mContext: Context,
    private val url: String,
    private val onVolleySuccess: ((response: JSONObject) -> Unit)?,
    private val mOnVolleyError: ((error: String) -> Unit)?,
    private val mOnVolleyEnd: (() -> Unit)?
) {
</code>```

And instead of doing:

```<code>onVolleySuccess?.onSuccess(response)
</code>```

You do:

```<code>onVolleySuccess?.invoke(response)
</code>```

Title: How can I use lambda expression here?

Body:
What you what is called SAM conversions (Single Abstract Method). It's only available to Java interfaces, but will be available to Kotlin interface from Kotlin 1.4. (see this article). Now if you want lambdas, use lambdas:

class GetVolley(
    private val mContext: Context,
    private val url: String,
    private val onVolleySuccess: ((response: JSONObject) -> Unit)?,
    private val mOnVolleyError: ((error: String) -> Unit)?,
    private val mOnVolleyEnd: (() -> Unit)?
) {

And instead of doing:

onVolleySuccess?.onSuccess(response)

You do:

onVolleySuccess?.invoke(response)


问:
Data Factory - Retrieve value from field with dash "-" from JSON file
In my pipeline I reach through REST API using GET request to a 3rd party database. As an output I receive  a bunch of JSON files. The number of JSON files I have to download (same as number of iterations I will have to use) is in one of the fields in JSON file. The problem is that the field's name is 'page-count' which contains "-".

```<code>@activity('Lookup1').output.firstRow.meta.page.page-count
</code>```

Data Factory considers dash in field's name as a minus sign, so I get an error instead of value from that field.

```<code>{"code":"BadRequest","message":"ErrorCode=InvalidTemplate, ErrorMessage=Unable to parse expression 'activity('Lookup1').output.firstRow.meta.page.['page-count']'","target":"pipeline/Product_pull/runid/f615-4aa0-8fcb-5c0a144","details":null,"error":null}
</code>```

This is how the structure of JSON file looks like:

```<code> "firstRow": {
        "meta": {
            "page": {
                "number": 1,
                "size": 1,
                "page-count": 7300,
                "record-count": 7300
            },
            "non-compliant-record-count": 7267
        }
    },
    "effectiveIntegrationRuntime": "intergrationRuntimeTest1",
    "billingReference": {
        "activityType": "PipelineActivity",
        "billableDuration": [
            {
                "meterType": "SelfhostedIR",
                "duration": 0.016666666666666666,
                "unit": "Hours"
            }
        ]
    },
    "durationInQueue": {
        "integrationRuntimeQueue": 1
    }
}
</code>```

How to solve this problem?

答:
The below syntax works when retrieving the value for a json element with a hyphen.  It is otherwise treated as a minus sign by the parser. It does not seem to be documented by Microsoft however I managed to get this to work through trial and error on a project of mine.</p>
```<code>@activity('Lookup1').output.firstRow.meta.page['page-count']
</code>```

Body:
In my pipeline I reach through REST API using GET request to a 3rd party database. As an output I receive  a bunch of JSON files. The number of JSON files I have to download (same as number of iterations I will have to use) is in one of the fields in JSON file. The problem is that the field's name is 'page-count' which contains "-".

@activity('Lookup1').output.firstRow.meta.page.page-count

Data Factory considers dash in field's name as a minus sign, so I get an error instead of value from that field.

{"code":"BadRequest","message":"ErrorCode=InvalidTemplate, ErrorMessage=Unable to parse expression 'activity('Lookup1').output.firstRow.meta.page.['page-count']'","target":"pipeline/Product_pull/runid/f615-4aa0-8fcb-5c0a144","details":null,"error":null}

This is how the structure of JSON file looks like:

 "firstRow": {
        "meta": {
            "page": {
                "number": 1,
                "size": 1,
                "page-count": 7300,
                "record-count": 7300
            },
            "non-compliant-record-count": 7267
        }
    },
    "effectiveIntegrationRuntime": "intergrationRuntimeTest1",
    "billingReference": {
        "activityType": "PipelineActivity",
        "billableDuration": [
            {
                "meterType": "SelfhostedIR",
                "duration": 0.016666666666666666,
                "unit": "Hours"
            }
        ]
    },
    "durationInQueue": {
        "integrationRuntimeQueue": 1
    }
}

How to solve this problem?

Body:
The below syntax works when retrieving the value for a json element with a hyphen.  It is otherwise treated as a minus sign by the parser. It does not seem to be documented by Microsoft however I managed to get this to work through trial and error on a project of mine.

@activity('Lookup1').output.firstRow.meta.page['page-count']


问:
how to define location in an entity using mongodb
I am using nest js in my sample application. I define the entity of my application .Entity means a document. But I struck at one place to define the location.

using mongoose I define the schema of my document like this see link

https://raw.githubusercontent.com/webmakaka/Node.js-API-Masterclass-With-Express-MongoDB/master/api/models/Bootcamp.js

```<code>location: {
      // GeoJSON Point
      type: {
        type: String,
        enum: ['Point']
      },
      coordinates: {
        type: [Number],
        index: '2dsphere'
      },
      formattedAddress: String,
      street: String,
      city: String,
      state: String,
      zipcode: String,
      country: String
    },
    careers: {
      // Array of strings
      type: [String],
      required: true,
      enum: [
        'Web Development',
        'Mobile Development',
        'UI/UX',
        'Data Science',
        'Business',
        'Other'
      ]
    },
</code>```

same thing I want to do using typeorm using mongoDB without mongoos .can you please help me how I will do that.

here is my entity class

```<code>import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, ManyToOne, ObjectID, ObjectIdColumn } from 'typeorm';
import { IsNotEmpty, MaxLength } from 'class-validator';

@Entity('bootcamp')
export class BootcampEntity extends BaseEntity {
  @ObjectIdColumn() id: ObjectID;

  @Column({type:'text',unique:true,length:50,nullable: false})
  name:string;

  @Column({type:'text'})
  slug: string;

  @Column({type:'text',length:500,nullable: false})
  description: string;

  @Column({type:'text'})
  website: string;

  @Column({type:'text',length:20})
  phone: string;

  @Column({type:'text',})
  email: string;

  @Column({type:'text',nullable: false})
  address: string;

  @Column({type:'text',array: true })
  careers: string[];

  @Column({type:'int'})
  averageRating:number

  @Column({type:'int'})
  averageCost:number
  //
  @Column({type:'string',default:'no-photo.jpg'})
  photo: string;
  //
  @Column({type:'boolean',default:false})
  housing: boolean;

  @Column({type:'boolean',default:false})
  jobAssistance: boolean;

  @Column({type:'boolean',default:false})
  jobGuarantee: boolean;

  @Column({type:'boolean',default:false})
  acceptGi: boolean;

  @Column({type:'date',default:Date.now()})
  createdAt: Date;

}
</code>```

I am using this framework

https://docs.nestjs.com/

typeorm link
https://typeorm.io/#/entities

there is schema

https://raw.githubusercontent.com/webmakaka/Node.js-API-Masterclass-With-Express-MongoDB/master/api/models/Bootcamp.js

I want make same schema using typeorm .I struck only defining the location attribute ?

how to define ?could you please tell me how I will define location in my entity class ?

答:
I think location would have similar structure to code below.

source 1
source 2

enum GeoJSONPoint {
  Point = "Point"
}

enum Careers {
  WebDevelopment = 'Web Development',
  MobileDevelopment = 'Mobile Development',
  UIUX = 'UI/UX',
  DataScience = 'Data Science',
  Business = 'Business',
  Other = 'Other'
}

@Entity('location')
export class LocationEntity extends BaseEntity {

  @Column({
    type: "enum",
    enum: GeoJSONPoint
  })
  type: GeoJSONPoint;

  @Column({type:'int'})
  coordinates: number;

  @Column({type:'text'})
  formattedAddress: string;

  @Column({type:'text'})
  street: string;

  @Column({type:'text'})
  city: string;

  @Column({type:'text'})
  state: string;

  @Column({type:'text'})
  zipcode: string;

  @Column({type:'text'})
  country: string;

  @Column({type:'simple-array'})
  careers: Careers[];
}
```

Body:
I am using nest js in my sample application. I define the entity of my application .Entity means a document. But I struck at one place to define the location.

using mongoose I define the schema of my document like this see link

https://raw.githubusercontent.com/webmakaka/Node.js-API-Masterclass-With-Express-MongoDB/master/api/models/Bootcamp.js

location: {
      // GeoJSON Point
      type: {
        type: String,
        enum: ['Point']
      },
      coordinates: {
        type: [Number],
        index: '2dsphere'
      },
      formattedAddress: String,
      street: String,
      city: String,
      state: String,
      zipcode: String,
      country: String
    },
    careers: {
      // Array of strings
      type: [String],
      required: true,
      enum: [
        'Web Development',
        'Mobile Development',
        'UI/UX',
        'Data Science',
        'Business',
        'Other'
      ]
    },

same thing I want to do using typeorm using mongoDB without mongoos .can you please help me how I will do that.

here is my entity class

import { BaseEntity, Entity, PrimaryGeneratedColumn, Column, ManyToOne, ObjectID, ObjectIdColumn } from 'typeorm';
import { IsNotEmpty, MaxLength } from 'class-validator';

@Entity('bootcamp')
export class BootcampEntity extends BaseEntity {
  @ObjectIdColumn() id: ObjectID;

  @Column({type:'text',unique:true,length:50,nullable: false})
  name:string;

  @Column({type:'text'})
  slug: string;

  @Column({type:'text',length:500,nullable: false})
  description: string;

  @Column({type:'text'})
  website: string;

  @Column({type:'text',length:20})
  phone: string;

  @Column({type:'text',})
  email: string;

  @Column({type:'text',nullable: false})
  address: string;

  @Column({type:'text',array: true })
  careers: string[];

  @Column({type:'int'})
  averageRating:number

  @Column({type:'int'})
  averageCost:number
  //
  @Column({type:'string',default:'no-photo.jpg'})
  photo: string;
  //
  @Column({type:'boolean',default:false})
  housing: boolean;

  @Column({type:'boolean',default:false})
  jobAssistance: boolean;

  @Column({type:'boolean',default:false})
  jobGuarantee: boolean;

  @Column({type:'boolean',default:false})
  acceptGi: boolean;

  @Column({type:'date',default:Date.now()})
  createdAt: Date;

}

I am using this framework

https://docs.nestjs.com/

typeorm link
https://typeorm.io/#/entities

there is schema

https://raw.githubusercontent.com/webmakaka/Node.js-API-Masterclass-With-Express-MongoDB/master/api/models/Bootcamp.js

I want make same schema using typeorm .I struck only defining the location attribute ?

how to define ?could you please tell me how I will define location in my entity class ?


问:
App is crashing after trying to show a UIAlert if the user hasn't granted permission for notifications
I have the following code, which is designed to ask permission to send notifications to the user and then if they don't grant permission, the app gives them a warning in the form of a UIAlert - this is because on the previous screen they selected if they want notifications and the time they want them, and therefore it wouldn't make sense for them to not give permission here.

```<code>let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in

    if !granted {
        let permissionNotGrantedAlert = UIAlertController(title: "Notifications not enabled", message: "We won't be able to send you notifications.\n\nYou can allow us to send you notifications from your device's settings.", preferredStyle: .alert)
        permissionNotGrantedAlert.addAction(UIAlertAction(title: "Go to settings", style: .default, handler: { action in
            UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        permissionNotGrantedAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        }))
        self.present(permissionNotGrantedAlert, animated: true)
    }

    if let error = error {
        print(error)
    }
}
</code>```

The problem is that when the app runs, this exception is thrown:

```<code>Exception: "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread."
</code>```

And this error message is shown in the console:

```<code>[Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behaviour.
</code>```

How can I go about displaying a UIAlert if permission is not granted?

答:
Consider the following code:  </p>

```<code>DispatchQueue.main.async {
    self.present(permissionNotGrantedAlert, animated: true)
}
</code>```

Body:
I have the following code, which is designed to ask permission to send notifications to the user and then if they don't grant permission, the app gives them a warning in the form of a UIAlert - this is because on the previous screen they selected if they want notifications and the time they want them, and therefore it wouldn't make sense for them to not give permission here.

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in

    if !granted {
        let permissionNotGrantedAlert = UIAlertController(title: "Notifications not enabled", message: "We won't be able to send you notifications.\n\nYou can allow us to send you notifications from your device's settings.", preferredStyle: .alert)
        permissionNotGrantedAlert.addAction(UIAlertAction(title: "Go to settings", style: .default, handler: { action in
            UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        permissionNotGrantedAlert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
        }))
        self.present(permissionNotGrantedAlert, animated: true)
    }

    if let error = error {
        print(error)
    }
}

The problem is that when the app runs, this exception is thrown:

Exception: "Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread."

And this error message is shown in the console:

[Animation] +[UIView setAnimationsEnabled:] being called from a background thread. Performing any operation from a background thread on UIView or a subclass is not supported and may result in unexpected and insidious behaviour.

How can I go about displaying a UIAlert if permission is not granted?

Body:
Consider the following code:

DispatchQueue.main.async {
    self.present(permissionNotGrantedAlert, animated: true)
}


问:
OpenCV 4.0.0 SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set
Hello I am trying to create a facial recognition program but I have a peculiar error:
here is my code:

```<code>import cv2 as cv
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_cascade = cv.CascadeClassifier("lbpcascade_frontalface.xml")
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);
</code>```

and this error is the output

```<code>SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set
</code>```

I have "lbpcascade_frontalface.xml" in the working directory so that shouldn't be an issue

if it helps when I enter

```<code>cv.__version__
</code>```

I get

```<code>'4.0.0'
</code>```

答:
As explained by @TylerStrouth above opencv has a directory of cascades in which the cascade files are available, I also faced the same problem while running the code for face detection on Ubuntu 16.04 and solved it as follows

Get the location of opencv using

whereis opencv

Mine was in /usr/share/opencv

Check whether the cascades are present in that location and copy paste the location in cv2.CascadeClassifier along with the required haarcascade

Body:
Hello I am trying to create a facial recognition program but I have a peculiar error:
here is my code:

import cv2 as cv
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
face_cascade = cv.CascadeClassifier("lbpcascade_frontalface.xml")
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5);

and this error is the output

SystemError: <class 'cv2.CascadeClassifier'> returned a result with an error set

I have "lbpcascade_frontalface.xml" in the working directory so that shouldn't be an issue

if it helps when I enter

cv.__version__

I get

'4.0.0'


问:
How to add if else statement in python along with function defination
Sorry to bother i m new to coding just learning python. i just created some code by myself in python  no error shows. but why if else statement not executing. can someone help.

code:

```<code>def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

person = name("Aditya", 17)
print(person)
</code>```

答:
Try this:</p>

```<code>def name(f_name, age):
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")
    return "Hi,", f_name, age

person = name("Aditya", 17)
print(person)
</code>```

Body:
Sorry to bother i m new to coding just learning python. i just created some code by myself in python  no error shows. but why if else statement not executing. can someone help.

code:

def name(f_name, age):
    return f"Hi, {f_name} {age}"
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")

person = name("Aditya", 17)
print(person)

Body:
Try this:

def name(f_name, age):
    if age <= 18:
        print("You are Not eligeble for The post")
    else:
        print("you are eligeble for post")
    return "Hi,", f_name, age

person = name("Aditya", 17)
print(person)


问:
Display js array acquired via JSON to webpage
Sorry if causing troubles again =x

With the help from you guys especially Scott Harwell,  I managed to get my php array passed to js array with the following code:

```<code>var horse_array = <?php echo json_encode($horse_info);?>;
</code>```

However, now I encounter problem in displaying the content of array. I could not load it into my html tag with id="horse1_r".

The following is my js code:

```<code><script type="text/javascript">

var horse_array = <?php echo json_encode($horse_info);?>;

function goto1(hid) {

$("#horse1_r").html(horse_array);

}

</script>
</code>```

Your kind help will be much appreciated.

答:
If you want to return the contents of the Javascript object, you can return it to a string:</p>

```<code>$('#horse1_r').html(JSON.stringify(horse_array));
</code>```

Body:
Sorry if causing troubles again =x

With the help from you guys especially Scott Harwell,  I managed to get my php array passed to js array with the following code:

var horse_array = <?php echo json_encode($horse_info);?>;

However, now I encounter problem in displaying the content of array. I could not load it into my html tag with id="horse1_r".

The following is my js code:

Your kind help will be much appreciated.

Body:
If you want to return the contents of the Javascript object, you can return it to a string:

$('#horse1_r').html(JSON.stringify(horse_array));


问:
Powershell JAR executable occupies instance
I try to write a powershell script to run my Jar, which is just a simple hello world spring web mvc app using tomcat catalina servlet. The problem is that after I execute my Jar file, the powershell instance is occupied by the servlet. Which means I cant run a consecutive command -> open chrome on localhost:8080.

My current powershell script:

```<code>java -jar .\helloworld-0.0.1-SNAPSHOT.jar

# doesnt get executed due to the servlet occupation of the ps instance
Start-Process "chrome.exe" "http://localhost:8080"
</code>```

Is there a way to run the second comand within the same powershell instance, or would I need to open another ps insance? And if, how would I do that?

答:
Executing Java code with java.exe runs the code synchronously, i.e. in a blocking fashion. Therefore, the Start-Process call isn't reached until after the server has shut down, which is obviously not the intent.

You have two basic choices for making the call asynchronous:

Use Start-Process to run the command in a new window (Windows only):

```<code># Opens the server in a *new window* (Windows only)
Start-Process java '-jar .\helloworld-0.0.1-SNAPSHOT.jar'
</code>```

Use a background or thread job (Start-Job or Start-ThreadJob [v6+]), which runs the command in an invisible background process or thread that you can monitor and manage with the *-Job cmdlets:

```<code># Start the server in a background process.
# In PowerShell [Core] 6+ you can use the lighter-weight Start-ThreadJob cmdlet.
# Monitor it with the *-Job cmdlets, such as Receive-Job.
$jb = Start-Job { java -jar .\helloworld-0.0.1-SNAPSHOT.jar }

# Syntactically simpler PowerShell [Core] v6+ alternative:
# (A postpositional & is the same as using Start-Job.
# As of PowerShell 7.0, there is no operator for Start-ThreadJob.)
$jb = java -jar .\helloworld-0.0.1-SNAPSHOT.jar &
</code>```

Use Receive-Job $jb to get the job's output and Stop-Job $jb to stop it (and thereby the server).

Body:
I try to write a powershell script to run my Jar, which is just a simple hello world spring web mvc app using tomcat catalina servlet. The problem is that after I execute my Jar file, the powershell instance is occupied by the servlet. Which means I cant run a consecutive command -> open chrome on localhost:8080.

My current powershell script:

java -jar .\helloworld-0.0.1-SNAPSHOT.jar

# doesnt get executed due to the servlet occupation of the ps instance
Start-Process "chrome.exe" "http://localhost:8080"

Is there a way to run the second comand within the same powershell instance, or would I need to open another ps insance? And if, how would I do that?

Body:
Executing Java code with java.exe runs the code synchronously, i.e. in a blocking fashion. Therefore, the Start-Process call isn't reached until after the server has shut down, which is obviously not the intent.

You have two basic choices for making the call asynchronous:

Use Start-Process to run the command in a new window (Windows only):

# Opens the server in a *new window* (Windows only)
Start-Process java '-jar .\helloworld-0.0.1-SNAPSHOT.jar'

Use a background or thread job (Start-Job or Start-ThreadJob [v6+]), which runs the command in an invisible background process or thread that you can monitor and manage with the *-Job cmdlets:

# Start the server in a background process.
# In PowerShell [Core] 6+ you can use the lighter-weight Start-ThreadJob cmdlet.
# Monitor it with the *-Job cmdlets, such as Receive-Job.
$jb = Start-Job { java -jar .\helloworld-0.0.1-SNAPSHOT.jar }

# Syntactically simpler PowerShell [Core] v6+ alternative:
# (A postpositional & is the same as using Start-Job.
# As of PowerShell 7.0, there is no operator for Start-ThreadJob.)
$jb = java -jar .\helloworld-0.0.1-SNAPSHOT.jar &

Use Receive-Job $jb to get the job's output and Stop-Job $jb to stop it (and thereby the server).


问:
'Shift+Enter' keys navigation sets focus to two cells in the editable column of ag-Grid in Angular 9
I am using a ag-Grid with an editable column named 'Cost'. The requirements are mentioned below:

If the user edits a value in any cell of this column and presses 'Enter' key, the focus should move to the cell below in the same column and turn it into edit mode (I am able to achieve this without any issues)

If the user edits a value in any cell of this column and presses 'Shift + Enter' keys, the focus should move to the cell above in the same column and convert it into edit mode

In the 'Shift + Enter' scenario, the focus moves to the cell above and turns it into edit mode but the focus is also set to a cell two rows below in the same column i.e two cells in the column now have focus, one in edit mode(I need this) and one in non-edit mode(I shouldn't have this) as shown in the image below

The code in the html file is:

```<code><ag-grid-angular
   #agGrid
   style="width:100%; height:100vh"
   id="myGrid"
   class="ag-theme-balham-dark"
   [columnDefs]="columnDefs"
   [defaultColDef]="defaultColDef"
   [singleClickEdit]="true"
   [enterMovesDown]="true"
   [enterMovesDownAfterEdit]="true"
   [autoGroupColumnDef]="autoGroupColumnDef"
   [treeData]="true"
   [rowData]="rowData"
   [groupDefaultExpanded]="groupDefaultExpanded"
   [getDataPath]="getDataPath"
   (cellValueChanged)="onCellValueChanged($event)"
   (keyup)="onKeyUp($event)"
   (gridReady)="onGridReady($event)"
   >
</ag-grid-angular>
</code>```

I am using 'keyup' event for this and the code inside 'onKeyUp' function in the component file is:

```<code>onKeyUp(e) {
  if(e.key === 'Enter') {
    if(e.shiftKey) {
      this.gridApi.startEditingCell({
        rowIndex: (this.gridApi.getFocusedCell().rowIndex - 2),
        colKey: this.gridApi.getFocusedCell().column.colId
      });
    }
    else {
      this.gridApi.startEditingCell({
        rowIndex: this.gridApi.getFocusedCell().rowIndex,
        colKey: this.gridApi.getFocusedCell().column.colId
      });
    }
  }
}
</code>```

I want to get rid of the focus set to cell two rows below the actual cell in edit mode as shown in the image. Please help me with this.

答:
I was finally able to solve the problem. Find 'rowIndex' and 'colKey' for current row and then use clearFocusedCell() to clear the non-required focus before converting the required cell into edit mode.</p>

```<code>onKeyUp(e) {
 if(e.key === 'Enter') {
  if(e.shiftKey) {
     var rowIndex = this.gridApi.getFocusedCell().rowIndex;  <-- Added line
     var colKey = this.gridApi.getFocusedCell().column.colId  <-- Added line
     this.gridApi.clearFocusedCell();  <-- Added line

     this.gridApi.startEditingCell({
       rowIndex: (rowIndex - 2),
       colKey: colKey
     });
  }
  else {
     this.gridApi.startEditingCell({
       rowIndex: this.gridApi.getFocusedCell().rowIndex,
       colKey: this.gridApi.getFocusedCell().column.colId
     });
  }
 }
}
</code>```

Body:
I am using a ag-Grid with an editable column named 'Cost'. The requirements are mentioned below:

If the user edits a value in any cell of this column and presses 'Enter' key, the focus should move to the cell below in the same column and turn it into edit mode (I am able to achieve this without any issues)

If the user edits a value in any cell of this column and presses 'Shift + Enter' keys, the focus should move to the cell above in the same column and convert it into edit mode

In the 'Shift + Enter' scenario, the focus moves to the cell above and turns it into edit mode but the focus is also set to a cell two rows below in the same column i.e two cells in the column now have focus, one in edit mode(I need this) and one in non-edit mode(I shouldn't have this) as shown in the image below

The code in the html file is:

<ag-grid-angular
   #agGrid
   style="width:100%; height:100vh"
   id="myGrid"
   class="ag-theme-balham-dark"
   [columnDefs]="columnDefs"
   [defaultColDef]="defaultColDef"
   [singleClickEdit]="true"
   [enterMovesDown]="true"
   [enterMovesDownAfterEdit]="true"
   [autoGroupColumnDef]="autoGroupColumnDef"
   [treeData]="true"
   [rowData]="rowData"
   [groupDefaultExpanded]="groupDefaultExpanded"
   [getDataPath]="getDataPath"
   (cellValueChanged)="onCellValueChanged($event)"
   (keyup)="onKeyUp($event)"
   (gridReady)="onGridReady($event)"
   >
</ag-grid-angular>

I am using 'keyup' event for this and the code inside 'onKeyUp' function in the component file is:

onKeyUp(e) {
  if(e.key === 'Enter') {
    if(e.shiftKey) {
      this.gridApi.startEditingCell({
        rowIndex: (this.gridApi.getFocusedCell().rowIndex - 2),
        colKey: this.gridApi.getFocusedCell().column.colId
      });
    }
    else {
      this.gridApi.startEditingCell({
        rowIndex: this.gridApi.getFocusedCell().rowIndex,
        colKey: this.gridApi.getFocusedCell().column.colId
      });
    }
  }
}

I want to get rid of the focus set to cell two rows below the actual cell in edit mode as shown in the image. Please help me with this.

Body:
I was finally able to solve the problem. Find 'rowIndex' and 'colKey' for current row and then use clearFocusedCell() to clear the non-required focus before converting the required cell into edit mode.

onKeyUp(e) {
 if(e.key === 'Enter') {
  if(e.shiftKey) {
     var rowIndex = this.gridApi.getFocusedCell().rowIndex;  <-- Added line
     var colKey = this.gridApi.getFocusedCell().column.colId  <-- Added line
     this.gridApi.clearFocusedCell();  <-- Added line

     this.gridApi.startEditingCell({
       rowIndex: (rowIndex - 2),
       colKey: colKey
     });
  }
  else {
     this.gridApi.startEditingCell({
       rowIndex: this.gridApi.getFocusedCell().rowIndex,
       colKey: this.gridApi.getFocusedCell().column.colId
     });
  }
 }
}


答:
A branch is not a directory. It is a commit label that moves along with commits, like tag is a commit label that stays with a particular commit. You will not have anything "inside" the master branch, rather master and develop will both initially label the same commit.

Create the develop branch like so:

```<code>git branch develop
</code>```

To clarify: let's say you have the initial commit A. It will be labeled as master branch.

```<code>git init

A [master]
</code>```

If you make a new commit B, the branch label will move:

```<code>git commit -a

A -> B [master]
</code>```

If you then branch into develop, the B will get the new label as well:

```<code>git branch develop

A -> B [master, develop]
</code>```

If you commit on the develop, it will move, but master won't:

```<code>git checkout develop
git commit -a

A -> B [master] -> C [develop]
</code>```

If you now commit on the master, the tree will fork:

```<code>git checkout master
git commit -a

A -> B -> C [develop]
     +--> D [master]
</code>```

Meanwhile, you only have in your directory whatever the contents of your current commit is. Switch branches, and the directory contents change.

Title: How does a Git repository works with a develop and master branch?

Body:
I'm new to Git and this is really confusing. I wanted to start off developing a web application on Git and so far I've been dealing with troubles that have kept me behind.

I've read this blog post on a successful branching model for Git. I was really interested in setting up something similar to this.

It says that the repository has 2 main branches called master and develop. So I went ahead and created a repository. However, to my surprise, the repository itself was the default master branch. How was I supposed to create a develop branch? Do I create it in the parent of the master branch? That would mean that the develop branch is outside the repository.

Am I getting something totally wrong here? Do I just ignore the fact that I'm creating two branches inside the master branch?

Body:
A branch is not a directory. It is a commit label that moves along with commits, like tag is a commit label that stays with a particular commit. You will not have anything "inside" the master branch, rather master and develop will both initially label the same commit.

Create the develop branch like so:

git branch develop

To clarify: let's say you have the initial commit A. It will be labeled as master branch.

git init

A [master]

If you make a new commit B, the branch label will move:

git commit -a

A -> B [master]

If you then branch into develop, the B will get the new label as well:

git branch develop

A -> B [master, develop]

If you commit on the develop, it will move, but master won't:

git checkout develop
git commit -a

A -> B [master] -> C [develop]

If you now commit on the master, the tree will fork:

git checkout master
git commit -a

A -> B -> C [develop]
     +--> D [master]

Meanwhile, you only have in your directory whatever the contents of your current commit is. Switch branches, and the directory contents change.


问:
Why Sonar-scanner 4.2 is unable to create user cache?
Using a dockerized sonar scanner 4.2 official image I try to run a sample Docker run operation of the sonar scanner and I get
 unable to create user cache: /usr/src/.sonar/cache caused by: Java.nio.file.accessdeniedexception: /usr/src/.sonar
everytime. Is it an issue with the user on the image? It's hard to believe since this is an official sonar scannerDocker image

答:
On Linux, I had to create manually folders and set correct chmod :

```<code>mkdir .sonar .sonar/cache .scannerwork
sudo chmod -R 777 .sonar
sudo chmod -R 777 .scannerwork
</code>```

To automize the scans, I created a docker-compose-sonarqube.yml which contains :

- the sonarqube server

- the sonarqube database

- tha sonarqube scanner

```<code>version: '3.7'

services:
  # Sonarqube server : continuous code quality + security
  # User = admin, password = admin
  # The first time, we need to adjust docker parameters for sonarqube. Execute commands in the section 'Docker Host Requirements' from https://hub.docker.com/_/sonarqube/ : sudo sysctl -w vm.max_map_count=262144; sudo sysctl -w fs.file-max=65536; ulimit -n 65536; ulimit -u 4096; docker-compose -f docker-compose-sonarqube.yml up
  sonarqube:
    image: sonarqube:8.3-community
    depends_on:
      - sonarqube-db
    ports:
      - "54380:9000"
    expose:
      - "9000"
    networks:
      - sonarnet
    environment:
      SONAR_JDBC_URL: jdbc:postgresql://sonarqube-db:5432/sonar
      SONAR_JDBC_USERNAME: sonar
      SONAR_JDBC_PASSWORD: sonar
    volumes:
      - sonarqube_data:/opt/sonarqube/data
      - sonarqube_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
      - sonarqube_temp:/opt/sonarqube/temp
  # Sonarqube database
  sonarqube-db:
    image: postgres
    networks:
      - sonarnet
    environment:
      POSTGRES_USER: sonar
      POSTGRES_PASSWORD: sonar
    volumes:
      - postgresql:/var/lib/postgresql
      # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52
      - postgresql_data:/var/lib/postgresql/data
  # Sonarqube client (scanner)
  sonarqube-scanner-cli:
    image: sonarsource/sonar-scanner-cli
    depends_on:
      - sonarqube
    networks:
      - sonarnet
    volumes:
      - ./:/usr/src
    environment:
      SONAR_HOST_URL: http://sonarqube:9000

networks:
  sonarnet:
    driver: bridge

volumes:
  sonarqube_data:
  sonarqube_extensions:
  sonarqube_logs:
  sonarqube_temp:
  postgresql:
  postgresql_data:
</code>```

Set your project sources in sonar-project.properties :

```<code># must be unique in a given SonarQube instance
sonar.projectKey=myapp

# --- optional properties ---

# defaults to project key
sonar.projectName=My App
# defaults to 'not provided'
#sonar.projectVersion=1.0

# Path is relative to the sonar-project.properties file. Defaults to .
sonar.sources=./symfony/src

# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8

# Sonarqube server url
sonar.host.url=http://sonarqube:9000
</code>```

Finally run sonarqube.sh

```<code># Usage : sh sonarqube.sh firefox

sonarcube() {
    sonarqubePort=54380
    sudo date # Ask for the password at the begining
    docker-compose -f docker-compose-sonarqube.yml up --d
    isServerUp=1
    while [ "$isServerUp" != "0" ]; do # Wait for sonarcube server to be up
        echo "Waiting for sonarqube. This may take 1 min ..."
        curl http://localhost:$sonarqubePort -s|grep "window.serverStatus"|grep "UP"
        isServerUp=$?
        sleep 1
    done
    sleep 3
    mkdir .sonar .sonar/cache .scannerwork
    sudo chmod -R 777 .sonar
    sudo chmod -R 777 .scannerwork
    docker-compose -f docker-compose-sonarqube.yml start sonarqube-scanner-cli;
    docker-compose -f docker-compose-sonarqube.yml logs -f sonarqube-scanner-cli;
    firefox http://localhost:54380/dashboard?id=myapp
    echo "View Sonarqube results at http://localhost:$sonarqubePort/dashboard?id=myapp"
}

sonarcube
</code>```

Body:
On Linux, I had to create manually folders and set correct chmod :

mkdir .sonar .sonar/cache .scannerwork
sudo chmod -R 777 .sonar
sudo chmod -R 777 .scannerwork

To automize the scans, I created a docker-compose-sonarqube.yml which contains :

- the sonarqube server

- the sonarqube database

- tha sonarqube scanner

version: '3.7'

services:
  # Sonarqube server : continuous code quality + security
  # User = admin, password = admin
  # The first time, we need to adjust docker parameters for sonarqube. Execute commands in the section 'Docker Host Requirements' from https://hub.docker.com/_/sonarqube/ : sudo sysctl -w vm.max_map_count=262144; sudo sysctl -w fs.file-max=65536; ulimit -n 65536; ulimit -u 4096; docker-compose -f docker-compose-sonarqube.yml up
  sonarqube:
    image: sonarqube:8.3-community
    depends_on:
      - sonarqube-db
    ports:
      - "54380:9000"
    expose:
      - "9000"
    networks:
      - sonarnet
    environment:
      SONAR_JDBC_URL: jdbc:postgresql://sonarqube-db:5432/sonar
      SONAR_JDBC_USERNAME: sonar
      SONAR_JDBC_PASSWORD: sonar
    volumes:
      - sonarqube_data:/opt/sonarqube/data
      - sonarqube_extensions:/opt/sonarqube/extensions
      - sonarqube_logs:/opt/sonarqube/logs
      - sonarqube_temp:/opt/sonarqube/temp
  # Sonarqube database
  sonarqube-db:
    image: postgres
    networks:
      - sonarnet
    environment:
      POSTGRES_USER: sonar
      POSTGRES_PASSWORD: sonar
    volumes:
      - postgresql:/var/lib/postgresql
      # This needs explicit mapping due to https://github.com/docker-library/postgres/blob/4e48e3228a30763913ece952c611e5e9b95c8759/Dockerfile.template#L52
      - postgresql_data:/var/lib/postgresql/data
  # Sonarqube client (scanner)
  sonarqube-scanner-cli:
    image: sonarsource/sonar-scanner-cli
    depends_on:
      - sonarqube
    networks:
      - sonarnet
    volumes:
      - ./:/usr/src
    environment:
      SONAR_HOST_URL: http://sonarqube:9000

networks:
  sonarnet:
    driver: bridge

volumes:
  sonarqube_data:
  sonarqube_extensions:
  sonarqube_logs:
  sonarqube_temp:
  postgresql:
  postgresql_data:

Set your project sources in sonar-project.properties :

# must be unique in a given SonarQube instance
sonar.projectKey=myapp

# --- optional properties ---

# defaults to project key
sonar.projectName=My App
# defaults to 'not provided'
#sonar.projectVersion=1.0

# Path is relative to the sonar-project.properties file. Defaults to .
sonar.sources=./symfony/src

# Encoding of the source code. Default is default system encoding
#sonar.sourceEncoding=UTF-8

# Sonarqube server url
sonar.host.url=http://sonarqube:9000

Finally run sonarqube.sh

# Usage : sh sonarqube.sh firefox

sonarcube() {
    sonarqubePort=54380
    sudo date # Ask for the password at the begining
    docker-compose -f docker-compose-sonarqube.yml up --d
    isServerUp=1
    while [ "$isServerUp" != "0" ]; do # Wait for sonarcube server to be up
        echo "Waiting for sonarqube. This may take 1 min ..."
        curl http://localhost:$sonarqubePort -s|grep "window.serverStatus"|grep "UP"
        isServerUp=$?
        sleep 1
    done
    sleep 3
    mkdir .sonar .sonar/cache .scannerwork
    sudo chmod -R 777 .sonar
    sudo chmod -R 777 .scannerwork
    docker-compose -f docker-compose-sonarqube.yml start sonarqube-scanner-cli;
    docker-compose -f docker-compose-sonarqube.yml logs -f sonarqube-scanner-cli;
    firefox http://localhost:54380/dashboard?id=myapp
    echo "View Sonarqube results at http://localhost:$sonarqubePort/dashboard?id=myapp"
}

sonarcube


问:
TypeError: Converting circular structure to JSON in nodejs
I am using request package for node.js

Code :

```<code> var formData = ({first_name:firstname,last_name:lastname,user_name:username, email:email,password:password});

  request.post({url:'http://localhost:8081/register', JSON: formData}, function(err, connection, body) {

exports.Register = function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    console.log("Request data " +JSON.stringify(req));
</code>```

Here I am getting this error :

TypeError: Converting circular structure to JSON

Can anybody tell me what is the problem

答:
use this https://www.npmjs.com/package/json-stringify-safe</p>

```<code>var stringify = require('json-stringify-safe');
var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(stringify(circularObj, null, 2));

stringify(obj, serializer, indent, decycler)
</code>```

Body:
I am using request package for node.js

Code :

 var formData = ({first_name:firstname,last_name:lastname,user_name:username, email:email,password:password});

  request.post({url:'http://localhost:8081/register', JSON: formData}, function(err, connection, body) {

exports.Register = function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    console.log("Request data " +JSON.stringify(req));

Here I am getting this error :

TypeError: Converting circular structure to JSON

Can anybody tell me what is the problem

Body:
use this https://www.npmjs.com/package/json-stringify-safe

var stringify = require('json-stringify-safe');
var circularObj = {};
circularObj.circularRef = circularObj;
circularObj.list = [ circularObj, circularObj ];
console.log(stringify(circularObj, null, 2));

stringify(obj, serializer, indent, decycler)


问:
Is it possible to view an HTML table in the viewer pane?
I would like to know if there is any function which makes it easy to visualize an html object in the RStudio's viewer pane. For instance, I would like to know if it would be possible to view an html table in the viewer pane. </p>

```<code>library("Quandl")
library("knitr")
df  <-  Quandl("FBI_UCR/USCRIME_TYPE_VIOLENTCRIMERATE")
kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")
</code>```

答:
I have a solution that works for kable tables.

```<code>kable(iris) %>% kableExtra::kable_styling()
</code>```

This is automatically displayed in the viewer pane. No need for tempfile.

Body:
I would like to know if there is any function which makes it easy to visualize an html object in the RStudio's viewer pane. For instance, I would like to know if it would be possible to view an html table in the viewer pane.

library("Quandl")
library("knitr")
df  <-  Quandl("FBI_UCR/USCRIME_TYPE_VIOLENTCRIMERATE")
kable(head(df[,1:9]), format = 'html', table.attr = "class=nofluid")

Body:
I have a solution that works for kable tables.

kable(iris) %>% kableExtra::kable_styling()

This is automatically displayed in the viewer pane. No need for tempfile.


问:
How to crawl a webpage with selectors?
I'm crawling a webpage: ogimet.com
This is my code:

```<code>import time
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver

#this path may be different on your cpu, you need to install a browser driver
driver = webdriver.Chrome(executable_path=r'C:/Users/jcrav/Desktop/driver/chromedriver.exe')
url="http://www.ogimet.com/"
driver.get(url)
#driver = webdriver.Chrome(driver)
#driver.get(url)

the_link = driver.find_element_by_xpath('/html/body/table/tbody/tr[2]/td[1]/div[19]/a')
the_link.click()
time.sleep(2)

desplegable_pais = driver.find_element_by_css_selector('select[name="estado"] option[value="Peru"]')
desplegable_pais.click()
time.sleep(2)
</code>```

The issue is that some selectors does not have a variable named value.
When i select a country, the selector has a variable named value.

```<code><option value="Peru">Perú</option>
</code>```

But when i select year, does not have a variable named value

```<code><option>2004</option>
</code>```

How can i select a year with the .click command?

答:
You can use selenium Select() class to select item from drop down.

To handle dynamic element induce WebDriverWait() and wait for element_to_be_clickable()

Code:

```<code>driver.get("http://www.ogimet.com/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Sondeos por territorios"))).click()
select=Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select[name='estado']"))))
select.select_by_value('Peru')
selectyear=Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='ano']"))))
selectyear.select_by_visible_text('2004')
</code>```

However if you still want to use option to click item then use this code.

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='ano']/option[text()='2004']"))).click()
</code>```

If you want to parameterize this try below code.

```<code>year='2004'
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='ano']/option[text()='{}']".format(year)))).click()
</code>```

You need to import following libraries.

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
</code>```

Title: How to crawl a webpage with selectors?

Body:
I'm crawling a webpage: ogimet.com
This is my code:

import time
from urllib.request import urlopen
from bs4 import BeautifulSoup
from selenium import webdriver

#this path may be different on your cpu, you need to install a browser driver
driver = webdriver.Chrome(executable_path=r'C:/Users/jcrav/Desktop/driver/chromedriver.exe')
url="http://www.ogimet.com/"
driver.get(url)
#driver = webdriver.Chrome(driver)
#driver.get(url)

the_link = driver.find_element_by_xpath('/html/body/table/tbody/tr[2]/td[1]/div[19]/a')
the_link.click()
time.sleep(2)

desplegable_pais = driver.find_element_by_css_selector('select[name="estado"] option[value="Peru"]')
desplegable_pais.click()
time.sleep(2)

The issue is that some selectors does not have a variable named value.
When i select a country, the selector has a variable named value.

<option value="Peru">Perú</option>

But when i select year, does not have a variable named value

<option>2004</option>

How can i select a year with the .click command?

Body:
You can use selenium Select() class to select item from drop down.

To handle dynamic element induce WebDriverWait() and wait for element_to_be_clickable()

Code:

driver.get("http://www.ogimet.com/")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Sondeos por territorios"))).click()
select=Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select[name='estado']"))))
select.select_by_value('Peru')
selectyear=Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='ano']"))))
selectyear.select_by_visible_text('2004')

However if you still want to use option to click item then use this code.

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='ano']/option[text()='2004']"))).click()

If you want to parameterize this try below code.

year='2004'
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='ano']/option[text()='{}']".format(year)))).click()

You need to import following libraries.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select


问:
How to find font and colour for each text in Python web scraping?
I wrote a Python scraper that can scrape text from websites and now I am in the process of labelling font and size.
For example the CSS is:

```<code>td{ font-family:Arial; font-size:9pt; }
hr { height:1px; }
.currency { color:#000099; }
</code>```

HTML:

```<code><td align="left">
<font class="currency">USD</font>
"3.20"
</td>
</code>```

My desired output:

```<code>{
"text": ["USD", "3.20"],
"font": ["Arial", "Arial"],
"colours": ["#000099", "#000000"],
}
</code>```

Is there any way I can do this with BeautifulSoup or regex?

答:
After some thoughts I came up with a solution, although its not elegant it worked fine:
1. Parse css using regex and construct a dictionary with classes and styles
2. Iterate through the dictionary and use beautifulsoup select method to inject labelling to the html string, for example:

```<code>original:
>>> <b>some text</b>
inject labels:
bs4_object.string = bs4_object.text + label
>>> <b>some[[bold]] text[[bold]]</b>
</code>```

Use bs4 to extract all the text, then parse the labels into a list

Body:
I wrote a Python scraper that can scrape text from websites and now I am in the process of labelling font and size.
For example the CSS is:

td{ font-family:Arial; font-size:9pt; }
hr { height:1px; }
.currency { color:#000099; }

HTML:

USD
"3.20"

My desired output:

{
"text": ["USD", "3.20"],
"font": ["Arial", "Arial"],
"colours": ["#000099", "#000000"],
}

Is there any way I can do this with BeautifulSoup or regex?

Body:
After some thoughts I came up with a solution, although its not elegant it worked fine:
1. Parse css using regex and construct a dictionary with classes and styles
2. Iterate through the dictionary and use beautifulsoup select method to inject labelling to the html string, for example:

original:
>>> <b>some text</b>
inject labels:
bs4_object.string = bs4_object.text + label
>>> <b>some[[bold]] text[[bold]]</b>

Use bs4 to extract all the text, then parse the labels into a list