问:
HTTP Status 405 - Request method 'POST' not supported. Spring Security
I have Spring Security with Spring MVC. When I try to sign up, it is giving me 405 'POST' not supported. I have disabled csrf token in security config. Let me know where did I go wrong?

My login page:

```<code><#-- @ftlvariable name="error" type="java.util.Optional<String>" -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log in</title>
</head>
<body>
<nav role="navigation">
<ul>
    <li><a href="/">Home</a></li>
</ul>
</nav>

<h1>Log in</h1>

<p>You can use: demo@localhost / demo</p>

<form role="form" action="/login" method="post">
<div>
    <label for="email">Email address</label>
    <input type="email" name="email" id="email" required autofocus/>
</div>
<div>
    <label for="password">Password</label>
    <input type="password" name="password" id="password" required/>
</div>
<div>
    <label for="remember-me">Remember me</label>
    <input type="checkbox" name="remember-me" id="remember-me"/>
</div>
<button type="submit">Sign in</button>
</form>
</body>
</html>
</code>```

Authorization is handled by LoginController:

```<code>@Controller
public class LoginController {

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}
}
</code>```

Here is my Spring Security configuration class:

```<code>@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/public/**").permitAll()
            .antMatchers("/users/**").hasAuthority("ADMIN")
            .anyRequest().fullyAuthenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("email")
            .passwordParameter("password")
            .permitAll()
            .and()
            .logout()
            .logoutUrl("/logout")
            .deleteCookies("remember-me")
            .logoutSuccessUrl("/")
            .permitAll()
            .and()
            .rememberMe().and().csrf().disable();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder());
}
}
</code>```

答:
This one is easy to solve, you are getting HTTP status 405 which means (from wiki):

A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

You trying to HTTP POST a form to a handler which handles GET requests.

Just change this:

```<code>@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}
}
</code>```

To this:

```<code>@Controller
public class LoginController {

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}
}
</code>```

Body:
I have Spring Security with Spring MVC. When I try to sign up, it is giving me 405 'POST' not supported. I have disabled csrf token in security config. Let me know where did I go wrong?

My login page:

<#-- @ftlvariable name="error" type="java.util.Optional<String>" -->
<!DOCTYPE html>

<meta charset="utf-8">
<title>Log in</title>

Home

Log in

You can use: demo@localhost / demo

<form role="form" action="/login" method="post">

    Email address
    <input type="email" name="email" id="email" required autofocus/>

    Password
    <input type="password" name="password" id="password" required/>

    Remember me
    <input type="checkbox" name="remember-me" id="remember-me"/>

<button type="submit">Sign in</button>
</form>

Authorization is handled by LoginController:

@Controller
public class LoginController {

@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}
}

Here is my Spring Security configuration class:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/", "/public/**").permitAll()
            .antMatchers("/users/**").hasAuthority("ADMIN")
            .anyRequest().fullyAuthenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("email")
            .passwordParameter("password")
            .permitAll()
            .and()
            .logout()
            .logoutUrl("/logout")
            .deleteCookies("remember-me")
            .logoutSuccessUrl("/")
            .permitAll()
            .and()
            .rememberMe().and().csrf().disable();
}

@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
            .userDetailsService(userDetailsService)
            .passwordEncoder(new BCryptPasswordEncoder());
}
}

Body:
This one is easy to solve, you are getting HTTP status 405 which means (from wiki):

A request method is not supported for the requested resource; for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource.

You trying to HTTP POST a form to a handler which handles GET requests.

Just change this:

@Controller
public class LoginController {
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}
}

To this:

@Controller
public class LoginController {

@RequestMapping(value = "/login", method = RequestMethod.POST)
public ModelAndView getLoginPage(@RequestParam Optional<String> error) {
    return new ModelAndView("login", "error", error);
}
}


来源: stackexchange

问:
Bootstrap: hover over the tooltip text to click a link
I am using the tooltip tool in Bootstrap 3.x in my web app to show helpful info. It works in this way:

```<code>$('[data-toggle="tooltip"]').tooltip({
        'animation': true,
        'placement': 'top',
        'trigger': 'hover',
        'html':true,
        'container': 'body'
});
</code>```

Please note that I have to use hover to trigger the tooltip. Now I need to add a new tooltip and its tooltip text contains a HTML link. A visitor should be able to mouse over the tooltip text to click the link.

The problem is that when a visitor moves his mouse, the tooltip text disappears before he can reach the tooltip text area.

答:
Time gap might solve your problem.

var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
  var self = obj instanceof this.constructor ?
    obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
  var container, timeout;

  originalLeave.call(this, obj);

  if(obj.currentTarget) {
    container = $(obj.currentTarget).siblings('.popover')
    timeout = self.timeout;
    container.one('mouseenter', function(){
      //We entered the actual popover – call off the dogs
      clearTimeout(timeout);
      //Let's monitor popover content instead
      container.one('mouseleave', function(){
        $.fn.popover.Constructor.prototype.leave.call(self, self);
      });
    })
  }
};

$('body').popover({ selector: '[data-popover]', trigger: 'click hover', placement: 'auto', delay: {show: 50, hide: 400}});

  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<p id='container'>
<button class='btn btn-primary btn-large' data-popover="true" data-html=true data-content="click me, I'll try not to disappear">hover here</button>
</p></code>```

ContentLicense: CC BY-SA 3.0

Body:
I am using the tooltip tool in Bootstrap 3.x in my web app to show helpful info. It works in this way:

$('[data-toggle="tooltip"]').tooltip({
        'animation': true,
        'placement': 'top',
        'trigger': 'hover',
        'html':true,
        'container': 'body'
});

Please note that I have to use hover to trigger the tooltip. Now I need to add a new tooltip and its tooltip text contains a HTML link. A visitor should be able to mouse over the tooltip text to click the link.

The problem is that when a visitor moves his mouse, the tooltip text disappears before he can reach the tooltip text area.

Body:
Time gap might solve your problem.

var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
  var self = obj instanceof this.constructor ?
    obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
  var container, timeout;

  originalLeave.call(this, obj);

  if(obj.currentTarget) {
    container = $(obj.currentTarget).siblings('.popover')
    timeout = self.timeout;
    container.one('mouseenter', function(){
      //We entered the actual popover – call off the dogs
      clearTimeout(timeout);
      //Let's monitor popover content instead
      container.one('mouseleave', function(){
        $.fn.popover.Constructor.prototype.leave.call(self, self);
      });
    })
  }
};

$('body').popover({ selector: '[data-popover]', trigger: 'click hover', placement: 'auto', delay: {show: 50, hide: 400}});

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<p id='container'>
<button class='btn btn-primary btn-large' data-popover="true" data-html=true data-content="<a href='http://www.wojt.eu' target='blank' >click me, I'll try not to disappear</a>">hover here</button>
</p>


问:
Launching Activities via package names
I have been working on testing some packages that I do not have the source code for, and one of the packages is normally launched by pressing three buttons for three seconds. When I try to launch the package using the typical method, I get a java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.addFlags(int) error. Below is my code

```<code>@Before
public void setup() {
    //Initialize UiDevice instance
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    mDevice = UiDevice.getInstance(instrumentation);

    mDevice.pressHome();

    final String launcherPackage = mDevice.getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);

    Context context = InstrumentationRegistry.getTargetContext();
    final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(DEALER_DIAG_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(DEALER_DIAG_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}
</code>```

I tried using getContext instead of getTargetContext, however someone pointed out to me that if the intents are not exported, I will not be able to launch the package this way no matter what I do. I tried to get the package names by using the command adb logcat ActivityManager:V *:F as well as adb shell pm list packages -f

```<code>--------- beginning of main
I/ActivityManager( 2296): START u0 {flg=0x10000000
cmp=com.android.systemui/.usb.UsbDebuggingActivity (has extras)} from uid
1000 on display 0
I/ActivityManager( 2296): Displayed
com.android.systemui/.usb.UsbDebuggingActivity: +184ms
I/ActivityManager( 2296): START u0 {act=android.intent.action.MAIN cat=
[android.intent.category.HOME] flg=0x10200000
cmp=com.android.launcher3/.Launcher} from uid 1000 on display 0
I/ActivityManager( 2296): START u0
{act=com.REDACTED.auto.diagnostics.dealer.MAIN flg=0x10800000
cmp=com.REDACTED.auto.diagnostics/.dealer.MainActivity} from uid 1000 on
display 0
I/ActivityManager( 2296): Start proc
20943:com.REDACTED.auto.diagnostics/1000 for activity
com.REDACTED.auto.diagnostics/.dealer.MainActivity
I/ActivityManager( 2296): Displayed
com.REDACTED.auto.diagnostics/.dealer.MainActivity: +572ms
</code>```

Does anyone have any input as to why I am getting this error? I have tried using every package name listed in the logcat dump with no success. Any input would be appreciated.

答:
I figured out a method that worked for me, though Brandon's could possibly work on another solution. Here is my solution:

```<code>Intent intent = new Intent("com.REDACTED.auto.diagnostics.dealer.MAIN");
intent.setClassName("com.REDACTED.auto.diagnostics",
"com.REDACTED.auto.diagnostics.dealer.MainActivity");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Context c = InstrumentationRegistry.getContext();
c.startActivity(intent);
</code>```

This possibly does the same thing that Brandon's solution does, however less abstracted.

Title: Launching Activities via package names

Body:
I have been working on testing some packages that I do not have the source code for, and one of the packages is normally launched by pressing three buttons for three seconds. When I try to launch the package using the typical method, I get a java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.content.Intent.addFlags(int) error. Below is my code

@Before
public void setup() {
    //Initialize UiDevice instance
    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    mDevice = UiDevice.getInstance(instrumentation);

    mDevice.pressHome();

    final String launcherPackage = mDevice.getLauncherPackageName();
    assertThat(launcherPackage, notNullValue());
    mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)), LAUNCH_TIMEOUT);

    Context context = InstrumentationRegistry.getTargetContext();
    final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(DEALER_DIAG_PACKAGE);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);

    mDevice.wait(Until.hasObject(By.pkg(DEALER_DIAG_PACKAGE).depth(0)), LAUNCH_TIMEOUT);
}

I tried using getContext instead of getTargetContext, however someone pointed out to me that if the intents are not exported, I will not be able to launch the package this way no matter what I do. I tried to get the package names by using the command adb logcat ActivityManager:V *:F as well as adb shell pm list packages -f

--------- beginning of main
I/ActivityManager( 2296): START u0 {flg=0x10000000
cmp=com.android.systemui/.usb.UsbDebuggingActivity (has extras)} from uid
1000 on display 0
I/ActivityManager( 2296): Displayed
com.android.systemui/.usb.UsbDebuggingActivity: +184ms
I/ActivityManager( 2296): START u0 {act=android.intent.action.MAIN cat=
[android.intent.category.HOME] flg=0x10200000
cmp=com.android.launcher3/.Launcher} from uid 1000 on display 0
I/ActivityManager( 2296): START u0
{act=com.REDACTED.auto.diagnostics.dealer.MAIN flg=0x10800000
cmp=com.REDACTED.auto.diagnostics/.dealer.MainActivity} from uid 1000 on
display 0
I/ActivityManager( 2296): Start proc
20943:com.REDACTED.auto.diagnostics/1000 for activity
com.REDACTED.auto.diagnostics/.dealer.MainActivity
I/ActivityManager( 2296): Displayed
com.REDACTED.auto.diagnostics/.dealer.MainActivity: +572ms

Does anyone have any input as to why I am getting this error? I have tried using every package name listed in the logcat dump with no success. Any input would be appreciated.

Body:
I figured out a method that worked for me, though Brandon's could possibly work on another solution. Here is my solution:

Intent intent = new Intent("com.REDACTED.auto.diagnostics.dealer.MAIN");
intent.setClassName("com.REDACTED.auto.diagnostics",
"com.REDACTED.auto.diagnostics.dealer.MainActivity");
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Context c = InstrumentationRegistry.getContext();
c.startActivity(intent);

This possibly does the same thing that Brandon's solution does, however less abstracted.


问:
Does the Datastore API for NodeJS use `distinct on` by default?
https://cloud.google.com/datastore/docs/concepts/queries#datastore-distinct-on-query-nodejs

When reading the documentation about querying entities, I noticed that keys-only queries and projection queries without a distinct on clause are considered small operations, which according to their quota and pricing are considered free.

However, when you look at the examples from different languages on that page, it looks like several (C#, Java, PHP, etc...) support a way of telling the query to specifically perform a distinct on operation, but there doesn't seem to be support in NodeJS for specifying this directly. This seems to significantly impact cost, but NodeJS is missing support.

What am I missing?

答: I don't think the NodeJS API use distinct by default, though you should be able to do a simple test to confirm. Looking through the examples tells me that NodeJS API uses a slightly different terminology, and calls it groupBy for fetching distinct results. Here is the link to the API Documentation.


问:
How to 'ALTER VIEW' in HP Vertica
In my new project, I am connecting to HP vertica using DBeaver. I have created a view on a large database (about few billion records) with size limit of 300. This view was created to setup other systems in the pipeline. After everything is setup, I want to remove the size limitation of 300 from the view and want to return all the data. Unfortunately, I can only find that command 'ALTER VIEW' for HP Vertica is allowed to simply rename the view and not modify the view itself. I am forced to drop the view and create another one but this breaks the already established data connection from other systems (Tableau) to the original view.

https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/SQLReferenceManual/Statements/CREATEVIEW.htm

and

https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/SQLReferenceManual/Statements/ALTERVIEW.htm

I tried using ALTER VIEW command as in SQL but I get an error -

```<code>SQL Error [4856] [42601]:
[Vertica][VJDBC](4856) ERROR: Syntax error at or near "AS"
[Vertica][VJDBC](4856) ERROR: Syntax error at or near "AS"
com.vertica.util.ServerException:
[Vertica][VJDBC](4856) ERROR: Syntax error at or near "AS"
</code>```

答:
CREATE OR REPLACE VIEW etc etc.

https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/SQLReferenceManual/Statements/CREATEVIEW.htm

Title: How to 'ALTER VIEW' in HP Vertica

Body:
In my new project, I am connecting to HP vertica using DBeaver. I have created a view on a large database (about few billion records) with size limit of 300. This view was created to setup other systems in the pipeline. After everything is setup, I want to remove the size limitation of 300 from the view and want to return all the data. Unfortunately, I can only find that command 'ALTER VIEW' for HP Vertica is allowed to simply rename the view and not modify the view itself. I am forced to drop the view and create another one but this breaks the already established data connection from other systems (Tableau) to the original view.

https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/SQLReferenceManual/Statements/CREATEVIEW.htm

and

https://my.vertica.com/docs/7.1.x/HTML/Content/Authoring/SQLReferenceManual/Statements/ALTERVIEW.htm

I tried using ALTER VIEW command as in SQL but I get an error -

SQL Error [4856] [42601]:
[Vertica][VJDBC](4856) ERROR: Syntax error at or near "AS"
[Vertica][VJDBC](4856) ERROR: Syntax error at or near "AS"
com.vertica.util.ServerException:
[Vertica][VJDBC](4856) ERROR: Syntax error at or near "AS"


问:
LoadError: cannot load such file -- tiny_tds/tiny_tds
Let me start by saying I'm not a Ruby dev. I'm just trying to install Redmine on Windows x64. I've found similar questions here which I will link later. But since I'm not a Ruby dev, I don't understand the answers and can't apply them to my situation. So please be a little verbose in your answer so that I can fully understand what I'm doing.

I get to Step 5 in the the Redmine Install and the following error is generated:

```<code>C:\redmine\redmine-3.2.3>bundle exec rake generate_secret_token
C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/htmlentities-4.3.1/lib/htmlentities/mappings/expanded.rb:465: warning: duplicated key at line 466 ignored: "inodot"
rake aborted!
LoadError: cannot load such file -- tiny_tds/tiny_tds
C:/redmine/redmine-3.2.3/config/application.rb:5:in `<top (required)>'
C:/redmine/redmine-3.2.3/Rakefile:5:in `require'
C:/redmine/redmine-3.2.3/Rakefile:5:in `<top (required)>'
LoadError: cannot load such file -- tiny_tds/2.2/tiny_tds
C:/redmine/redmine-3.2.3/config/application.rb:5:in `<top (required)>'
C:/redmine/redmine-3.2.3/Rakefile:5:in `require'
C:/redmine/redmine-3.2.3/Rakefile:5:in `<top (required)>'
(See full trace by running task with --trace)
</code>```

Looking at this answer and this answer, I see that looking at Redmine's Gemfile and my list of gems should provide some insight as to the problem.

The problem seems to be with tiny_tds and the only place it is mentioned in the Gemfile is here:

```<code>when /sqlserver/
  gem "tiny_tds", "~> 0.6.2", :platforms => [:mri, :mingw, :x64_mingw]
  gem "activerecord-sqlserver-adapter", :platforms => [:mri, :mingw, :x64_mingw]
</code>```

From my gem list:

```<code>rake (11.2.2, default: 10.4.2)
tiny_tds (1.0.4, 0.6.2 x64-mingw32)
</code>```

It looks to me that I have multiple versions of rake and tiny_tds installed and it is choosing the wrong ones. One of the answers linked above seems to suggest that the Gemfile needs to be edited to pick the correct version and the other seems to suggest that using bundle exec should take care of this for me.

So what do I need to do here to complete this installation?

答:
This error is due to a problem in the 0.6.2 version of tiny_tds on windows, and not due to bundle being unable to resolve the correct version.  You do not need to worry about having multiple versions of tiny_tds installed; the bundle exec command will read the Gemfile and load the correct versions of each gem, for whatever command is being executed.

While installing Redmine 3.3.3, I was able to get past this specific error by updating the Redmine Gemfile to use tiny_tds version 0.7.0 instead.  As you suspected, you must edit the Gemfile in your Redmine folder.  Search for "tiny_tds" and update the version number from 0.6.2 to 0.7.0.

After making this change, you must re-execute the bundle install --without development test rmagick command.  This will install tiny_tds version 0.7.0. You should then be able to execute bundle exec rake generate_secret_token without errors.

I see that you already have both 0.6.2 and 1.0.4 installed.  I am not familiar with tiny_tds at all, and I do not know if there are breaking changes between 0.6.2 and 1.0.4.  I am under the impression that 0.7.0 is the first working version past 0.6.2, and therefore the version with the least risk of breaking changes. I can confirm that this is working in Redmine 3.3.3.stable using SQL Server without errors.

Body:
Let me start by saying I'm not a Ruby dev. I'm just trying to install Redmine on Windows x64. I've found similar questions here which I will link later. But since I'm not a Ruby dev, I don't understand the answers and can't apply them to my situation. So please be a little verbose in your answer so that I can fully understand what I'm doing.

I get to Step 5 in the the Redmine Install and the following error is generated:

C:\redmine\redmine-3.2.3>bundle exec rake generate_secret_token
C:/Ruby22-x64/lib/ruby/gems/2.2.0/gems/htmlentities-4.3.1/lib/htmlentities/mappings/expanded.rb:465: warning: duplicated key at line 466 ignored: "inodot"
rake aborted!
LoadError: cannot load such file -- tiny_tds/tiny_tds
C:/redmine/redmine-3.2.3/config/application.rb:5:in `<top (required)>'
C:/redmine/redmine-3.2.3/Rakefile:5:in `require'
C:/redmine/redmine-3.2.3/Rakefile:5:in `<top (required)>'
LoadError: cannot load such file -- tiny_tds/2.2/tiny_tds
C:/redmine/redmine-3.2.3/config/application.rb:5:in `<top (required)>'
C:/redmine/redmine-3.2.3/Rakefile:5:in `require'
C:/redmine/redmine-3.2.3/Rakefile:5:in `<top (required)>'
(See full trace by running task with --trace)

Looking at this answer and this answer, I see that looking at Redmine's Gemfile and my list of gems should provide some insight as to the problem.

The problem seems to be with tiny_tds and the only place it is mentioned in the Gemfile is here:

when /sqlserver/
  gem "tiny_tds", "~> 0.6.2", :platforms => [:mri, :mingw, :x64_mingw]
  gem "activerecord-sqlserver-adapter", :platforms => [:mri, :mingw, :x64_mingw]

From my gem list:

rake (11.2.2, default: 10.4.2)
tiny_tds (1.0.4, 0.6.2 x64-mingw32)

It looks to me that I have multiple versions of rake and tiny_tds installed and it is choosing the wrong ones. One of the answers linked above seems to suggest that the Gemfile needs to be edited to pick the correct version and the other seems to suggest that using bundle exec should take care of this for me.

So what do I need to do here to complete this installation?


问:
How do you respond immediately from an Azure Function PowerShell HTTP Trigger and then respond "out of band to another Url"?
I have a PowerShell HTTP trigger wired up to a Slack command. If the PS trigger responds in < 3 seconds all is good. I've got this working

If it takes longer, Slack requires two things, respond immediately and then respond out of band on the response_url.

This works. If I put a sleep 10 after the set-content, neither return and Slack says it timed out.

Is there way to accomplish this in PowerShell?

```<code>@"
{
  "response_type": "ephemeral",
   "text": "Checking $(get-date) ..."
}
"@ |  set-content $res -Encoding Ascii
</code>```

The out of band works.

```<code>$b = @"
{
    "response_type": "in_channel",
    "text": "It's 80 degrees right now.",
    "attachments": [
        {
            "text":"Partly cloudy today and tomorrow"
        }
    ]
}
"@

Invoke-RestMethod $responseUrl -Method post -Body $b -ContentType "application/json"
</code>```

答: The right pattern of doing that in Azure Functions is to have your HTTP trigger function just push a message in a queue, then return immediately. Then have another Azure Function that's listening on that queue and then run your logic there.</p>

Body:
I have a PowerShell HTTP trigger wired up to a Slack command. If the PS trigger responds in < 3 seconds all is good. I've got this working

If it takes longer, Slack requires two things, respond immediately and then respond out of band on the response_url.

This works. If I put a sleep 10 after the set-content, neither return and Slack says it timed out.

Is there way to accomplish this in PowerShell?

@"
{
  "response_type": "ephemeral",
   "text": "Checking $(get-date) ..."
}
"@ |  set-content $res -Encoding Ascii

The out of band works.

$b = @"
{
    "response_type": "in_channel",
    "text": "It's 80 degrees right now.",
    "attachments": [
        {
            "text":"Partly cloudy today and tomorrow"
        }
    ]
}
"@

Invoke-RestMethod $responseUrl -Method post -Body $b -ContentType "application/json"


问:
DB Microsoft Excel Driver
somebody knows where i could find the driver for Microsoft Excel Driver Data Base?  </p>

答:
You will get the driver from https://xlsql.dev.java.net

Here is the sample application for the same

ContentLicense: CC BY-SA 2.5

Title: DB Microsoft Excel Driver


问:
In scala, can a variable changed in a for-loop be used outside the loop?
I'm updating a variable within a for-loop in scala that I need outside the loop. I tested the code below and got the message "ERROR: undefined". The variable is not empty, inside the loop the values are returned. Thank you.  </p>

```<code>val example=List(0,0,1,0.7,10,2,5,7,4,1,-9,0,0,0,0,3,3,0,0,0,-80,-6.6,-1,0)
var b=scala.collection.mutable.MutableList.empty[Double]
var b_val:Double=0

for (i<-1 to 24) {
    if ( example (i) != 0 ){b_val = b_val + example(i)} else {b_val = 0}
    b += b_val;
}
println(b);
</code>```

答: You're getting an error because example only has 24 items. Therefore example(i) will throw an IndexOutOfBoundsException when i is 24.

Body:
I'm updating a variable within a for-loop in scala that I need outside the loop. I tested the code below and got the message "ERROR: undefined". The variable is not empty, inside the loop the values are returned. Thank you.

val example=List(0,0,1,0.7,10,2,5,7,4,1,-9,0,0,0,0,3,3,0,0,0,-80,-6.6,-1,0)
var b=scala.collection.mutable.MutableList.empty[Double]
var b_val:Double=0

for (i<-1 to 24) {
    if ( example (i) != 0 ){b_val = b_val + example(i)} else {b_val = 0}
    b += b_val;
}
println(b);


问:
@font-face not working
Don't know why but font is not displaying.Please help.

CSS(in css folder):
   style.css:

```<code>@font-face {
 font-family: Gotham;
 src: url(../fonts/gothammedium.eot);
 src: local('Gotham-Medium'),
 url(../fonts/Gotham-Medium.ttf) format('truetype');
}

a {
 font-family:Gotham,Verdana,Arial;
}
</code>```

答:
I'm also facing this type of problem. After trying all solutions I got final solution on this problem. Reasons for this type of problem is per-defined global fonts. Use !important keyword for each line in @font-face is the solution for this problem.

Full description and example for Solution of this problem is here :-  http://answerdone.blogspot.com/2017/06/font-face-not-working-solution.html

Title: @font-face not working

Body:
Don't know why but font is not displaying.Please help.

CSS(in css folder):
   style.css:

@font-face {
 font-family: Gotham;
 src: url(../fonts/gothammedium.eot);
 src: local('Gotham-Medium'),
 url(../fonts/Gotham-Medium.ttf) format('truetype');
}

a {
 font-family:Gotham,Verdana,Arial;
}


问:
How to linearly interpolate through an array in SAS?
bear with me! This is a project that I've been working on for awhile, trying many things and I just can't seem to get it to work.

Below is the existing code that I'm using to create a new table. The existing output table (claims.simulation_ISLPx) is also below.

What I want to do is take an "array" of members (5,6,8,10,12) and run 5 iterations of a process for the 5 member group, 6 iterations for the 6 member group,..., and 12 iterations for the 12 member group.

The "process" should draw a random value from U(0,1) and then linearly interpolate it with the given values in the claims.simulationISLPx table to determine the average claims among the group (it would take the total claims and divide it by 5, 6, 8, 10, or 12).

I have no idea what do add to my code. Any help would be really appreciated.

/*Inputs from Zero-Inflated Lognormal Function and Allowed to Paid Formula */

```<code>%let P_0 = .25;
%let Mean = 8.9;
%let Std_Dev = 1.8;
%let ISL = 50000;
%let Deductible = 1750;
%let COINS = .80;
%let OOPM = 2000;
%let Min_Paid = 253.08;
%let Ind_Cap_Claim = 2500000;
%let Iterations = 10;
%let Distribution = 'Lognormal';
%let Member_Count = (5,6,8,10,12,15,20,25,30,40,50,60,70,80,90,100,125,150,175,200,250,300,400,500)

libname claims

data simulation;
    do i = 1 to &Iterations;
        Px = rand('Uniform',&P_0,1);
        Px1 = rand('Uniform',0,1);/*generate random numbers from 0 to 1*/
            if Px>= %sysevalf(&P_0) then
        Allowed_Claims = quantile(&Distribution,Px1,%sysevalf(&Mean),%sysevalf(&Std_Dev));  /*inverse of cdf*/
        output;
    end;
run;

proc sql;
   create table claims.simulation_ISLPx as
   select Allowed_Claims, Px1
      from simulation
      order by Allowed_Claims,Px1;
quit;

proc sql;
alter table claims.simulation_ISLPx add Paid_Claims_NoISL float;
    update claims.simulation_ISLPx
        set Paid_Claims_NoISL = min(max(0,Allowed_Claims - %sysevalf(&OOPM), min(Allowed_Claims,
                                %sysevalf(&Min_Paid) + max(Allowed_Claims - %sysevalf(&Deductible)*%sysevalf(&COINS),0))),
                                %sysevalf(&Ind_Cap_Claim));
alter table claims.simulation_ISLPx add Paid_Claims_AfterISL float;
    update claims.simulation_ISLPx
        set Paid_Claims_AfterISL = min(Paid_Claims_NoISL, %sysevalf(&ISL));
alter table claims.simulation_ISLPx add Total_Cost float;
    update claims.simulation_ISLPx
        set Total_Cost = Paid_Claims_NoISL - Paid_Claims_AfterISL;
quit;

proc sql;
select * from claims.simulation_ISLPx;
run;
quit;
</code>```

Below is kind of what I thought about doing

```<code>%let Member_Count= [5,6,8,10,12,15,20,25,30,40,50,60,70,80,90,100,125,150,175,200,250,300,400,500];

data simulation_interpolation;
    do i = 1 to &Member_Count[0];
    xyz = rand('uniform',0,1);
        if xyz >= 0 then Px = xyz;
        output;
        end;
        run;
    proc print data= simulation_interpolation;
    run;
</code>```

答:
There are several ways to iterate thru a macro string.  Below is one approach I would use based on your example, although there are more efficient methods.  This will convert the Member_Count macro string into a dataset, and that dataset is used to generate the simulations.  Then a PROC SUMMARY is used to average the simulations for each group.

```<code>%let Member_Count= [5,6,8,10,12,15,20,25,30,40,50,60,70,80,90,100,125,150,175,200,250,300,400,500];

*** GET MACRO STRING AND CONVERT INTO A DATASET - ONE RECORD PER ITEM ***;
data start;
    *** COMPRESS BRACKETS FROM MACRO STRING ***;
    temp = compress("&member_count.", '[]');
    *** COUNT THE NUMBER OF COMMAS IN STRING AND ADD 1 ***;
    n = count(temp, ',') + 1;
    *** LOOP OVER STRING - GET MEMBER_COUNT, CONVERT TO NUMERIC, AND OUTPUT ***;
    do i = 1 to n;
        member_count = input( scan(temp, i), best8.);
        output;
    end;
run;

data simulation_interpolation;
    set start(keep=member_count);
    do i = 1 to member_count ;
        xyz = rand('uniform',0,1);
        if xyz >= 0 then Px = xyz;
        output;
    end;
run;

proc print data= simulation_interpolation;
run;

*** USE PROC SUMMARY TO CALCUATE AVERAGE FOR EACH GROUP OF ITERATIONS ***;
proc summary data=simulation_interpolation  nway;
    class member_count;
    var px;
    output out=stats  mean=mean;
run;
</code>```

I’m not sure this is what you want, and I don’t understand your description about interpolation, but hopefully this helps you make progress on your problem.

Body:
bear with me! This is a project that I've been working on for awhile, trying many things and I just can't seem to get it to work.

Below is the existing code that I'm using to create a new table. The existing output table (claims.simulation_ISLPx) is also below.

What I want to do is take an "array" of members (5,6,8,10,12) and run 5 iterations of a process for the 5 member group, 6 iterations for the 6 member group,..., and 12 iterations for the 12 member group.

The "process" should draw a random value from U(0,1) and then linearly interpolate it with the given values in the claims.simulationISLPx table to determine the average claims among the group (it would take the total claims and divide it by 5, 6, 8, 10, or 12).

I have no idea what do add to my code. Any help would be really appreciated.

/*Inputs from Zero-Inflated Lognormal Function and Allowed to Paid Formula */

%let P_0 = .25;
%let Mean = 8.9;
%let Std_Dev = 1.8;
%let ISL = 50000;
%let Deductible = 1750;
%let COINS = .80;
%let OOPM = 2000;
%let Min_Paid = 253.08;
%let Ind_Cap_Claim = 2500000;
%let Iterations = 10;
%let Distribution = 'Lognormal';
%let Member_Count = (5,6,8,10,12,15,20,25,30,40,50,60,70,80,90,100,125,150,175,200,250,300,400,500)

libname claims

data simulation;
    do i = 1 to &Iterations;
        Px = rand('Uniform',&P_0,1);
        Px1 = rand('Uniform',0,1);/*generate random numbers from 0 to 1*/
            if Px>= %sysevalf(&P_0) then
        Allowed_Claims = quantile(&Distribution,Px1,%sysevalf(&Mean),%sysevalf(&Std_Dev));  /*inverse of cdf*/
        output;
    end;
run;

proc sql;
   create table claims.simulation_ISLPx as
   select Allowed_Claims, Px1
      from simulation
      order by Allowed_Claims,Px1;
quit;

proc sql;
alter table claims.simulation_ISLPx add Paid_Claims_NoISL float;
    update claims.simulation_ISLPx
        set Paid_Claims_NoISL = min(max(0,Allowed_Claims - %sysevalf(&OOPM), min(Allowed_Claims,
                                %sysevalf(&Min_Paid) + max(Allowed_Claims - %sysevalf(&Deductible)*%sysevalf(&COINS),0))),
                                %sysevalf(&Ind_Cap_Claim));
alter table claims.simulation_ISLPx add Paid_Claims_AfterISL float;
    update claims.simulation_ISLPx
        set Paid_Claims_AfterISL = min(Paid_Claims_NoISL, %sysevalf(&ISL));
alter table claims.simulation_ISLPx add Total_Cost float;
    update claims.simulation_ISLPx
        set Total_Cost = Paid_Claims_NoISL - Paid_Claims_AfterISL;
quit;

proc sql;
select * from claims.simulation_ISLPx;
run;
quit;

Below is kind of what I thought about doing

%let Member_Count= [5,6,8,10,12,15,20,25,30,40,50,60,70,80,90,100,125,150,175,200,250,300,400,500];

data simulation_interpolation;
    do i = 1 to &Member_Count[0];
    xyz = rand('uniform',0,1);
        if xyz >= 0 then Px = xyz;
        output;
        end;
        run;
    proc print data= simulation_interpolation;
    run;

Body:
There are several ways to iterate thru a macro string.  Below is one approach I would use based on your example, although there are more efficient methods.  This will convert the Member_Count macro string into a dataset, and that dataset is used to generate the simulations.  Then a PROC SUMMARY is used to average the simulations for each group.

%let Member_Count= [5,6,8,10,12,15,20,25,30,40,50,60,70,80,90,100,125,150,175,200,250,300,400,500];

*** GET MACRO STRING AND CONVERT INTO A DATASET - ONE RECORD PER ITEM ***;
data start;
    *** COMPRESS BRACKETS FROM MACRO STRING ***;
    temp = compress("&member_count.", '[]');
    *** COUNT THE NUMBER OF COMMAS IN STRING AND ADD 1 ***;
    n = count(temp, ',') + 1;
    *** LOOP OVER STRING - GET MEMBER_COUNT, CONVERT TO NUMERIC, AND OUTPUT ***;
    do i = 1 to n;
        member_count = input( scan(temp, i), best8.);
        output;
    end;
run;

data simulation_interpolation;
    set start(keep=member_count);
    do i = 1 to member_count ;
        xyz = rand('uniform',0,1);
        if xyz >= 0 then Px = xyz;
        output;
    end;
run;

proc print data= simulation_interpolation;
run;

*** USE PROC SUMMARY TO CALCUATE AVERAGE FOR EACH GROUP OF ITERATIONS ***;
proc summary data=simulation_interpolation  nway;
    class member_count;
    var px;
    output out=stats  mean=mean;
run;

I’m not sure this is what you want, and I don’t understand your description about interpolation, but hopefully this helps you make progress on your problem.


问:
Okta: How to create usernames without email address?
How can I create unique usernames, without email address?

When I send curl request as below

```<code>curl -X POST \
  'https://xxxx.oktapreview.com/api/v1/users?activate=true' \
  -H 'accept: application/json' \
  -H 'authorization: SSWS xxxx' \
  -H 'content-type: application/json' \
  -d '{
  "profile": {
    "firstName": "Isaac",
    "lastName": "Brock",
    "email": "isaac@test.com",
    "login": "isaac1223"
  },
  "credentials": {
    "password" : { "value": "ddas4235sff" }
  }
}'
</code>```

I get response as below

```<code>{
  "errorCode": "E0000001",
  "errorSummary": "Api validation failed: login",
  "errorLink": "E0000001",
  "errorId": "oaeVuAktJ_ZSbGQbB_VfsuFlg",
  "errorCauses": [
    {
      "errorSummary": "login: User name must be in the form of an
email address (e.g. bob@nowhere.com)"
    }
  ]
}
</code>```

I want to keep different username than email address, how to achieve this in okta?

答: Unfortunately this isn't possible at the moment, there is a hard requirement that usernames must be email addresses.  Your request is a common one and it is being considered, I would suggest working with your contact at Okta to see where this may be on our roadmap.</p>

Body:
How can I create unique usernames, without email address?

When I send curl request as below

curl -X POST \
  'https://xxxx.oktapreview.com/api/v1/users?activate=true' \
  -H 'accept: application/json' \
  -H 'authorization: SSWS xxxx' \
  -H 'content-type: application/json' \
  -d '{
  "profile": {
    "firstName": "Isaac",
    "lastName": "Brock",
    "email": "isaac@test.com",
    "login": "isaac1223"
  },
  "credentials": {
    "password" : { "value": "ddas4235sff" }
  }
}'

I get response as below

{
  "errorCode": "E0000001",
  "errorSummary": "Api validation failed: login",
  "errorLink": "E0000001",
  "errorId": "oaeVuAktJ_ZSbGQbB_VfsuFlg",
  "errorCauses": [
    {
      "errorSummary": "login: User name must be in the form of an
email address (e.g. bob@nowhere.com)"
    }
  ]
}

I want to keep different username than email address, how to achieve this in okta?


问:
Sampling a list with linq
I need a helper method for adding axis labels to a chart. I don't want to add a label at every point along the axis that has values in the chart because that would get too busy. So I need to extract samples at regular intervals. So far I've come up with the following method which meets the requirements but I think there must be a neater way of accomplishing this with Linq. Can anyone think of how this could be made more concise (n represents the total number of samples I want back)?</p>

```<code>public static List<T> Sample<T>(this List<T> list, int n)
{
  var samples = new List<T>();
  var divisor = list.Count/n;
  for (var i = 0; i < list.Count; i++)
    if (samples.Count == i/divisor)
      samples.Add(list[i]);
  return samples;
}
</code>```

答:
If I understand correctly:</p>

```<code>int divisor = list.Count / n;
return list.Where((val, index) => index % divisor == 0).ToList();
</code>```

Title: Sampling a list with linq

Body:
I need a helper method for adding axis labels to a chart. I don't want to add a label at every point along the axis that has values in the chart because that would get too busy. So I need to extract samples at regular intervals. So far I've come up with the following method which meets the requirements but I think there must be a neater way of accomplishing this with Linq. Can anyone think of how this could be made more concise (n represents the total number of samples I want back)?

public static List<T> Sample<T>(this List<T> list, int n)
{
  var samples = new List<T>();
  var divisor = list.Count/n;
  for (var i = 0; i < list.Count; i++)
    if (samples.Count == i/divisor)
      samples.Add(list[i]);
  return samples;
}

Body:
If I understand correctly:

int divisor = list.Count / n;
return list.Where((val, index) => index % divisor == 0).ToList();


问:
Tag a commit in Xcode
Is there any way how to create a tag for specific commit in Xcode? Is there any support for git tags? I can see just branch stuff (new, switch, merge) under Source Control.</p>

答: Three years after, Xcode 9 has been enhanced by tagging feature. Just go to Source Control navigator and tag any commit via context menu opened by rightclicking that specific commit.

Title: Tag a commit in Xcode


问:
Removing all but specific string sequence
I have a list of strings. Each string contains a specific sequence of characters I need - there are three or four exact sequences I'm looking for - and the rest contains unpredictable data that needs to get eliminated from the string. ie:

```<code>sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']
goalList = ['sequenceB', 'sequenceA', 'sequenceC', '']
</code>```

I can use either sub or .replace to remove specific characters, but this is the inversion: I need to remove everything BUT specific strings, and in the case of list elements without an instance of a specific sequence I still need to keep the element so the list stays in order. I'm still new to regex - is there a way to do this I haven't found yet?

答:
Try this:

```<code>   goalList = ['' for x in range(len(bigList)]
   for elem in bigList:
       if sequenceA in bigList[elem]:
           goalList[elem] = sequenceA
       if sequenceB in bigList[elem]:
           goalList[elem] = sequenceB
       if sequenceA in bigList[elem]:
           goalList[elem] = sequenceC
</code>```

Of course, adapting it to the things you have on the database.

Body:
I have a list of strings. Each string contains a specific sequence of characters I need - there are three or four exact sequences I'm looking for - and the rest contains unpredictable data that needs to get eliminated from the string. ie:

sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']
goalList = ['sequenceB', 'sequenceA', 'sequenceC', '']

I can use either sub or .replace to remove specific characters, but this is the inversion: I need to remove everything BUT specific strings, and in the case of list elements without an instance of a specific sequence I still need to keep the element so the list stays in order. I'm still new to regex - is there a way to do this I haven't found yet?

Body:
Try this:

   goalList = ['' for x in range(len(bigList)]
   for elem in bigList:
       if sequenceA in bigList[elem]:
           goalList[elem] = sequenceA
       if sequenceB in bigList[elem]:
           goalList[elem] = sequenceB
       if sequenceA in bigList[elem]:
           goalList[elem] = sequenceC

Of course, adapting it to the things you have on the database.


问:
Exclusives Reservation Granule (ERG) on Apple's processors
Does anyone know what is ERG on Apple's A5, A5X, A6 and A6X processors?

We ran into an obscure bug with LDREX/STREX instructions and the behavior is different between A5's and A6's. The only explanation I have is that they have different ERG, but can't find anything on that. I also could not find a way to retrieve this value, the MRC instruction seems to be prohibited in the user mode on iOS.

Thank you!

答:
ERG size is a critical consideration when using ldrex/strex.

When an ldrex has been issued, if a memory access occurs in the ERG within which the ldrex read occured, the strex will fail.

It is not unusual to have a structure which contains an ldrex/strex target and some additional data, where the additional data is accessed between the ldrex/strex pair (for example, to store the value loaded by ldex).

If the ldrex/strex target has insufficient padding in the structure (i.e. the ERG size chosen is too small) the access to other members of the structure will therefore cause the strex to ALWAYS fail.

Game over, lights out.

Regarding ldrex/strex, ARM implements a "local monitor" and a "global monitor".  On systems with only a local monitor, the only way an ldrex/strex can fail is if two ldrexs are issued on the same address prior to an strex having been issued - only systems with global monitors actually notice memory bus traffic within the ERG of the ldrex/strex target.

ARM systems vary hugely and I suspect there are systems which have only local monitors and so do not in fact actually support ldrex/strex.


问:
Match sequence at the very beginning of a string along with other sequences in the middle
I'm trying to find a way to match 2 patterns in the same regular expression, but I can't seem to be able to combine both. These are a few strings I'm trying to match against:

```<code>0 800-204-4000
0800-204 4000
0 800 -204 - 4000
800 204 4000
</code>```

What I'm trying to do is find a regular expression that matches a zero at the beginning of a string if it exists and all subsequent white spaces and dashes. So I was able to match the first zero if it exists using /^0?/ and match all empty spaces and dashes using /[\s-]*/g but how exactly can I combine both into the same expression?

Edit:

So I want to match the first 0 IF it exists and all following spaces and dashes. So in the examples above, what should be matched is in brackets:

```<code>[0 ]800[-]204[-]4000
[0]800[-]204[ ]4000
[0 ]800[ -]204[ - ]4000
800[ ]204[ ]4000
</code>```

The regex provided in the answers do not work. Check it out: https://regex101.com/r/dMN6xR/1

答:
(^0|[\s-])[\s-]*

To avoid empty matches, set up a match group () that matches starting zero ^0 or | whitespace/- [\s-], and then match rest of whitespace/- [\s-]*

To allow whitespace before the zero, just add that right after the start anchor like this

(^[\s-]*0|[\s-])[\s-]*.

Body:
I'm trying to find a way to match 2 patterns in the same regular expression, but I can't seem to be able to combine both. These are a few strings I'm trying to match against:

0 800-204-4000
0800-204 4000
0 800 -204 - 4000
800 204 4000

What I'm trying to do is find a regular expression that matches a zero at the beginning of a string if it exists and all subsequent white spaces and dashes. So I was able to match the first zero if it exists using /^0?/ and match all empty spaces and dashes using /[\s-]*/g but how exactly can I combine both into the same expression?

Edit:

So I want to match the first 0 IF it exists and all following spaces and dashes. So in the examples above, what should be matched is in brackets:

[0 ]800[-]204[-]4000
[0]800[-]204[ ]4000
[0 ]800[ -]204[ - ]4000
800[ ]204[ ]4000

The regex provided in the answers do not work. Check it out: https://regex101.com/r/dMN6xR/1


问:
Get width of d3.js SVG text element after it's created
I'm trying to get the widths of a bunch of text elements I have created with d3.js

This is how I'm creating them:

```<code>var nodesText = svg.selectAll("text")
           .data(dataset)
           .enter()
           .append("text")
           .text(function(d) {
                return d.name;
           })
          .attr("x", function(d, i) {
                return i * (w / dataset.length);
           })
          .attr("y", function(d) {
                return 45;
          });
</code>```

I'm then using the width to create rectangles the same size as the text's boxes

```<code>var nodes = svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("x", function(d, i) {
                return i * (w / dataset.length);
            })
            .attr("y", function(d) {
                return 25;
            })
            .attr("width", function(d, i) {
              //To Do: find width of each text element, after it has been generated
              var textWidth = svg.selectAll("text")
                  .each(function () {
                      return d3.select(this.getComputedTextLength());
                  });
                console.log(textWidth);
                return textWidth;
            })
            .attr("height", function(d) {
                return 30;
            })
</code>```

I tried using the Bbox method from here but I don't really understand it. I think selecting the actual element is where I'm going wrong really.

答:
d3.selectAll returns a selection. You can get each of the elements by navigating through the array in the _groups property. When you are determining the width of a rectangle, you can use its index to get the corresponding text element:

```<code>.attr('width', function (d, i) {
    var textSelection = d3.selectAll('text');
    return textSelection._groups[0][i].getComputedTextLength();
});
</code>```

The _groups property of d3's selection has a list of nodes at [0]. This list contains all of the selected elements, which you can access by index. It's important that you get the SVG element so that you can use the getComputedTextLength method.

You may also want to consider creating the rect elements first, then the text elements, and then going back to the rectangles to edit the width attribute, so that the text elements are on top of the rectangles (in case you want to fill the rectangles with color).

Update:

It's typically preferred that you don't access _groups, though, so a safer way to get the matching text element's width would be:

```<code>.attr('width', function (d, i) {
    return d3.selectAll('text').filter(function (d, j) { return i === j; })
        .node().getComputedTextLength();
});
</code>```

Using node safely retrieves the element, and filter will find the text element which matches index.

Body:
I'm trying to get the widths of a bunch of text elements I have created with d3.js

This is how I'm creating them:

var nodesText = svg.selectAll("text")
           .data(dataset)
           .enter()
           .append("text")
           .text(function(d) {
                return d.name;
           })
          .attr("x", function(d, i) {
                return i * (w / dataset.length);
           })
          .attr("y", function(d) {
                return 45;
          });

I'm then using the width to create rectangles the same size as the text's boxes

var nodes = svg.selectAll("rect")
            .data(dataset)
            .enter()
            .append("rect")
            .attr("x", function(d, i) {
                return i * (w / dataset.length);
            })
            .attr("y", function(d) {
                return 25;
            })
            .attr("width", function(d, i) {
              //To Do: find width of each text element, after it has been generated
              var textWidth = svg.selectAll("text")
                  .each(function () {
                      return d3.select(this.getComputedTextLength());
                  });
                console.log(textWidth);
                return textWidth;
            })
            .attr("height", function(d) {
                return 30;
            })

I tried using the Bbox method from here but I don't really understand it. I think selecting the actual element is where I'm going wrong really.

Body:
d3.selectAll returns a selection. You can get each of the elements by navigating through the array in the _groups property. When you are determining the width of a rectangle, you can use its index to get the corresponding text element:

.attr('width', function (d, i) {
    var textSelection = d3.selectAll('text');
    return textSelection._groups[0][i].getComputedTextLength();
});

The _groups property of d3's selection has a list of nodes at [0]. This list contains all of the selected elements, which you can access by index. It's important that you get the SVG element so that you can use the getComputedTextLength method.

You may also want to consider creating the rect elements first, then the text elements, and then going back to the rectangles to edit the width attribute, so that the text elements are on top of the rectangles (in case you want to fill the rectangles with color).

Update:

It's typically preferred that you don't access _groups, though, so a safer way to get the matching text element's width would be:

.attr('width', function (d, i) {
    return d3.selectAll('text').filter(function (d, j) { return i === j; })
        .node().getComputedTextLength();
});

Using node safely retrieves the element, and filter will find the text element which matches index.


问:
Eclipse CDT - why is it building copies of files I made?
I'm using an eclipse project that somebody else set up.  My past experience has been with Makefile-based projects imported into Eclipse CDT.  This one is using the CDT internal builder.

The problem I'm having is that due to unrelated version control issues, I made some temporary copies of source files, just to make sure the sources I've changed don't get clobbered.  These copies are getting sucked into the CDT build and of course causing multiple definition errors.  Is this standard behavior for the internal builder?  How can I avoid having the builder pick up files that I don't want to be compiled?

Illustration:
I changed foo.cpp and bar.cpp.  I made copies of these files: "foo - Copy.cpp" and bar - Copy.cpp" in the same original folder.  The eclipse builder tries to build foo.cpp, bar.cpp, "foo - Copy.cpp", and "bar - Copy.cpp".  I did not add the "copy" files to the project.

答: When Eclipse finds a c or cpp file in a C or C++ project folder, it assumes you want the file built and linked in. You can tell Eclipse otherwise by right clicking the file and selecting Resource Configurations->Exclude from Build from the pop-up menu. Put a check mark in the configurations, sounds like all of them in this case,  you wish the file to be left out of and then click OK.


问:
Asterisk hangs up if caller inputs number early
We have an Asterisk IVR system setup that prompts the user for input

In our extensions file, we have the following:

```<code>[englishprocess]
exten => s,1,Answer()
exten => s,n,Wait(1)
exten => s,n,Set(TIMEOUT(digit)=2)
exten => s,n,agi(mstts.agi,"Please enter your ID number followed by pound.",en-US)
exten => s,n,Read(APCODE,,666)
exten => s,n,agi(mstts.agi,"Your ID Number is",en)
exten => s,n,SayDigits(${APCODE})
exten => s,n,agi(mstts.agi,"If this is correct press, 1, otherwise, press, 3",en-US)
exten => s,n,Read(CHECK,,1)
exten => s,n,GotoIf($["${CHECK}" = "3"]?englishprocess,s,1)
exten => s,n,Set(MYADDR=${CURL(webserviceaddress.php?idnum=${APCODE})})
exten => s,n,agi(mstts.agi,${MYADDR},en-US)
exten => s,n,Hangup()
</code>```

The problem is that if the user inputs their ID before the text to speech prompt finishes, or if they hit 1 before it finishes saying

"If this is correct press, 1, otherwise, press, 3"

The service hangs up.

How can we keep the process the same and accept early user input?

If accepting user input early is not possible is there a way to prevent hangup and prompt again?

答:
We switched to Amazon's Polly service to generate the sound files and used the asterisk method Playback(filename) instead of agi() inside of extensions_custom.conf in order to stop the call from hanging up if the user inputs text prematurely.

Granted the service ignores the inputs that are put in early, but at least it does not hang up. A better solution would accept early input. I'll update this if I find an alternative.

Edit: Found an alternative Read() which lets us play soundbites that can be interrupted, so we now have a mix of Read() and playback() calls and can control which sound files can be skipped by the user in this way. The service no longer hangs up on users and we no longer use agi() calls.

Body:
We have an Asterisk IVR system setup that prompts the user for input

In our extensions file, we have the following:

[englishprocess]
exten => s,1,Answer()
exten => s,n,Wait(1)
exten => s,n,Set(TIMEOUT(digit)=2)
exten => s,n,agi(mstts.agi,"Please enter your ID number followed by pound.",en-US)
exten => s,n,Read(APCODE,,666)
exten => s,n,agi(mstts.agi,"Your ID Number is",en)
exten => s,n,SayDigits(${APCODE})
exten => s,n,agi(mstts.agi,"If this is correct press, 1, otherwise, press, 3",en-US)
exten => s,n,Read(CHECK,,1)
exten => s,n,GotoIf($["${CHECK}" = "3"]?englishprocess,s,1)
exten => s,n,Set(MYADDR=${CURL(webserviceaddress.php?idnum=${APCODE})})
exten => s,n,agi(mstts.agi,${MYADDR},en-US)
exten => s,n,Hangup()

The problem is that if the user inputs their ID before the text to speech prompt finishes, or if they hit 1 before it finishes saying

"If this is correct press, 1, otherwise, press, 3"

The service hangs up.

How can we keep the process the same and accept early user input?

If accepting user input early is not possible is there a way to prevent hangup and prompt again?


问:
GridAdaptedFeatureDetector disappeared from OpenCV 3.1?
I'm working on an algorithm that should recognize an object from an image in a video file. For now, I want to use ORB(I know that SURF and SIFT are better at this kind of job, but I want to make this affirmation based on my results). Now I have one problem: when I run my program, in one of the images the keypoints are detected in a different area than in the other image and it hardly finds any matches. Now, in OpenCV 2.4 there was GridAdaptedFeatureDetector, a class that allows you to partition the source image into a grid and detect points in each cell. But I'm using OpenCV 3.1(Visual Studio 2015) and it seems to have disappeared?  Please help me find a solution.</p>

答:
It's in python, so it might be useful (I found this question when looking for a python solution so hopefully someone else does too...) but this is what I used to iterate over sub-blocks of the image:</p>

```<code>def blocks(img, rows, cols):
    h, w = img.shape[:2]
    xs = np.uint32(np.rint(np.linspace(0, w, num=cols+1)))
    ys = np.uint32(np.rint(np.linspace(0, h, num=rows+1)))
    ystarts, yends = ys[:-1], ys[1:]
    xstarts, xends = xs[:-1], xs[1:]
    for y1, y2 in zip(ystarts, yends):
        for x1, x2 in zip(xstarts, xends):
            yield img[y1:y2, x1:x2]
</code>```

Body:
It's in python, so it might be useful (I found this question when looking for a python solution so hopefully someone else does too...) but this is what I used to iterate over sub-blocks of the image:

def blocks(img, rows, cols):
    h, w = img.shape[:2]
    xs = np.uint32(np.rint(np.linspace(0, w, num=cols+1)))
    ys = np.uint32(np.rint(np.linspace(0, h, num=rows+1)))
    ystarts, yends = ys[:-1], ys[1:]
    xstarts, xends = xs[:-1], xs[1:]
    for y1, y2 in zip(ystarts, yends):
        for x1, x2 in zip(xstarts, xends):
            yield img[y1:y2, x1:x2]


问:
Get a subset of data from one row of Dataframe
Let's say I have a dataframe df with columns 'A', 'B', 'C'
Now I just want to extract row 2 of df and only columns 'B' and 'C'. What is the most efficient way to do that?

Can you please tell me why df.ix[2, ['B', 'C']] didn't work?

Thank you!

答:
row_2 = df[['B', 'C']].iloc[1]

OR

# Convert column to 2xN vector, grab row 2
row_2 = list(df[['B', 'C']].apply(tuple, axis=1))[1]


问:
How can i run all migrations for all plugins in cakephp 3?
I know I can run bin/cake Migrations migrate --plugin MyPlugin

but I use 50+ plugins in my project and id liked to run all migrations in all plugins with one command is this possible?

答:
As far as I am aware there is no straight forward command for running migrations for all plugins. However, you could put together a simple Shell script to do this.

You can retrieve a list of all the loaded plugins for an app using:-

```<code>$plugins = Plugin::loaded();
</code>```

You can then run the migrations for each plugin using dispatchShell which allows you to run a command from another Shell:-

```<code>$this->dispatchShell(
    'migrations',
    'migrate',
    '-p',
    $plugin
);
</code>```

Each argument for the migration is passed as an argument to dispatchShell.

So, putting all that together into a Shell script:-

```<code><?php
// src/Shell/InstallShell.php
namespace App\Shell;

use Cake\Console\Shell;
use Cake\Core\Plugin;

class InstallShell extends Shell
{
    public function plugins()
    {
        $plugins = Plugin::loaded();
        foreach ($plugins as $plugin) {
            $this->dispatchShell(
                'migrations',
                'migrate',
                '-p',
                $plugin
            );
        }
    }
}
</code>```

This script would be called like $ bin/cake install plugins.

Body:
As far as I am aware there is no straight forward command for running migrations for all plugins. However, you could put together a simple Shell script to do this.

You can retrieve a list of all the loaded plugins for an app using:-

$plugins = Plugin::loaded();

You can then run the migrations for each plugin using dispatchShell which allows you to run a command from another Shell:-

$this->dispatchShell(
    'migrations',
    'migrate',
    '-p',
    $plugin
);

Each argument for the migration is passed as an argument to dispatchShell.

So, putting all that together into a Shell script:-

<?php
// src/Shell/InstallShell.php
namespace App\Shell;

use Cake\Console\Shell;
use Cake\Core\Plugin;

class InstallShell extends Shell
{
    public function plugins()
    {
        $plugins = Plugin::loaded();
        foreach ($plugins as $plugin) {
            $this->dispatchShell(
                'migrations',
                'migrate',
                '-p',
                $plugin
            );
        }
    }
}

This script would be called like $ bin/cake install plugins.


问:
Find open sockets in docker container
I have attached to a docker container and need to find out the number of sockets being open by java application . Unfortunately there is no lsof or netstat available in the container . There is no data in /proc/PID/net/tcp. Is there any way I can find this data?

答:
I like netshoot for this. You can run a container in the same networking and even pid namespace, and use the tools in netshoot to analyze the other container's network:</p>

```<code>$ docker run -d -p 8888:80 --name nginx-test nginx
d8a90f5c7d1744483ae6d26cc97dad222ed237b5c4211f711c9f15f88252897f

$ docker run --net container:nginx-test --pid container:nginx-test -it --rm nicolaka/netshoot

/ # netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1/nginx: master pro
/ # ps -ef
PID   USER     TIME   COMMAND
    1 root       0:00 nginx: master process nginx -g daemon off;
    7 104        0:00 nginx: worker process
    8 root       0:00 sh
   15 root       0:00 ps -ef
</code>```

ContentLicense: CC BY-SA 4.0

Title: Find open sockets in docker container

Body:
I like netshoot for this. You can run a container in the same networking and even pid namespace, and use the tools in netshoot to analyze the other container's network:

$ docker run -d -p 8888:80 --name nginx-test nginx
d8a90f5c7d1744483ae6d26cc97dad222ed237b5c4211f711c9f15f88252897f

$ docker run --net container:nginx-test --pid container:nginx-test -it --rm nicolaka/netshoot

/ # netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1/nginx: master pro
/ # ps -ef
PID   USER     TIME   COMMAND
    1 root       0:00 nginx: master process nginx -g daemon off;
    7 104        0:00 nginx: worker process
    8 root       0:00 sh
   15 root       0:00 ps -ef


问:
How to get props value of boolean type in react
I have created one component where I am passing two props - taskName which is string and status which is boolean. I found a way to get taskName in my App.js but it failed in case of boolean type.

Doesn't react support boolean props ?

TaskComponent.js

```<code>export default class TaskComponent extends Component {
    render() {
        var taskStatus = this.props.status;
        if(taskStatus)
            return <h1><strike>Task: {this.props.taskName}</strike></h1>
    }
}
</code>```

App.js

```<code>class App extends Component {
  render() {
    return (
      <TaskComponent taskName="Buy Milk" status={false} />
    );
  }
}

export default App;
</code>```

I am getting this error while trying to get status value.

TaskComponent.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

答:
Because you are not returning anything when status is false (by default it will return undefined that's why you are getting the error), You forgot the else condition, you need to return something when status will be false.

If you don't want to render anything then return null.

write it like this:

```<code>render() {
    var taskStatus = this.props.status;
    if(taskStatus)
        return <h1><strike>Task: {this.props.taskName}</strike></h1>
    else return null;
}
</code>```

Body:
I have created one component where I am passing two props - taskName which is string and status which is boolean. I found a way to get taskName in my App.js but it failed in case of boolean type.

Doesn't react support boolean props ?

TaskComponent.js

export default class TaskComponent extends Component {
    render() {
        var taskStatus = this.props.status;
        if(taskStatus)
            return
Task: {this.props.taskName}

    }
}

App.js

class App extends Component {
  render() {
    return (
      <TaskComponent taskName="Buy Milk" status={false} />
    );
  }
}

export default App;

I am getting this error while trying to get status value.

TaskComponent.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Body:
Because you are not returning anything when status is false (by default it will return undefined that's why you are getting the error), You forgot the else condition, you need to return something when status will be false.

If you don't want to render anything then return null.

write it like this:

render() {
    var taskStatus = this.props.status;
    if(taskStatus)
        return <h1><strike>Task: {this.props.taskName}</strike></h1>
    else return null;
}


问:
Executing a Python script in Apache2
I am trying to execute a Python program using Apache.  However, Apache will only serve the file and not actually execute it.  The permissions on the file are r/w/x and it is in /var/www.  I will post the contents of httpd.conf and the program code after.  I also tried to running the python script as a .cgi file but that did not work as well.  I have both the mod_python and mod_wsgi modules loaded into apache as well.

Python sample:

```<code>#!/usr/bin/python

# enable debugging
import cgitb
cgitb.enable()

print "Content-Type: text/plain\r\n\r\n"
print

print "Hello World!"
</code>```

httpd.conf:

```<code>AddHandler cgi-script .cgi .pl
AddHandler python-program .py
</code>```

I know its a small httpd.conf file but when I installed apache, there was nothing in the file.  I should also mention that this is just so that I learn the basics of running python in apache.  It is not meant for production.
Thanks for the help!

Edit

The OS I'm using is Ubuntu 10.04 and the version of apache is 2.  I have python version 2.6 which is automatically used when #!/usr/bin/env python is invoked.

I am getting two main errors, the first is that the file is not being found even though the permissions of the file and folder are 777. The error from the log is

```<code>[Sun Feb 05 13:29:44 2012] [error] [client 192.168.1.3] File does not exist: /var/www/poit-0.1
</code>```

This error is for a different python script that I did not write.  What is weird is that the file shows up in the index of the folder when accessed from a browser window.  However, when I navigate to the file, I get the above error.

The other error that I am getting is premature end of headers.  The error is below:

```<code>[Sun Feb 05 12:10:19 2012] [error] (8)Exec format error: exec of '/var/www/pyth.py' failed
[Sun Feb 05 12:10:19 2012] [error] [client 192.168.1.3] Premature end of script headers: pyth.py
</code>```

答:
In my case, it was a trivial issue. I had to add this line:

```<code>#!/usr/bin/python3
</code>```

to the top of every .py file I wanted to run.

Then, everything started working correctly.

Title: Executing a Python script in Apache2

Body:
I am trying to execute a Python program using Apache.  However, Apache will only serve the file and not actually execute it.  The permissions on the file are r/w/x and it is in /var/www.  I will post the contents of httpd.conf and the program code after.  I also tried to running the python script as a .cgi file but that did not work as well.  I have both the mod_python and mod_wsgi modules loaded into apache as well.

Python sample:

#!/usr/bin/python

# enable debugging
import cgitb
cgitb.enable()

print "Content-Type: text/plain\r\n\r\n"
print

print "Hello World!"

httpd.conf:

AddHandler cgi-script .cgi .pl
AddHandler python-program .py

I know its a small httpd.conf file but when I installed apache, there was nothing in the file.  I should also mention that this is just so that I learn the basics of running python in apache.  It is not meant for production.
Thanks for the help!

Edit

The OS I'm using is Ubuntu 10.04 and the version of apache is 2.  I have python version 2.6 which is automatically used when #!/usr/bin/env python is invoked.

I am getting two main errors, the first is that the file is not being found even though the permissions of the file and folder are 777. The error from the log is

[Sun Feb 05 13:29:44 2012] [error] [client 192.168.1.3] File does not exist: /var/www/poit-0.1

This error is for a different python script that I did not write.  What is weird is that the file shows up in the index of the folder when accessed from a browser window.  However, when I navigate to the file, I get the above error.

The other error that I am getting is premature end of headers.  The error is below:

[Sun Feb 05 12:10:19 2012] [error] (8)Exec format error: exec of '/var/www/pyth.py' failed
[Sun Feb 05 12:10:19 2012] [error] [client 192.168.1.3] Premature end of script headers: pyth.py

Body:
In my case, it was a trivial issue. I had to add this line:

#!/usr/bin/python3

to the top of every .py file I wanted to run.

Then, everything started working correctly.


问:
Using Dagger, is it ok to recreate an injected object?
A have code that is similar to this one:

```<code>class MyActivity extends Activity {
    IStrategy mStrategy;

    public void onCreate(Bundle data) {
        if (someSpecificCondition) {
            mStrategy = new StrategyA();
        } else {
            mStrategy = new StrategyB();
        }
    }

    public void onUnsupportedState() {
        // Will have to switch strategy
        mStrategy = new StrategyB();
    }
}
</code>```

I would like to inject IStrategy here. But I have two problems:

It is an interface and the concrete implementation changes dynamically.

Even after a concrete implementation is chosen, there is the possibility that it will need to be recreated.

I could overcome (1) by creating a provides method with the decision logic (not sure if it is the best approach though).

But I am not sure what to do with (2).
Is it ok to manually create an injected object in this case? Does anyone see another solution?

答:
As you said, adding logic to provider method is not a good design decision. Manually instantiating the object is valid in some cases, but only as a last resort.

In this case, the best approach (IMHO) is to inject abstract factory that instantiates IStrategy implementations on demand.

In the current state of the matters, the factory method will need to accept additional parameter that allows you to specify which strategy you're interested in. While it is not the end of the world, the fact that the client controls which strategy it uses is a bit unclean - the client knows how many strategies are there.

Depending on the specific use case at hand, you might be able to refactor the code and extract the logic that differentiates between strategies out of the client. That way your client will be asking for IStrategy while being completely agnostic of both the specifics of the implementation, and the number of available implementations.

Body:
A have code that is similar to this one:

class MyActivity extends Activity {
    IStrategy mStrategy;

    public void onCreate(Bundle data) {
        if (someSpecificCondition) {
            mStrategy = new StrategyA();
        } else {
            mStrategy = new StrategyB();
        }
    }

    public void onUnsupportedState() {
        // Will have to switch strategy
        mStrategy = new StrategyB();
    }
}

I would like to inject IStrategy here. But I have two problems:

It is an interface and the concrete implementation changes dynamically.

Even after a concrete implementation is chosen, there is the possibility that it will need to be recreated.

I could overcome (1) by creating a provides method with the decision logic (not sure if it is the best approach though).

But I am not sure what to do with (2).
Is it ok to manually create an injected object in this case? Does anyone see another solution?


问:
In scala, can a variable changed in a for-loop be used outside the loop?
I'm updating a variable within a for-loop in scala that I need outside the loop. I tested the code below and got the message "ERROR: undefined". The variable is not empty, inside the loop the values are returned. Thank you.  </p>

```<code>val example=List(0,0,1,0.7,10,2,5,7,4,1,-9,0,0,0,0,3,3,0,0,0,-80,-6.6,-1,0)
var b=scala.collection.mutable.MutableList.empty[Double]
var b_val:Double=0

for (i<-1 to 24) {
    if ( example (i) != 0 ){b_val = b_val + example(i)} else {b_val = 0}
    b += b_val;
}
println(b);
</code>```

答:
you are trying to add b_val which is double to AnyVal which won't work.

So, to add you need to cast the elements in List to Double as below or define example as List[Double], also your iteration won't work because you are doing to 24 which will blow up because list indexes from 0 to 23

```<code>    val example = List(0, 0, 1, 0.7, 10, 2, 5, 7, 4, 1, -9, 0, 0, 0, 0, 3, 3, 0, 0, 0, -80, -6.6, -1, 0)
    var b = scala.collection.mutable.MutableList.empty[Double]
    var b_val: Double = 0

    for (i <- 0 until example.length) {

      if (example(i) != 0) {
        b_val = (b_val + example(i).asInstanceOf[Double])
      } else {
        b_val = 0
      }
      b += b_val
    }
    println(b)
</code>```

Result is : MutableList(0.0, 0.0, 1.0, 1.7, 11.7, 13.7, 18.7, 25.7, 29.7, 30.7, 21.7, 0.0, 0.0, 0.0, 0.0, 3.0, 6.0, 0.0, 0.0, 0.0, -80.0, -86.6, -87.6, 0.0)

But only you know what you are trying to achieve, small refactor I would do to it in scala way

```<code>val example = List(0, 0, 1, 0.7, 10, 2, 5, 7, 4, 1, -9, 0, 0, 0, 0, 3, 3, 0, 0, 0, -80, -6.6, -1, 0)

var b = scala.collection.mutable.MutableList.empty[Double]

var b_val: Double = 0

example.foreach(elem => {
  if (elem != 0) {
    b_val = b_val + elem.asInstanceOf[Double]
  } else {
    b_val = 0
  }
  b += b_val
})

println(b)
</code>```

Body:
I'm updating a variable within a for-loop in scala that I need outside the loop. I tested the code below and got the message "ERROR: undefined". The variable is not empty, inside the loop the values are returned. Thank you.

val example=List(0,0,1,0.7,10,2,5,7,4,1,-9,0,0,0,0,3,3,0,0,0,-80,-6.6,-1,0)
var b=scala.collection.mutable.MutableList.empty[Double]
var b_val:Double=0

for (i<-1 to 24) {
    if ( example (i) != 0 ){b_val = b_val + example(i)} else {b_val = 0}
    b += b_val;
}
println(b);

Body:
you are trying to add b_val which is double to AnyVal which won't work.

So, to add you need to cast the elements in List to Double as below or define example as List[Double], also your iteration won't work because you are doing to 24 which will blow up because list indexes from 0 to 23

    val example = List(0, 0, 1, 0.7, 10, 2, 5, 7, 4, 1, -9, 0, 0, 0, 0, 3, 3, 0, 0, 0, -80, -6.6, -1, 0)
    var b = scala.collection.mutable.MutableList.empty[Double]
    var b_val: Double = 0

    for (i <- 0 until example.length) {

      if (example(i) != 0) {
        b_val = (b_val + example(i).asInstanceOf[Double])
      } else {
        b_val = 0
      }
      b += b_val
    }
    println(b)

Result is : MutableList(0.0, 0.0, 1.0, 1.7, 11.7, 13.7, 18.7, 25.7, 29.7, 30.7, 21.7, 0.0, 0.0, 0.0, 0.0, 3.0, 6.0, 0.0, 0.0, 0.0, -80.0, -86.6, -87.6, 0.0)

But only you know what you are trying to achieve, small refactor I would do to it in scala way

val example = List(0, 0, 1, 0.7, 10, 2, 5, 7, 4, 1, -9, 0, 0, 0, 0, 3, 3, 0, 0, 0, -80, -6.6, -1, 0)

var b = scala.collection.mutable.MutableList.empty[Double]

var b_val: Double = 0

example.foreach(elem => {
  if (elem != 0) {
    b_val = b_val + elem.asInstanceOf[Double]
  } else {
    b_val = 0
  }
  b += b_val
})

println(b)


问:
different version of Typescript used in `npm run` script
I use npm as my build tool and one of the entries in the scripts dictionary of my packages.json file is "tsc", which causes the .ts files in my project to be compiled.  However I noticed that I was getting different TypeScript error messages when I call > tsc directly v.s. calling > npm run start.  I updated the script entry to (tsc -v; tsc), and I get:

```<code>> npm run build
message TS6029: Version 1.6.2
</code>```

whereas as If I call the same command directly, I get:

```<code>> (tsc -v; tsc)
Version 1.8.10
</code>```

What could cause this behavior?

答:
Another consideration (for those who may also experience a similar issue, but without having a direct dependency), is that other npm packages could have a dependency on TypeScript, and those packages are using an older version. In this scenario, you won't see anything in your package.json file, but npm will find the transitive dependency and use that.

For example, the grunt-typescript module has a dependency on TypeScript, but the module is old and outdated--even though it still works. This could cause conflicts with having tsc -p . inside of a postinstall script.

Body:
I use npm as my build tool and one of the entries in the scripts dictionary of my packages.json file is "tsc", which causes the .ts files in my project to be compiled.  However I noticed that I was getting different TypeScript error messages when I call > tsc directly v.s. calling > npm run start.  I updated the script entry to (tsc -v; tsc), and I get:

> npm run build
message TS6029: Version 1.6.2

whereas as If I call the same command directly, I get:

> (tsc -v; tsc)
Version 1.8.10

What could cause this behavior?


问:
Python: Multiprocessing Does Not Complete Jobs
I'm using python 2.7 with multiprocessing::Pool to run a job in parallel

I've simplified the example below, but here's the main gist of it.

It will create a file for each person in my dict using the apply_async() function. However when I check to see if the file was created properly, I notice that sometimes the file was not created.

Now I'm thinking I've done something wrong in how I used multiprocessing::Pool

Any advice?

```<code>import os
from multiprocessing import Pool

def outputFile(person):
    ofh=open(person+'.txt','w')
    ofh.write('test\n')
    ofh.close()

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputFile,args(person))
pool.close()
pool.join()
for person in person_dict:
    print os.path.isfile(person+'.txt')
</code>```

```<code>True
True
False
True
</code>```

答:
Could this be related to contents of the person_dict?

I have modified your code and run it several times. They all produced the expected results.

Here is the code I modified and tested:

```<code>import os
from multiprocessing import Pool

def outputfile(person):
    with open(person+'.txt','w') as ofh:
        ofh.write('test\n')

person_dict = {'a': 'a', 'b': 'b', 'c':'c', 'd':'d'}

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputfile, (person))
pool.close()
pool.join()

for person in person_dict:
    print(os.path.isfile(person+'.txt'))
</code>```

Body:
I'm using python 2.7 with multiprocessing::Pool to run a job in parallel

I've simplified the example below, but here's the main gist of it.

It will create a file for each person in my dict using the apply_async() function. However when I check to see if the file was created properly, I notice that sometimes the file was not created.

Now I'm thinking I've done something wrong in how I used multiprocessing::Pool

Any advice?

import os
from multiprocessing import Pool

def outputFile(person):
    ofh=open(person+'.txt','w')
    ofh.write('test\n')
    ofh.close()

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputFile,args(person))
pool.close()
pool.join()
for person in person_dict:
    print os.path.isfile(person+'.txt')

True
True
False
True

Body:
Could this be related to contents of the person_dict?

I have modified your code and run it several times. They all produced the expected results.

Here is the code I modified and tested:

import os
from multiprocessing import Pool

def outputfile(person):
    with open(person+'.txt','w') as ofh:
        ofh.write('test\n')

person_dict = {'a': 'a', 'b': 'b', 'c':'c', 'd':'d'}

pool = Pool(processes=4)
for person in person_dict:
    pool.apply_async(outputfile, (person))
pool.close()
pool.join()

for person in person_dict:
    print(os.path.isfile(person+'.txt'))


问:
Install packages using pip for updated versions of python
I recently updated from Python 3.5 to Python 3.6 and am trying to use packages that I had previously downloaded, but they are not working for the updated version of Python.  When I try to use pip, I use the command "pip install selenium" and get the message "Requirement already satisfied: selenium in /Users/Jeff/anaconda/lib/python3.5/site-packages"  How do I add packages to the new version of Python?</p>

答:
First, make sure that your packages do have compatibility with the version of Python you're looking to use.

Next, run pip freeze > requirements.txt in the base directory of your Python project. This puts everything in a readable file to re-install from. If you know of any packages that require a certain version that you'll want to re-install, put package==x.x.x (where package is the package name and x.x.x is the version number) in the list of packages to make sure it downloads the correct version.

Run pip uninstall -r requirements.txt -y to uninstall all packages. Afterwards, run pip install -r requirements.txt.

This allows you to keep packages at the correct version for the ones you assign a version number in requirements.txt, while upgrading all others.


问:
Why is the Chars property of the StringBuilder class missing in Visual C# 2008 Express?
That's pretty much the whole question. I've installed Visual C# 2008 Express on a clean Windows XP Pro SP3 machine, started a new Windows Forms project, double-clicked the form to create a Form1_Load method, then typed:

```<code>StringBuilder SB;
SB = new StringBuilder("test");
SB.Chars
</code>```

but Chars doesn't appear on the autocomplete menu. Why not?

答:
It's because you're using C#.

In C#, properties that take parameters can't be referred to by name, while in VB they can be used by name. You can access this property in the same way as an Items property off of a collection:

```<code>StringBuilder sb = new StringBuilder();
char ch = sb[0];
</code>```

This will return the first character in the StringBuilder's internal string.

OwnerDisplayName: matthewk

Body:
That's pretty much the whole question. I've installed Visual C# 2008 Express on a clean Windows XP Pro SP3 machine, started a new Windows Forms project, double-clicked the form to create a Form1_Load method, then typed:

StringBuilder SB;
SB = new StringBuilder("test");
SB.Chars

but Chars doesn't appear on the autocomplete menu. Why not?

Body:
It's because you're using C#.

In C#, properties that take parameters can't be referred to by name, while in VB they can be used by name. You can access this property in the same way as an Items property off of a collection:

StringBuilder sb = new StringBuilder();
char ch = sb[0];

This will return the first character in the StringBuilder's internal string.

OwnerDisplayName: Andy


问:
Removing all but specific string sequence
I have a list of strings. Each string contains a specific sequence of characters I need - there are three or four exact sequences I'm looking for - and the rest contains unpredictable data that needs to get eliminated from the string. ie:

```<code>sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']
goalList = ['sequenceB', 'sequenceA', 'sequenceC', '']
</code>```

I can use either sub or .replace to remove specific characters, but this is the inversion: I need to remove everything BUT specific strings, and in the case of list elements without an instance of a specific sequence I still need to keep the element so the list stays in order. I'm still new to regex - is there a way to do this I haven't found yet?

答:
You can do that with a simple double loop:</p>

```<code>sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']

goalList = []
for element in bigList:
    for seq in sequences:
        if seq in element:
            break
    goalList.append(seq if seq in element else "")

print(goalList)
# prints: ['sequenceB', 'sequenceA', 'sequenceC', '']
</code>```

Body:
I have a list of strings. Each string contains a specific sequence of characters I need - there are three or four exact sequences I'm looking for - and the rest contains unpredictable data that needs to get eliminated from the string. ie:

sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']
goalList = ['sequenceB', 'sequenceA', 'sequenceC', '']

I can use either sub or .replace to remove specific characters, but this is the inversion: I need to remove everything BUT specific strings, and in the case of list elements without an instance of a specific sequence I still need to keep the element so the list stays in order. I'm still new to regex - is there a way to do this I haven't found yet?

Body:
You can do that with a simple double loop:

sequences = ['sequenceA', 'sequenceB', 'sequenceC']
bigList = ['Garbage sequenceB blahblah', 'sequenceA nonsense', 'silliness sequenceC', 'total nonsense']

goalList = []
for element in bigList:
    for seq in sequences:
        if seq in element:
            break
    goalList.append(seq if seq in element else "")

print(goalList)
# prints: ['sequenceB', 'sequenceA', 'sequenceC', '']


问:
Run python script only if it's not running
I want to launch a python script from another python script. I know how to do it. But I should launch this script only if it is not running already.

code:

```<code>import os
os.system("new_script.py")
</code>```

But I'm not sure how to check if this script is already running or not.

答:
Came across this old question looking for solution myself.

Use psutil:

```<code>import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])
</code>```

You can also use start time of the previous process to determine if it's running too long and might be hung:

```<code>process.create_time()
</code>```

There is tons of other useful metadata of the process.

Body:
I want to launch a python script from another python script. I know how to do it. But I should launch this script only if it is not running already.

code:

import os
os.system("new_script.py")

But I'm not sure how to check if this script is already running or not.

Body:
Came across this old question looking for solution myself.

Use psutil:

import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])

You can also use start time of the previous process to determine if it's running too long and might be hung:

process.create_time()

There is tons of other useful metadata of the process.


问:
Module "QtQuick.Controls" is not installed on Raspberry Pi
I'm trying to compile some qml on a Raspberry pi 3 running Raspbian-Jessie using qt5 (5.3.2).

I managed to run some simple stuff but now I need to use QtQuick.Controls so I added
import QtQuick.Controls 1.0 to my qml file but when I try to run it, I get this error message: module "QtQuick.Controls" is not installed

Qt is installed in the following folder /usr/lib/arm-linux-gnueabihf/qt5/ (it's auto detected) so I went there and found that QtQuick Controls is actually in there (in [path to qt]/qml/QtQuick/Controls)

Do I need to do something to actually install it ?

I tried to add /usr/lib/arm-linux-gnueabihf/qt5/qml/QtQuick/Controls to QML_IMPORT_PATH but I still get the error message.

I also read that I need QtQuick 2.0 for QtQuick.Controls to work but when I change import QtQuick 1.0 to import QtQuick 2.0 I get a module "QtQuick" version 2.0 is not installed

Anyone managed to use QtQuick.Controls on Raspberry Pi ?

Any advice on how to debug this ?

答:
Dependencies for QML in Raspbian are somewhat confusing. Try checking if you have these packages installed, using apt-get install, or apt-cache search first to see what every single package does:

```<code>qtdeclarative5-*
qml-module-qtquick*
qtquick1-*
qtquickcontrols5-*
qml-module-qtquick2
</code>```

After that, Qt Creator should compile without problems.

Body:
Dependencies for QML in Raspbian are somewhat confusing. Try checking if you have these packages installed, using apt-get install, or apt-cache search first to see what every single package does:

qtdeclarative5-*
qml-module-qtquick*
qtquick1-*
qtquickcontrols5-*
qml-module-qtquick2

After that, Qt Creator should compile without problems.


问:
cut a field from its position & place it in different position
I have 2 files - file1 & file2 with contents as shown.

```<code>cat file1.txt

1,2,3

cat file2.txt

a,b,c
</code>```

& the desired output is as below,

```<code>a,1,b,2,c,3
</code>```

Can anyone please help to achieve this?

Till now i have tried this,

```<code>paste -d "," file1.txt file2.txt|cut -d , -f4,1,5,2,6,3
</code>```

& the output came as 1,2,3,a,b,c

But using 'cut' is not the good approach i think.
Becuase here i know there are 3 values in both files, but if the values are more, above command will not be helpful.

答:
try:

```<code>awk -F, 'FNR==NR{for(i=1;i<=NF;i++){a[FNR,i]=$i};next} {printf("%s,%s",a[FNR,1],$1);for(i=2;i<=NF;i++){printf(",%s,%s",a[FNR,i],$i)};print ""}' file2.txt  file1.txt
</code>```

OR(a NON-one liner form of solution too as follows)

```<code>awk -F, 'FNR==NR{                      ####making field separator as , then putting FNR==NR condition will be TRUE when first file named file1.txt will be read by awk.
        for(i=1;i<=NF;i++){            ####Starting a for loop here which will run till the total number of fields value from i=1.
        a[FNR,i]=$i                    ####creating an array with name a whose index is FNR,i and whose value is $i(fields value).
                          };
        next                           ####next will skip all further statements, so that second file named file2.txt will NOT read until file1.txt is completed.
                }
                {
        printf("%s,%s",a[FNR,1],$1);   ####printing the value of a very first element of each lines first field here with current files first field.
        for(i=2;i<=NF;i++){            ####starting a for loop here till the value of NF(number of fields).
        printf(",%s,%s",a[FNR,i],$i)   ####printing the values of array a value whose index is FNR and variable i and printing the $i value too here.
                          };
        print ""                       ####printing a new line here.
                }
        ' file2.txt  file1.txt         ####Mentioning the Input_files here.
</code>```

Body:
I have 2 files - file1 & file2 with contents as shown.

cat file1.txt

1,2,3

cat file2.txt

a,b,c

& the desired output is as below,

a,1,b,2,c,3

Can anyone please help to achieve this?

Till now i have tried this,

paste -d "," file1.txt file2.txt|cut -d , -f4,1,5,2,6,3

& the output came as 1,2,3,a,b,c

But using 'cut' is not the good approach i think.
Becuase here i know there are 3 values in both files, but if the values are more, above command will not be helpful.

Body:
try:

awk -F, 'FNR==NR{for(i=1;i<=NF;i++){a[FNR,i]=$i};next} {printf("%s,%s",a[FNR,1],$1);for(i=2;i<=NF;i++){printf(",%s,%s",a[FNR,i],$i)};print ""}' file2.txt  file1.txt

OR(a NON-one liner form of solution too as follows)

awk -F, 'FNR==NR{                      ####making field separator as , then putting FNR==NR condition will be TRUE when first file named file1.txt will be read by awk.
        for(i=1;i<=NF;i++){            ####Starting a for loop here which will run till the total number of fields value from i=1.
        a[FNR,i]=$i                    ####creating an array with name a whose index is FNR,i and whose value is $i(fields value).
                          };
        next                           ####next will skip all further statements, so that second file named file2.txt will NOT read until file1.txt is completed.
                }
                {
        printf("%s,%s",a[FNR,1],$1);   ####printing the value of a very first element of each lines first field here with current files first field.
        for(i=2;i<=NF;i++){            ####starting a for loop here till the value of NF(number of fields).
        printf(",%s,%s",a[FNR,i],$i)   ####printing the values of array a value whose index is FNR and variable i and printing the $i value too here.
                          };
        print ""                       ####printing a new line here.
                }
        ' file2.txt  file1.txt         ####Mentioning the Input_files here.