问:
how to repeat characters in a string
I'm trying to link two tables, one has an 'EntityRef' that's made of four alpha characters and a sequential number...

```<code>EntityRef
=========
SWIT1
LIVE32
KIRB48
MEHM38
BRAD192
</code>```

The table that I'm trying to link to stores the reference in a 15 character field where the 4 alphas are at the start and the numbers are at the end but with zeros in between to make up the 15 characters...

```<code>EntityRef
=========
SWIT00000000001
LIVE00000000032
</code>```

So, to get theses to link, my options are to either remove the zeros on one field or add the zeros on the other.

I've gone for the later as it seems to be a simpler approach and eliminates the risk of getting into problems if the numeric element contains a zero.

So, the alpha is always 4 characters at the beginning and the number is the remainder and 15 minus the LEN() of the EntityRef is the number of zeros that I need to insert...

```<code>left(entityref,4) as 'Alpha',
right(entityref,len(EntityRef)-4) as 'Numeric',
15-len(EntityRef) as 'No.of Zeros'

Alpha   Numeric No.of Zeros
=====   ======= ===========
SWIT    1       10
LIVE    32      9
KIRB    48      9
MEHM    38      9
MALL    36      9
</code>```

So, I need to concatenate the three elements but I don't know how to create the string of zeros to the specified length...how do I do that??

```<code>Concat(Alpha, '0'*[No. of Zeros], Numeric)
</code>```

What is the correct way to repeat a character a specified number of times?

答:
You may try left padding with zeroes:

```<code>SELECT
    LEFT(EntityRef, 4) +
    RIGHT('00000000000' + SUBSTRING(ISNULL(EntityRef,''), 5, 30), 11) AS EntityRef
FROM yourTable;
</code>```

Demo

Title: how to repeat characters in a string

Body:
I'm trying to link two tables, one has an 'EntityRef' that's made of four alpha characters and a sequential number...

EntityRef
=========
SWIT1
LIVE32
KIRB48
MEHM38
BRAD192

The table that I'm trying to link to stores the reference in a 15 character field where the 4 alphas are at the start and the numbers are at the end but with zeros in between to make up the 15 characters...

EntityRef
=========
SWIT00000000001
LIVE00000000032

So, to get theses to link, my options are to either remove the zeros on one field or add the zeros on the other.

I've gone for the later as it seems to be a simpler approach and eliminates the risk of getting into problems if the numeric element contains a zero.

So, the alpha is always 4 characters at the beginning and the number is the remainder and 15 minus the LEN() of the EntityRef is the number of zeros that I need to insert...

left(entityref,4) as 'Alpha',
right(entityref,len(EntityRef)-4) as 'Numeric',
15-len(EntityRef) as 'No.of Zeros'

Alpha   Numeric No.of Zeros
=====   ======= ===========
SWIT    1       10
LIVE    32      9
KIRB    48      9
MEHM    38      9
MALL    36      9

So, I need to concatenate the three elements but I don't know how to create the string of zeros to the specified length...how do I do that??

Concat(Alpha, '0'*[No. of Zeros], Numeric)

What is the correct way to repeat a character a specified number of times?

Body:
You may try left padding with zeroes:

SELECT
    LEFT(EntityRef, 4) +
    RIGHT('00000000000' + SUBSTRING(ISNULL(EntityRef,''), 5, 30), 11) AS EntityRef
FROM yourTable;

Demo


来源: stackexchange

问:
How to crop a numpy 2d array to non-zero values?
Let's say i have a 2d boolean numpy array like this:

```<code>import numpy as np
a = np.array([
    [0,0,0,0,0,0],
    [0,1,0,1,0,0],
    [0,1,1,0,0,0],
    [0,0,0,0,0,0],
], dtype=bool)
</code>```

How can i in general crop it to the smallest box (rectangle, kernel) that includes all True values?

So in the example above:

```<code>b = np.array([
    [1,0,1],
    [1,1,0],
], dtype=bool)
</code>```

答:
```<code>a = np.transpose(a[np.sum(a,1) != 0])
a = np.transpose(a[np.sum(a,1) != 0])
</code>```

It's not the quickest but it's alright.

ContentLicense: CC BY-SA 3.0

Body:
Let's say i have a 2d boolean numpy array like this:

import numpy as np
a = np.array([
    [0,0,0,0,0,0],
    [0,1,0,1,0,0],
    [0,1,1,0,0,0],
    [0,0,0,0,0,0],
], dtype=bool)

How can i in general crop it to the smallest box (rectangle, kernel) that includes all True values?

So in the example above:

b = np.array([
    [1,0,1],
    [1,1,0],
], dtype=bool)

Body:
a = np.transpose(a[np.sum(a,1) != 0])
a = np.transpose(a[np.sum(a,1) != 0])

It's not the quickest but it's alright.

ContentLicense: CC BY-SA 4.0


问:
Your bundle is locked to ffi (1.11.0), but that version could not be found in any of the sources listed in your Gemfile
I get this error when starting the rails server:
I've tried gem install, gem update, bundle update, bundle install.

```<code>Your bundle is locked to ffi (1.11.0), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of ffi
(1.11.0) has removed it. You'll need to update your bundle to a version other than ffi (1.11.0) that hasn't been removed in order to install.
</code>```

can you help? thank you!

```<code>source 'https://rubygems.org'
ruby '2.5.3'

gem 'bootsnap', require: false
gem 'jbuilder', '~> 2.0'
gem 'pg', '~> 0.21'
gem 'puma'
gem 'shopify_app'
gem 'rails', '5.2.3'
gem 'redis'
gem 'devise'

gem 'autoprefixer-rails'
gem 'font-awesome-sass', '~> 5.6.1'
gem 'sassc-rails'
gem 'simple_form'
gem 'uglifier'
gem 'webpacker'

group :development do
  gem 'web-console', '>= 3.3.0'
end

group :development, :test do
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'dotenv-rails'

end

</code>```

this is my rake file:

```<code>require_relative 'config/application'

Rails.application.load_tasks

</code>```

答: Delete the bundler version mentioned in your Gemfile.lock</p>

Body:
I get this error when starting the rails server:
I've tried gem install, gem update, bundle update, bundle install.

Your bundle is locked to ffi (1.11.0), but that version could not be found in any of the sources listed in your Gemfile. If you haven't changed sources, that means the author of ffi
(1.11.0) has removed it. You'll need to update your bundle to a version other than ffi (1.11.0) that hasn't been removed in order to install.

can you help? thank you!

source 'https://rubygems.org'
ruby '2.5.3'

gem 'bootsnap', require: false
gem 'jbuilder', '~> 2.0'
gem 'pg', '~> 0.21'
gem 'puma'
gem 'shopify_app'
gem 'rails', '5.2.3'
gem 'redis'
gem 'devise'

gem 'autoprefixer-rails'
gem 'font-awesome-sass', '~> 5.6.1'
gem 'sassc-rails'
gem 'simple_form'
gem 'uglifier'
gem 'webpacker'

group :development do
  gem 'web-console', '>= 3.3.0'
end

group :development, :test do
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'dotenv-rails'

end

this is my rake file:

require_relative 'config/application'

Rails.application.load_tasks


问:
Solr Boost-Function on Sales
I am using Apache Solr 8 with products as documents. Each document includes sales within the last X days that I want to boost, as well as a title and other fields.

Say productA has been sold 5 times, I want to boost it with score+10; a productB has been sold 50 times, I want to boost the score by 30.

I tried to use a boostFunction that looks like (edismax query parser)

```<code>q=Coffee&qf=title&bf=if(lt(sales,5),10,if(lt(sales,50),30))
</code>```

Solr now returns documents that have nothing to do with my "Coffee"-Query but just match the boostfunction. There are even results with score "0".
E.g.

```<code>Rank;Score;Sales;Title
1;58.53;55;Coffee big
2;38.11;50;Coffee
3;30;55;Tea
</code>```

Any idea to get rid of those "only boost function"-matches?

答:
Found the answer!

My Query-Fields actually included boostings like

```<code>&qf=title^2 longDescription^0 whatever^0...
</code>```

Instead of excluding the results found in those 0-boosted fields, solr adds them and matches with - well score 0.

When I remove the 0-boostings, everything works as intended.

Title: Solr Boost-Function on Sales

Body:
I am using Apache Solr 8 with products as documents. Each document includes sales within the last X days that I want to boost, as well as a title and other fields.

Say productA has been sold 5 times, I want to boost it with score+10; a productB has been sold 50 times, I want to boost the score by 30.

I tried to use a boostFunction that looks like (edismax query parser)

q=Coffee&qf=title&bf=if(lt(sales,5),10,if(lt(sales,50),30))

Solr now returns documents that have nothing to do with my "Coffee"-Query but just match the boostfunction. There are even results with score "0".
E.g.

Rank;Score;Sales;Title
1;58.53;55;Coffee big
2;38.11;50;Coffee
3;30;55;Tea

Any idea to get rid of those "only boost function"-matches?

Body:
Found the answer!

My Query-Fields actually included boostings like

&qf=title^2 longDescription^0 whatever^0...

Instead of excluding the results found in those 0-boosted fields, solr adds them and matches with - well score 0.

When I remove the 0-boostings, everything works as intended.


问:
No advertisement is shown from Admob
I had an Google Admob account which was banned by any reason (for 30 days, and I've no goddamn idea why) probably for "watching" the interstitial which I cannot avoid.

I then had to create a new account on AdMob because I do not have the time to wait 30 days for this.

I also have my iOS application linked to Firebase (On my old gmail account) which is linked to my banned AdMob account.

I replaced my key in info.plist and googleService-info.plist
I changed the app unit ID.

```<code>        interstitial = GADInterstitial(adUnitID: "ca-app-pub-MY-ID-is-here")
        let request = GADRequest()

        request.testDevices = [ kGADSimulatorID]
        interstitial.load(request)
        interstitial.delegate = self

</code>```

```<code>                                    if self.interstitial.isReady
                                    {
                                        self.interstitial.present(fromRootViewController: self)
                                    }
                                    else
                                    {
                                        print("Advertisement is not ready!")

                                        self.performSegue(withIdentifier: "History", sender: self)
                                    }
</code>```

No ads is being displayed on the application, but why? Is it impossible to add advertisement to this right now? Even thought I changed my account?

The new account is NOT linked to the Firebase, does that matter?

I expect advertisement to show up but it doesnt.

答:
I had faced the same situation but the ads started coming once I linked my app store application link to the ad mob account.

Make sure you have configured correct AdmobId in the App delegate and adUnitID in the controller correctly.

Singin to AdMob account and navigate to the app setting and find 'App name & store link'. You can link your app link from there.

Title: No advertisement is shown from Admob

Body:
I had an Google Admob account which was banned by any reason (for 30 days, and I've no goddamn idea why) probably for "watching" the interstitial which I cannot avoid.

I then had to create a new account on AdMob because I do not have the time to wait 30 days for this.

I also have my iOS application linked to Firebase (On my old gmail account) which is linked to my banned AdMob account.

I replaced my key in info.plist and googleService-info.plist
I changed the app unit ID.

        interstitial = GADInterstitial(adUnitID: "ca-app-pub-MY-ID-is-here")
        let request = GADRequest()

        request.testDevices = [ kGADSimulatorID]
        interstitial.load(request)
        interstitial.delegate = self

                                    if self.interstitial.isReady
                                    {
                                        self.interstitial.present(fromRootViewController: self)
                                    }
                                    else
                                    {
                                        print("Advertisement is not ready!")

                                        self.performSegue(withIdentifier: "History", sender: self)
                                    }

No ads is being displayed on the application, but why? Is it impossible to add advertisement to this right now? Even thought I changed my account?

The new account is NOT linked to the Firebase, does that matter?

I expect advertisement to show up but it doesnt.


问:
How to toggle mat-sidenav in another component?
I want to toggle side-nav(in the drawer component)by clicking menu icon (in the header component). I've tried using service; but the service state didn't share between these two components.

The demo is here https://stackblitz.com/edit/angular-11pdkj

答:
Angular provides very powerful concept of Input, Output.
Please consider to use Input, Output and EventEmitter
with this all you can bounce event from one component to another component.

Please have a look on this demo link.

```<code>// drawer.component.ts
export class DrawerComponent implements AfterViewInit, OnChanges {
  @ViewChild('sidenav') public sidenav: MatSidenav;

  @Input()
  openNav: boolean;

  ngOnChanges(): void {
    console.log('ngOnChanges', this.openNav);
    if (this.openNav) {
      this.sidenav.open();
    } else {
      this.sidenav.close();
    }
  }
}

// header.component.ts
export class HeaderComponent implements OnInit {
  title: string = "Dashboard";

  @Output()
  open: EventEmitter<boolean> = new EventEmitter();

  clickMenu() {
    this.open.emit(true);
  }
}

// layouts.component.html
<div class="app-wrapper">
  <app-drawer [openNav]="isOpen"></app-drawer>
  <app-header (open)="navOpen($event)"></app-header>
<div>

// layouts.component.ts
export class LayoutsComponent implements OnInit {

  isOpen: boolean;
  navOpen($event): void {
    this.isOpen = !this.isOpen;
    console.log('navOpen', $event);
  }
}
</code>```

also use respective component lifecycle hooks whenever required.

Body:
Angular provides very powerful concept of Input, Output.
Please consider to use Input, Output and EventEmitter
with this all you can bounce event from one component to another component.

Please have a look on this demo link.

// drawer.component.ts
export class DrawerComponent implements AfterViewInit, OnChanges {
  @ViewChild('sidenav') public sidenav: MatSidenav;

  @Input()
  openNav: boolean;

  ngOnChanges(): void {
    console.log('ngOnChanges', this.openNav);
    if (this.openNav) {
      this.sidenav.open();
    } else {
      this.sidenav.close();
    }
  }
}

// header.component.ts
export class HeaderComponent implements OnInit {
  title: string = "Dashboard";

  @Output()
  open: EventEmitter<boolean> = new EventEmitter();

  clickMenu() {
    this.open.emit(true);
  }
}

// layouts.component.html
<div class="app-wrapper">
  <app-drawer [openNav]="isOpen"></app-drawer>
  <app-header (open)="navOpen($event)"></app-header>
<div>

// layouts.component.ts
export class LayoutsComponent implements OnInit {

  isOpen: boolean;
  navOpen($event): void {
    this.isOpen = !this.isOpen;
    console.log('navOpen', $event);
  }
}

also use respective component lifecycle hooks whenever required.


问:
IE8 CSS Hack - best method?
Can anyone recommend the best way to hack IE8 styling via CSS, I've recently been making IE8 render as IE7 for ease -  but wondered if it was best to add IE8 hacks?</p>

答:
Can you explain a bit more what you want?

Generally, IE8 is quite standards compatible, so just make sure your HTML document is in standards mode and give IE8 the same stylesheet as any other browser.

If IE is acting up, then the best solution is to use Conditional Comments to give IE a separate stylesheet.

Title: IE8 CSS Hack - best method?


问:
set option label of selected value in React
Using React I want to set a defaulvalue for my select and diplay the label in the options.
This is what I've built so far :

```<code><Select showSearch style = {{ width: '100%' }}
                   placeholder = "Selection la choix de votre numÃ©ro de tÃ©lÃ©phone "
                   optionFilterProp = "children"
                   onChange = {handleChangeSelect}

                   defaultValue = {extraitMP3[ids].Mp3[idJson].visibilite}
                   onFocus = {handleFocusSelect}
                   onBlur = {handleBlurSelect}
                   filterOption = {(input, Option) => Option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>

    <Option value = "1"> Visible dans la recherche et sur ma fiche </Option>
    <Option value = "2"> Visible sur ma fiche uniquement </Option>
    <Option value = "3"> Masqué </Option>
</Select>
</code>```

The result now is showing {extraitMP3[ids].Mp3[idJson].visibilite} which is equal to one of the option values but what I want to display is the option labels. Any help to change what to display from values to their labels in the defaulValue

答:
You could store the options in a Map, and then look up the text for the option:

Somewhere in your component's module but not in the component itself (no need to recreate it all the time):

```<code>const selectOptions = new Map([
    ["1", "Visible dans la recherche et sur ma fiche"],
    ["2", "Visible sur ma fiche uniquement"],
    ["3", "Masqué"],
]);
</code>```

Then when rendering, look it up:

```<code>defaultValue={selectOptions.get(extraitMP3[ids].Mp3[idJson].visibilite)}
</code>```

also, use the map for rendering the options. So the rendering code would look something like:

```<code><Select
            showSearch
            style={{ width: '100%' }}
            placeholder="Selection la choix de votre numÃ©ro de tÃ©lÃ©phone "
            optionFilterProp="children"
            onChange={handleChangeSelect}

            defaultValue={selectOptions.get(extraitMP3[ids].Mp3[idJson].visibilite)}
            onFocus={handleFocusSelect}
            onBlur={handleBlurSelect}
            filterOption={(input, Option) => Option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
          {[...selectOptions].map(([value, label]) => <Option value="{value}"> {label} </Option>)}
</Select>
</code>```

Body:
Using React I want to set a defaulvalue for my select and diplay the label in the options.
This is what I've built so far :

<Select showSearch style = {{ width: '100%' }}
                   placeholder = "Selection la choix de votre numÃ©ro de tÃ©lÃ©phone "
                   optionFilterProp = "children"
                   onChange = {handleChangeSelect}

                   defaultValue = {extraitMP3[ids].Mp3[idJson].visibilite}
                   onFocus = {handleFocusSelect}
                   onBlur = {handleBlurSelect}
                   filterOption = {(input, Option) => Option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>

    <Option value = "1"> Visible dans la recherche et sur ma fiche </Option>
    <Option value = "2"> Visible sur ma fiche uniquement </Option>
    <Option value = "3"> Masqué </Option>
</Select>

The result now is showing {extraitMP3[ids].Mp3[idJson].visibilite} which is equal to one of the option values but what I want to display is the option labels. Any help to change what to display from values to their labels in the defaulValue

Body:
You could store the options in a Map, and then look up the text for the option:

Somewhere in your component's module but not in the component itself (no need to recreate it all the time):

const selectOptions = new Map([
    ["1", "Visible dans la recherche et sur ma fiche"],
    ["2", "Visible sur ma fiche uniquement"],
    ["3", "Masqué"],
]);

Then when rendering, look it up:

defaultValue={selectOptions.get(extraitMP3[ids].Mp3[idJson].visibilite)}

also, use the map for rendering the options. So the rendering code would look something like:

<Select
            showSearch
            style={{ width: '100%' }}
            placeholder="Selection la choix de votre numÃ©ro de tÃ©lÃ©phone "
            optionFilterProp="children"
            onChange={handleChangeSelect}

            defaultValue={selectOptions.get(extraitMP3[ids].Mp3[idJson].visibilite)}
            onFocus={handleFocusSelect}
            onBlur={handleBlurSelect}
            filterOption={(input, Option) => Option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
          >
          {[...selectOptions].map(([value, label]) => <Option value="{value}"> {label} </Option>)}
</Select>


问:
"initialize" class method for classes in Swift?
I'm looking for behavior similar to Objective-C's +(void)initialize class method, in that the method is called once when the class is initialized, and never again thereafter.

A simple class init () {} in a class closure would be really sleek! And obviously when we get to use "class vars" instead of "static vars in a struct closure", this will all match really well!

答:
You can use stored type properties instead of initialize method.

```<code>class SomeClass: {
  private static let initializer: Void = {
    //some initialization
  }()
}
</code>```

But since stored types properties are actually lazily initialized on their first access, you will need refer them somewhere. You can do this with ordinary stored property:

```<code>class SomeClass: {
  private static let initializer: Void = {
    //some initialization
  }()
  private let initializer: Void = SomeClass.initializer
}
</code>```

Body:
You can use stored type properties instead of initialize method.

class SomeClass: {
  private static let initializer: Void = {
    //some initialization
  }()
}

But since stored types properties are actually lazily initialized on their first access, you will need refer them somewhere. You can do this with ordinary stored property:

class SomeClass: {
  private static let initializer: Void = {
    //some initialization
  }()
  private let initializer: Void = SomeClass.initializer
}


问:
rxjs observable.pipe(take(1)) vs toPromise
Recently I've been moved to a new project which uses angular 6 as frontend framework and spring for REST services.

The project is in development for 2 years now and what I've observed was that almost all HTTP request made with angular HttpClient is then piped to take filter from rxjs. All REST APIs emit only one value. There's no need for manual cancellation and the laziness property of observables.

My intuition is that using toPromise() would be a better way to code.

What are your thoughts?

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() {
     return http.get('/customers');
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().pipe(take(1)).subscribe((customers) => {
           //do some stuff
      })
  }
```

<p>My proposed approach:</p>

<pre class="lang-js prettyprint-override"><code>  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() : Promise<Array<Customer>> {
     return http.get('/customers').toPromise();
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().then((customers: Array<Customer>) => {
         //do some stuff
      })
  }
</code>```

I think that my approach is better because it is strongly typed and it's cleaner.

答:
As you mentioned strongly typed we can do the same in observable approach.

```<code>
public getCustomers():Observable<Array<Customer>>  {
     return http.get<Array<Customer>>('/customers');
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers()
      .pipe(take(1))
      .subscribe((customers: Array<Customer>) => {
       //do some stuff
       });
  }

</code>```

For HttpRequest with single HttpResponse you may rely on promise
approach.

But HttpRequest with multiple response such as progress/stream of
data(blob) go for the Observable approach.

Try to use Observable as much as possible, once you familiar with you wont go for other options. So Give it a try!

Body:
Recently I've been moved to a new project which uses angular 6 as frontend framework and spring for REST services.

The project is in development for 2 years now and what I've observed was that almost all HTTP request made with angular HttpClient is then piped to take filter from rxjs. All REST APIs emit only one value. There's no need for manual cancellation and the laziness property of observables.

My intuition is that using toPromise() would be a better way to code.

What are your thoughts?

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() {
     return http.get('/customers');
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().pipe(take(1)).subscribe((customers) => {
           //do some stuff
      })
  }

My proposed approach:

  //customer-service.ts
  constructor(private http: HttpClient) {

  }

  public getCustomers() : Promise<Array<Customer>> {
     return http.get('/customers').toPromise();
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers().then((customers: Array<Customer>) => {
         //do some stuff
      })
  }

I think that my approach is better because it is strongly typed and it's cleaner.

Body:
As you mentioned strongly typed we can do the same in observable approach.

public getCustomers():Observable<Array<Customer>>  {
     return http.get<Array<Customer>>('/customers');
  }

  //component.ts
  public ngOnInit() {
      this.customerService.getCustomers()
      .pipe(take(1))
      .subscribe((customers: Array<Customer>) => {
       //do some stuff
       });
  }

For HttpRequest with single HttpResponse you may rely on promise
approach.

But HttpRequest with multiple response such as progress/stream of
data(blob) go for the Observable approach.

Try to use Observable as much as possible, once you familiar with you wont go for other options. So Give it a try!


问:
Why does the first parameter of the function LdrRegisterDllNotification have to be zero?
As stated in the Microsoft docs, the parameter Flags of the LdrRegisterDllNotification must be zero, but no further explanation is provided. What's the purpose of defining this parameter at all if the only accepted value is zero? What happens if a non-zero value is passed instead?

答:
Parameters where the documentation tells you to pass zero has two possible reasons:

The parameter is unused in all existing Windows versions but might be used for something in the future. The developer might have envisioned extra features but they did not have time to implement them etc.

The parameter is used to pass undocumented information/flags that triggers some private functionality inside the function. Windows 95 for example supports undocumented flags in its *Alloc functions that causes them to allocate shared memory visible to all processes.

Either way, the best practice is to just follow the documentation and pass zero.


问:
Receive input from command line with Spring Boot
So I have a really small Spring Boot command line application (There is no embedded tomcat server or anything that would make it a web application) with a single class where I try to use the Scanner class from java.util to read input from the user. This does not work at all. I thought it would be pretty basic stuff in Spring Boot, but all of my searches both on S.O or tutorials have yielded no results. What's the best way to go about it? or is Spring Boot just not for what I want to do?

Here's my class:

```<code>package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Scanner;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
        .getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("EXECUTING : command line runner");

        Scanner in = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = in.next();
        System.out.println("Hello " + name + " welcome to spring boot" );
    }
}
</code>```

The exception being thrown is:

```<code>2019-05-29 11:31:29.116  INFO 4321 --- [           main] test.MyApplication  : EXECUTING : command line runner
2019-05-29 11:31:29.119  INFO 4321 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-29 11:31:29.124 ERROR 4321 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at com.jaletechs.png.PrimeNumberGeneratorApplication.main(MyApplication.java:19) [main/:na]
Caused by: java.util.NoSuchElementException: null
        at java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_201]
        at java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_201]
        at test.MyApplication.run(MyApplication.java:27) [main/:na]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        ... 3 common frames omitted
</code>```

答:
Spring boot is not designed for any kind of general purpose usages. It has specific purposes. We should not always think about how to use Spring Boot for any kind of requirements. I know Spring Boot has become very popular. To your question, if you want to create an interactive application/program, you have to do in a simple manner. I just provide below the code snippet.

```<code>public class Interactive
{

  public static void main (String[] args)
  {
    // create a scanner so we can read the command-line input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter your name ? ");
    String username = scanner.next();
    System.out.print("Enter your age ? ");
    int age = scanner.nextInt();

    //Print all name, age etc
  }

}
</code>```

Hope this may be your requirement. Again Spring Boot application can not be stated as interactive in true sense. Many interpretations are there. Spring Boot is suitable for client server architecture.

Body:
So I have a really small Spring Boot command line application (There is no embedded tomcat server or anything that would make it a web application) with a single class where I try to use the Scanner class from java.util to read input from the user. This does not work at all. I thought it would be pretty basic stuff in Spring Boot, but all of my searches both on S.O or tutorials have yielded no results. What's the best way to go about it? or is Spring Boot just not for what I want to do?

Here's my class:

package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.Scanner;

@SpringBootApplication
public class MyApplication implements CommandLineRunner {

    private static Logger LOG = LoggerFactory
        .getLogger(MyApplication.class);

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(MyApplication.class);
        app.run(args);
    }

    @Override
    public void run(String... args) throws Exception {
        LOG.info("EXECUTING : command line runner");

        Scanner in = new Scanner(System.in);

        System.out.println("What is your name?");
        String name = in.next();
        System.out.println("Hello " + name + " welcome to spring boot" );
    }
}

The exception being thrown is:

2019-05-29 11:31:29.116  INFO 4321 --- [           main] test.MyApplication  : EXECUTING : command line runner
2019-05-29 11:31:29.119  INFO 4321 --- [           main] ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-05-29 11:31:29.124 ERROR 4321 --- [           main] o.s.boot.SpringApplication               : Application run failed

java.lang.IllegalStateException: Failed to execute CommandLineRunner
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:816) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:797) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at org.springframework.boot.SpringApplication.run(SpringApplication.java:324) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        at com.jaletechs.png.PrimeNumberGeneratorApplication.main(MyApplication.java:19) [main/:na]
Caused by: java.util.NoSuchElementException: null
        at java.util.Scanner.throwFor(Scanner.java:862) ~[na:1.8.0_201]
        at java.util.Scanner.next(Scanner.java:1371) ~[na:1.8.0_201]
        at test.MyApplication.run(MyApplication.java:27) [main/:na]
        at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813) ~[spring-boot-2.1.5.RELEASE.jar:2.1.5.RELEASE]
        ... 3 common frames omitted

Body:
Spring boot is not designed for any kind of general purpose usages. It has specific purposes. We should not always think about how to use Spring Boot for any kind of requirements. I know Spring Boot has become very popular. To your question, if you want to create an interactive application/program, you have to do in a simple manner. I just provide below the code snippet.

public class Interactive
{

  public static void main (String[] args)
  {
    // create a scanner so we can read the command-line input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter your name ? ");
    String username = scanner.next();
    System.out.print("Enter your age ? ");
    int age = scanner.nextInt();

    //Print all name, age etc
  }

}

Hope this may be your requirement. Again Spring Boot application can not be stated as interactive in true sense. Many interpretations are there. Spring Boot is suitable for client server architecture.


问:
Speed of NSArray#count
If I do

```<code>[myArray count]
</code>```

is it O(1) or O(n), where n is the number of elements in the array?

答: If it is not O(1) then you should find another array implementation :)</p>

Title: Speed of NSArray#count

Body:
If I do

[myArray count]

is it O(1) or O(n), where n is the number of elements in the array?


问:
Use "perl6" command with Git Bash on windows
Using Windows, I installed Rakudo Star and Git and ensured that C:\rakudo\bin and C:\rakudo\share\perl6\site\bin are in my Path environment variable.

Now, typing perl6 inside Git Bash afterwards gives the command not found error, while the command does work inside powershell and cmd. Typing echo $PATH inside Git Bash confirms again that the folders above are in my path variable here as well.

How can I get the perl6 command working inside Git Bash?

Note: Using moar (moar.exe) which resides in the same folder as perl6 works as well in Git Bash. Also hitting Tab show the autocomplete suggestion for moar, it does not do that for perl6.

答:
Bash doesn't run Windows batch files, so you'll have to work around that.

An easy solution might be to add something like this you your .bashrc:

```<code>alias perl6='cmd /c perl6.bat'
</code>```

Alternatively, you can convert perl6.bat to a shell script and put it somewhere in your $PATH.
I use the following:

```<code>#!/bin/sh

PATH=/cygdrive/c/rakudo/bin:/cygdrive/c/rakudo/share/perl6/site/bin:$PATH
unset HOME

moar --execname="$0" \
     --libpath='C:\rakudo\share\nqp\lib' \
     --libpath='C:\rakudo\share\perl6\lib' \
     --libpath='C:\rakudo\share\perl6\runtime' \
     'C:\rakudo\share\perl6\runtime\perl6.moarvm' \
     "$@"
</code>```

This is using Cygwin; you may need to adapt it a bit for Git bash (I don't know, no experience with it).

Alternatively, if you're using Windows 10, I can recommend installing WSL, and using perl6 in a WSL bash prompt instead.  This runs much smoother for me than the Windows version under Cygwin.

Body:
Bash doesn't run Windows batch files, so you'll have to work around that.

An easy solution might be to add something like this you your .bashrc:

alias perl6='cmd /c perl6.bat'

Alternatively, you can convert perl6.bat to a shell script and put it somewhere in your $PATH.
I use the following:

#!/bin/sh

PATH=/cygdrive/c/rakudo/bin:/cygdrive/c/rakudo/share/perl6/site/bin:$PATH
unset HOME

moar --execname="$0" \
     --libpath='C:\rakudo\share\nqp\lib' \
     --libpath='C:\rakudo\share\perl6\lib' \
     --libpath='C:\rakudo\share\perl6\runtime' \
     'C:\rakudo\share\perl6\runtime\perl6.moarvm' \
     "$@"

This is using Cygwin; you may need to adapt it a bit for Git bash (I don't know, no experience with it).

Alternatively, if you're using Windows 10, I can recommend installing WSL, and using perl6 in a WSL bash prompt instead.  This runs much smoother for me than the Windows version under Cygwin.


问:
Issues with POST and PUT in table with comma separated numeric values
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

```<code>DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);
</code>```

It has a corresponding Model, which looks like this

```<code>public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}
</code>```

I am trying to insert numeric values into coordinate like so:

```<code>sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();
</code>```

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'
</code>```

And my backend throws the following error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}
</code>```

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

```<code>sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();
</code>```

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

```<code>sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"
</code>```

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

```<code>{
 "Message": "An error has occurred.",
 "ExceptionMessage": "You have an error in your SQL syntax; check the manual
 that corresponds to your MySQL server version for the right syntax to use
 near '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}
</code>```

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.

答:
Maybe give the following a go. I think the issue is that you need to use a '.' instead of a ',' to make decimal values clear to SQL. Bear in mind that when you try to return the longitude/latitude, it'll be returned as a string.

I haven't tested this but give it a try.

```<code>using System.Globalization;
public class Coordinate
{
    NumberFormatInfo nfi = new NumberFormatInfo();

    public Coordinate()
    {
        nfi.NumberDecimalSeparator = ".";
    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    public string GetLatitudeComma()
    {
        return this.Latitude.ToString(nfi);
    }

    public string GetLongitudeComma()
    {
        return this.Longitude.ToString(nfi);
    }
}
</code>```

And...

```<code>sql = "UPDATE coordinate SET longitude = '" + coordinate.GetLongitudeComma() + "," + " latitude = " + coordinate.GetLatitudeComma()+ "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();
</code>```

Body:
I am running into issues with POST and PUT for my backend. The relevant table structure can be seen here

DROP TABLE IF EXISTS coordinate;
CREATE TABLE coordinate
(
   id                    int(10) NOT NULL auto_increment,
   longitude             double(8,4) NOT NULL,
   latitude              double(8,4) NOT NULL,
   measurementId         int(10) default NULL,
   PRIMARY KEY (id),
   FOREIGN KEY (measurementId)
        REFERENCES measurement (id)
        ON DELETE CASCADE
);

It has a corresponding Model, which looks like this

public class Coordinate
{
    public Coordinate()
    {

    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    ...
}

I am trying to insert numeric values into coordinate like so:

sql = "UPDATE coordinate SET longitude = '" + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();

Notice the inclusion of the single bracket before the double bracket after longitude = '" and + "' WHERE ...

When I run this with a debugger the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude = '55,6, latitude = 70,33, measurementId = 2' WHERE id = 2'

And my backend throws the following error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "Data truncated for column 'longitude' at row 1",
 "ExceptionType": "MySql.Data.MySqlClient.MySqlException",
 ...
}

My hunch is that the sql string is not constructed properly because of the inclusion of the single bracket, so I remove it like and construct a new sql string like so:

sql = "UPDATE coordinate SET longitude = " + coordinate.Longitude + "," + " latitude = " + coordinate.Latitude + "," + " measurementId = " + coordinate.MeasurementId + " WHERE id = " + id.ToString();

Notice the removal of the single bracket ' in the places it was present before. Now, in the debugger, the string sql is constructed like so:

sql = "UPDATE coordinate SET longitude 55,6 latitude = 70,33, measurementId = 2 WHERE id = 2"

It's my impression that the numeric values should be separated by a . and not a ,, which could by why the backend now throws this error:

{
 "Message": "An error has occurred.",
 "ExceptionMessage": "You have an error in your SQL syntax; check the manual
 that corresponds to your MySQL server version for the right syntax to use
 near '6, latitude = 70,33, measurementId = 2 WHERE id = 2' at line 1",
}

I am a bit at a loss on how to then handle the insertion of numeric values in my database. Any help is much appreciated.

Body:
Maybe give the following a go. I think the issue is that you need to use a '.' instead of a ',' to make decimal values clear to SQL. Bear in mind that when you try to return the longitude/latitude, it'll be returned as a string.

I haven't tested this but give it a try.

using System.Globalization;
public class Coordinate
{
    NumberFormatInfo nfi = new NumberFormatInfo();

    public Coordinate()
    {
        nfi.NumberDecimalSeparator = ".";
    }

    public int ID { get; set; }

    public double Latitude { get; set; }

    public double Longitude { get; set; }

    public int MeasurementId { get; set; }

    public string GetLatitudeComma()
    {
        return this.Latitude.ToString(nfi);
    }

    public string GetLongitudeComma()
    {
        return this.Longitude.ToString(nfi);
    }
}

And...

sql = "UPDATE coordinate SET longitude = '" + coordinate.GetLongitudeComma() + "," + " latitude = " + coordinate.GetLatitudeComma()+ "," + " measurementId = " + coordinate.MeasurementId + "' WHERE id = " + id.ToString();


问:
Programmaticaly define size of SQL columns
I am working on an ETL job in Azure Databricks. When I am writing to an Azure DB, the nvarchar columns are created as nvarchar(max).

I am doing the following to write the dataframe to SQL:

```<code>df.write \
    .format("jdbc") \
    .option("url", _get_dw_jdbc_url()) \
    .option("forwardSparkAzureStorageCredentials", "true") \
    .option("dbTable", table_name) \
    .option("tempDir", _get_temp_connection_string()) \
    .option("maxStrLength", 255)\
    .mode(mode) \
    .save()
</code>```

I was hoping the maxStrLength would magically fix the problem, but it is not.

Any solutions on this one? Can I define the schema for the SQL table prior to writing to the database?

答:
Use pyodbc to create the table before you do the write above. This would mean your mode would have to be append (you haven't shown it in the snippet). </p>

<p>The lengths cannot be determined until the complete soruce data has been read, so Spark cannot calculate these on the fly as it starts writing (usually/ideally) before reading has finished. </p>

Body:
I am working on an ETL job in Azure Databricks. When I am writing to an Azure DB, the nvarchar columns are created as nvarchar(max).

I am doing the following to write the dataframe to SQL:

df.write \
    .format("jdbc") \
    .option("url", _get_dw_jdbc_url()) \
    .option("forwardSparkAzureStorageCredentials", "true") \
    .option("dbTable", table_name) \
    .option("tempDir", _get_temp_connection_string()) \
    .option("maxStrLength", 255)\
    .mode(mode) \
    .save()

I was hoping the maxStrLength would magically fix the problem, but it is not.

Any solutions on this one? Can I define the schema for the SQL table prior to writing to the database?

Body:
Use pyodbc to create the table before you do the write above. This would mean your mode would have to be append (you haven't shown it in the snippet).

The lengths cannot be determined until the complete soruce data has been read, so Spark cannot calculate these on the fly as it starts writing (usually/ideally) before reading has finished.


问:
Is there a .Net Statistics library with T-Tests and p-values?
Does anybody know of any good and free statistics libraries for .Net?

I am working on calculating T-Tests, which I have written a formula to calculate, although now I need a formula for the p-value, which is a little more complex, and not being a statistician, has me a little lost.

答: I suggest you look at the Math.NET project. It supports various distributions, but I don't know if it has t-tests and p-values. </p>

ContentLicense: CC BY-SA 2.5


问:
Render state in another component in reactjs
I'm trying to display current user name in a different component but It's not working, what am I doing wrong ?

Here's where I'm initialising the username (App.js)

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {
      logged_in: localStorage.getItem('token') ? true : false,
      username: ''
    };
  }
  componentDidMount() {
    if (this.state.logged_in) {
      fetch('http://localhost:8000/user/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          this.setState({ username: json.username });
          console.log(json.username);
        });

    }
  }
  render() {
  return (

      <Router history={history}>
        <Switch>
          <Route exact path="/" component={First} />
          <Route path="/home" component={Projects} />
          <Route path="/menu" component={MenuH} />
          <Route path ="/createProject" component={CreateP} />
          <Route path ="/connect" component={Newacount} />
          <Route component={Notfound} />
        </Switch>
      </Router>

  );
  }
}
...
```

<p>And here's how I'm calling it in a different component (projects)</p>

<pre class="lang-js prettyprint-override"><code>{this.state.username}
</code>```

答:
try sending state as props for child and access it from child! or to access state directly u can use redux store or context api from react!</p>

```<code><Route path="/home" render={()=><Home username={this.state.username} />} />
</code>```

Body:
I'm trying to display current user name in a different component but It's not working, what am I doing wrong ?

Here's where I'm initialising the username (App.js)

class App extends Component{
  constructor(props) {
    super(props);
    this.state = {
      logged_in: localStorage.getItem('token') ? true : false,
      username: ''
    };
  }
  componentDidMount() {
    if (this.state.logged_in) {
      fetch('http://localhost:8000/user/current_user/', {
        headers: {
          Authorization: `JWT ${localStorage.getItem('token')}`
        }
      })
        .then(res => res.json())
        .then(json => {
          this.setState({ username: json.username });
          console.log(json.username);
        });

    }
  }
  render() {
  return (

      <Router history={history}>
        <Switch>
          <Route exact path="/" component={First} />
          <Route path="/home" component={Projects} />
          <Route path="/menu" component={MenuH} />
          <Route path ="/createProject" component={CreateP} />
          <Route path ="/connect" component={Newacount} />
          <Route component={Notfound} />
        </Switch>
      </Router>

  );
  }
}
...

And here's how I'm calling it in a different component (projects)

{this.state.username}

Body:
try sending state as props for child and access it from child! or to access state directly u can use redux store or context api from react!

<Route path="/home" render={()=><Home username={this.state.username} />} />


问:
Check the owner type in `__set_name__` method introduced in python 3.6+ PEP-0487
I want to check the owner class type and allow Field class attribute to be used with Dataset class or any of its subclass. That is I want other developers to not accidentally use Field class with any other class which is not a subclass of Dataset.

It seems that Dataset is not yet completely loaded.

The print(f"Field: {name!r} of {owner!r} ...")
does show that owner class is Dataset

But then the code fails at the next statement if issubclass(owner, Dataset): as python is still not aware of class Dataset.

class Field:
    def __set_name__(self, owner, name):
        print(f"Field: {name!r} of {owner!r} ...")
        self.name = name
        if issubclass(owner, Dataset):
            raise Exception(
                f"Use the class {Field!r} only with class {Dataset!r}...."
            )

class Dataset:
    field = Field()

```

<p>Expected to run without raising any error. But instead, I get the error that </p>

```Field: 'field' of <class '__main__.Dataset'>...

NameError: name 'Dataset' is not defined
```

答:
This happens because we're still in the middle of constructing the Database class, and it's not available in the global scope yet. I hope someone comes up with a better solution, but one workaround is to have an additional base class that does nothing:

```<code>class _DatasetBase:
    pass

class Field:
    def __set_name__(self, owner, name):
        print(f"Field: {name!r} of {owner!r} ...")
        self.name = name
        if not issubclass(owner, _DatasetBase):
            raise Exception(
                f"Use the class {Field!r} only with class {Dataset!r}...."
            )

class Dataset(_DatasetBase):
    field = Field()
</code>```

Body:
I want to check the owner class type and allow Field class attribute to be used with Dataset class or any of its subclass. That is I want other developers to not accidentally use Field class with any other class which is not a subclass of Dataset.

It seems that Dataset is not yet completely loaded.

The print(f"Field: {name!r} of {owner!r} ...")
does show that owner class is Dataset

But then the code fails at the next statement if issubclass(owner, Dataset): as python is still not aware of class Dataset.

class Field:
    def __set_name__(self, owner, name):
        print(f"Field: {name!r} of {owner!r} ...")
        self.name = name
        if issubclass(owner, Dataset):
            raise Exception(
                f"Use the class {Field!r} only with class {Dataset!r}...."
            )

class Dataset:
    field = Field()

Expected to run without raising any error. But instead, I get the error that

Field: 'field' of <class '__main__.Dataset'>...

NameError: name 'Dataset' is not defined

Body:
This happens because we're still in the middle of constructing the Database class, and it's not available in the global scope yet. I hope someone comes up with a better solution, but one workaround is to have an additional base class that does nothing:

class _DatasetBase:
    pass

class Field:
    def __set_name__(self, owner, name):
        print(f"Field: {name!r} of {owner!r} ...")
        self.name = name
        if not issubclass(owner, _DatasetBase):
            raise Exception(
                f"Use the class {Field!r} only with class {Dataset!r}...."
            )

class Dataset(_DatasetBase):
    field = Field()


问:
How to submit reactive form from outside the form [submitting on click save or update buttons outside the form]
I am working on reactive forms in angular 7, and I need to call submit from a button outside the form.

```<code><input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit()" >
</form>
</code>```

This function is working fine.

Now, I need to submit the form from multiple buttons i.e.

if user click Save button, the form should be submitted and save

if user click Update button, the form should be submitted and update

For this purpose, I want to pass a flag 'Save' or 'Update' from

```<code><input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit(flag)" >
    </form>
</code>```

But I could not submit the form with the 'Save' / 'Update' flag. How could I pass a parameter from Save and Update buttons outside the form to my submit function.

Any fruitful suggestion would be highly appreciated.

答:
Try this:

HTML:

```<code><button (click)="onSubmit(detailForm.value,'save')">Submit</button>
<button (click)="onSubmit(detailForm.value,'update')">Update</button>
</code>```

TS:

```<code>onSubmit(formValue:any, type:string) {
 /// your code
}
</code>```

Body:
I am working on reactive forms in angular 7, and I need to call submit from a button outside the form.

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit()" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit()" >
</form>

This function is working fine.

Now, I need to submit the form from multiple buttons i.e.

if user click Save button, the form should be submitted and save

if user click Update button, the form should be submitted and update

For this purpose, I want to pass a flag 'Save' or 'Update' from

<input type="button" form="ngForm"  class='Button' value="Save" (click)="detailForm.ngSubmit.emit('Save')" />

<input type="button" form="ngForm"  class='Button' value="Update" (click)="detailForm.ngSubmit.emit('Update')" />

<form [formGroup]="gDetailForm" (ngSubmit)="onSubmit(flag)" >
    </form>

But I could not submit the form with the 'Save' / 'Update' flag. How could I pass a parameter from Save and Update buttons outside the form to my submit function.

Any fruitful suggestion would be highly appreciated.

Body:
Try this:

HTML:

<button (click)="onSubmit(detailForm.value,'save')">Submit</button>
<button (click)="onSubmit(detailForm.value,'update')">Update</button>

TS:

onSubmit(formValue:any, type:string) {
 /// your code
}


问:
Why css and bootstrap is not loading in Laravel 5.3?
This is my route file...

```

    Route::group(['middleware' => ['auth']], function(){

        Route::get('/profile/{username}', 'ProfileControllers@getProfile');

    });

```

The "ProfileControllers" is this...

```

    namespace App\Http\Controllers;
    use DB;
    use App\User;
    use Illuminate\Http\Request;

    class ProfileControllers extends Controller
    {
        public function getProfile($username)
        {
            $user = DB::table('users')->where('username','=', $username)->get();
            return view('web.profile');
        }
    }

```

And this is the view file...

```

    @extends('layout')

    @section('content')
        This is your profile
    @stop

```

And The head of the Layout file is this...

```

    link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"
    link rel="stylesheet" type="text/css" href="css/app.css"

```

When I go to the url "localhost:8000/profile/username" and a ugly html without any css webpage is showing....
when I remove "/{username}" from route file, and make it "/profile/username" and go to the "localhost:8000/profile/username" (and also remove the $username part form controller) , then css and bootstrap loads perfectly....

 What is happening here?

答:
You can add this line at the top of the blade file.

{{ HTML::style('css/app.css') }}

OR

link rel="stylesheet" href="{{ url('css/bootstrap.min.css') }}"

Hope it works!

Body:
This is my route file...

    Route::group(['middleware' => ['auth']], function(){

        Route::get('/profile/{username}', 'ProfileControllers@getProfile');

    });

The "ProfileControllers" is this...

    namespace App\Http\Controllers;
    use DB;
    use App\User;
    use Illuminate\Http\Request;

    class ProfileControllers extends Controller
    {
        public function getProfile($username)
        {
            $user = DB::table('users')->where('username','=', $username)->get();
            return view('web.profile');
        }
    }

And this is the view file...

    @extends('layout')

    @section('content')
        This is your profile
    @stop

And The head of the Layout file is this...

    link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"
    link rel="stylesheet" type="text/css" href="css/app.css"

When I go to the url "localhost:8000/profile/username" and a ugly html without any css webpage is showing....
when I remove "/{username}" from route file, and make it "/profile/username" and go to the "localhost:8000/profile/username" (and also remove the $username part form controller) , then css and bootstrap loads perfectly....

 What is happening here?


问:
Error with loops in javascript?
I have, in multiple parts of my code, snippits similar to this:

```<code>function updateScore() {
    var currentPoints=0;
    for (nni=0;nni<currentSession.Questions.length+1;nni++) {
        currentPoints+=currentSession.Questions[nni].Score;
    }
    alert('hi');
    document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
}
</code>```

Everything works fine... until after the loop.  This happens in multiple cases.  The alert won't even show after the loop ends.  It's like the function just stops...

I'm also having problems where the iterator (in this case, nni) stays global.  Basically, I can't use that variable ever again in my code because for some reason, if I change nni, it messes up the for loop.  I'm obvisouly not doing something right.  I'm a self tought Javascripter (basically googling anything I don't know, I've never taken a lesson).  I must be missing something about for loops.

Thanks if you can!

答:
```<code>for (var nni=0;nni<currentSession.Questions.length+1;nni++) {
    currentPoints+=currentSession.Questions[nni].Score;
}
</code>```

<p>It should be like that, you didnt declare the variable nni. Or didnt you go out of bound? </p>

```<code>nni<currentSession.Questions.length+1?
</code>```

Title: Error with loops in javascript?

Body:
I have, in multiple parts of my code, snippits similar to this:

function updateScore() {
    var currentPoints=0;
    for (nni=0;nni<currentSession.Questions.length+1;nni++) {
        currentPoints+=currentSession.Questions[nni].Score;
    }
    alert('hi');
    document.getElementById('quiz_score').innerHTML='%'+(currentPoints/currentSession.TotalPoints)*100
}

Everything works fine... until after the loop.  This happens in multiple cases.  The alert won't even show after the loop ends.  It's like the function just stops...

I'm also having problems where the iterator (in this case, nni) stays global.  Basically, I can't use that variable ever again in my code because for some reason, if I change nni, it messes up the for loop.  I'm obvisouly not doing something right.  I'm a self tought Javascripter (basically googling anything I don't know, I've never taken a lesson).  I must be missing something about for loops.

Thanks if you can!

Body:
for (var nni=0;nni<currentSession.Questions.length+1;nni++) {
    currentPoints+=currentSession.Questions[nni].Score;
}

It should be like that, you didnt declare the variable nni. Or didnt you go out of bound?

nni<currentSession.Questions.length+1?


问:
I cant retrieve what is inside my outlook with my code
I can't get the inside on my Task folder on my outlook with my code. Do you guys know any problems here?

The problem I saw is that it doesnt go in my For Loop.

```<code>Private Sub CommandButton1_Click()

Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Integer

Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Task")

i = 1

For Each OutlookMail In Folder.Items
If OutlookMail.ReceivedTime >= Range(“date_received”).Value Then
Range(“Sender”).Offset(i, 0).Value = OutlookMail.SenderName
Range(“Sender”).Offset(i, 0).Columns.AutoFit
Range(“Sender”).Offset(i, 0).VerticalAlignment = xlTop
Range(“Body”).Offset(i, 0).Value = OutlookMail.Body
Range(“Body”).Offset(i, 0).Columns.AutoFit
Range(“Body”).Offset(i, 0).VerticalAlignment = xlTop

i = i + 1
End If
Next OutlookMail

Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing

End Sub
</code>```

答:
I just changed few things on your code but it's working allright for me

```<code>Option Explicit
Private Sub CommandButton1_Click()

    Dim OutlookApp As Outlook.Application
    Dim OutlookNamespace As Namespace
    Dim Folder As MAPIFolder
    Dim OutlookMail As Variant
    Dim i As Integer

    Set OutlookApp = New Outlook.Application
    Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
    Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Bienvenidas")

    i = 2

    With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your sheet name, and ALWAYS reference sheets and workbooks.
        For Each OutlookMail In Folder.Items
            If OutlookMail.ReceivedTime >= .Range("C1") Then
                With .Cells(i, 1)
                    .Value = OutlookMail.SenderName
                    .Columns.AutoFit
                    .VerticalAlignment = xlTop
                End With
                With .Cells(i, 2)
                    .Value = OutlookMail.Body
                    .Columns.AutoFit
                    .VerticalAlignment = xlTop
                End With
                i = i + 1
            End If
        Next OutlookMail
    End With

    Set Folder = Nothing
    Set OutlookNamespace = Nothing
    Set OutlookApp = Nothing

End Sub
</code>```

Instead of using ranges and then offseting, go to the cell which have the sender, body and date range and reference them directly.

The only thing that comes to me, is that folder "tasks" inside your inbox folder? The error may come from there.

Edit: Code to check all your subfolders inside the inbox folder:

```<code>Sub Loop_folders_of_inbox()

    Dim ns As Outlook.Namespace
    Dim myfolder As Outlook.Folder
    Dim mysubfolder As Outlook.Folder
    Dim OutlookApp As Outlook.Application

    Set OutlookApp = New Outlook.Application
    Set ns = OutlookApp.GetNamespace("MAPI")
    'Get the default inboxfolder
    Set myfolder = ns.GetDefaultFolder(olFolderInbox)
    'Loop through each folder and display name of the folder
    For Each mysubfolder In myfolder.Folders
        Debug.Print mysubfolder.Name
    Next mysubfolder

End Sub
</code>```

Edit 2: Each word from the body into a different column:

```<code>Dim arrBody
Dim j As Long

arrBody = Split(OutlookMail.Body, " ") 'words delimited by space
For j = LBound(arrBody) To UBound(arrBody)
    .Cells(i, j + 1) = arrBody(j) 'use j + 1 because arrays built from Space function start at index 0
Next j
</code>```

Body:
I can't get the inside on my Task folder on my outlook with my code. Do you guys know any problems here?

The problem I saw is that it doesnt go in my For Loop.

Private Sub CommandButton1_Click()

Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim Folder As MAPIFolder
Dim OutlookMail As Variant
Dim i As Integer

Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Task")

i = 1

For Each OutlookMail In Folder.Items
If OutlookMail.ReceivedTime >= Range(“date_received”).Value Then
Range(“Sender”).Offset(i, 0).Value = OutlookMail.SenderName
Range(“Sender”).Offset(i, 0).Columns.AutoFit
Range(“Sender”).Offset(i, 0).VerticalAlignment = xlTop
Range(“Body”).Offset(i, 0).Value = OutlookMail.Body
Range(“Body”).Offset(i, 0).Columns.AutoFit
Range(“Body”).Offset(i, 0).VerticalAlignment = xlTop

i = i + 1
End If
Next OutlookMail

Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing

End Sub

Body:
I just changed few things on your code but it's working allright for me

Option Explicit
Private Sub CommandButton1_Click()

    Dim OutlookApp As Outlook.Application
    Dim OutlookNamespace As Namespace
    Dim Folder As MAPIFolder
    Dim OutlookMail As Variant
    Dim i As Integer

    Set OutlookApp = New Outlook.Application
    Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
    Set Folder = OutlookNamespace.GetDefaultFolder(olFolderInbox).Folders("Bienvenidas")

    i = 2

    With ThisWorkbook.Sheets("MySheet") 'Change MySheet for your sheet name, and ALWAYS reference sheets and workbooks.
        For Each OutlookMail In Folder.Items
            If OutlookMail.ReceivedTime >= .Range("C1") Then
                With .Cells(i, 1)
                    .Value = OutlookMail.SenderName
                    .Columns.AutoFit
                    .VerticalAlignment = xlTop
                End With
                With .Cells(i, 2)
                    .Value = OutlookMail.Body
                    .Columns.AutoFit
                    .VerticalAlignment = xlTop
                End With
                i = i + 1
            End If
        Next OutlookMail
    End With

    Set Folder = Nothing
    Set OutlookNamespace = Nothing
    Set OutlookApp = Nothing

End Sub

Instead of using ranges and then offseting, go to the cell which have the sender, body and date range and reference them directly.

The only thing that comes to me, is that folder "tasks" inside your inbox folder? The error may come from there.

Edit: Code to check all your subfolders inside the inbox folder:

Sub Loop_folders_of_inbox()

    Dim ns As Outlook.Namespace
    Dim myfolder As Outlook.Folder
    Dim mysubfolder As Outlook.Folder
    Dim OutlookApp As Outlook.Application

    Set OutlookApp = New Outlook.Application
    Set ns = OutlookApp.GetNamespace("MAPI")
    'Get the default inboxfolder
    Set myfolder = ns.GetDefaultFolder(olFolderInbox)
    'Loop through each folder and display name of the folder
    For Each mysubfolder In myfolder.Folders
        Debug.Print mysubfolder.Name
    Next mysubfolder

End Sub

Edit 2: Each word from the body into a different column:

Dim arrBody
Dim j As Long

arrBody = Split(OutlookMail.Body, " ") 'words delimited by space
For j = LBound(arrBody) To UBound(arrBody)
    .Cells(i, j + 1) = arrBody(j) 'use j + 1 because arrays built from Space function start at index 0
Next j


问:
How to call `one_hot` in `keras` in python3?
I have below code in python3:

```<code>docs = ['Well done!',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent!',
        'Weak',
        'Poor effort!',
        'not good',
        'poor work',
        'Could have done better.']
# define class labels
labels = np.array([1,1,1,1,1,0,0,0,0,0])
from keras import backend as K

# integer encode the documents
vocab_size = 50
encoded_docs = [K.one_hot(d, vocab_size) for d in docs]
print(encoded_docs)
</code>```

Basically I tries to encode each word from the list but I got this error:

TypeError: Value passed to parameter 'indices' has DataType string not in list of allowed values: uint8, int32, int64
.

What is wrong in my code? It seems like a type error but I don't understand why.

答:
Keras one_hot method expects the first argument to be integer type(in your case index of the words). So you need first to map each word to unique integer before using one_hot method.

docs = ['Well done!',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent!',
        'Weak',
        'Poor effort!',
        'not good',
        'poor work',
        'Could have done better.']
all_words = set()
for s in docs:
    for word in s.split():
        all_words.add(word)
all_words = list(all_words)
# define class labels
labels = np.array([1,1,1,1,1,0,0,0,0,0])
from keras import backend as K

# integer encode the documents
vocab_size = len(all_words)
encoded_docs = [[K.one_hot(all_words.index(word), vocab_size) for word in d.split()] for d in docs]
print(encoded_docs)

```

<p>If  you want to encode punctuation as separate words, then you can use <code>re</code> module to split words.</p>

<pre class="lang-py prettyprint-override"><code>import re
import string

encoded_docs = [[K.one_hot(all_words.index(word), vocab_size) for word in re.findall("[\w]+|["+string.punctuation+"]", d) for d in docs]
</code>```

Body:
I have below code in python3:

docs = ['Well done!',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent!',
        'Weak',
        'Poor effort!',
        'not good',
        'poor work',
        'Could have done better.']
# define class labels
labels = np.array([1,1,1,1,1,0,0,0,0,0])
from keras import backend as K

# integer encode the documents
vocab_size = 50
encoded_docs = [K.one_hot(d, vocab_size) for d in docs]
print(encoded_docs)

Basically I tries to encode each word from the list but I got this error:

TypeError: Value passed to parameter 'indices' has DataType string not in list of allowed values: uint8, int32, int64
.

What is wrong in my code? It seems like a type error but I don't understand why.

Body:
Keras one_hot method expects the first argument to be integer type(in your case index of the words). So you need first to map each word to unique integer before using one_hot method.

docs = ['Well done!',
        'Good work',
        'Great effort',
        'nice work',
        'Excellent!',
        'Weak',
        'Poor effort!',
        'not good',
        'poor work',
        'Could have done better.']
all_words = set()
for s in docs:
    for word in s.split():
        all_words.add(word)
all_words = list(all_words)
# define class labels
labels = np.array([1,1,1,1,1,0,0,0,0,0])
from keras import backend as K

# integer encode the documents
vocab_size = len(all_words)
encoded_docs = [[K.one_hot(all_words.index(word), vocab_size) for word in d.split()] for d in docs]
print(encoded_docs)

If  you want to encode punctuation as separate words, then you can use re module to split words.

import re
import string

encoded_docs = [[K.one_hot(all_words.index(word), vocab_size) for word in re.findall("[\w]+|["+string.punctuation+"]", d) for d in docs]


问:
SOAPProcessingException occurred when execute the artifact in WSO2 ESB
I used WSO2 ESB 5.0. I used two soap endpoints to get the response. Below mention the proxy service code.

```<code> <?xml version="1.0" encoding="UTF-8"?>
<inSequence xmlns="http://ws.apache.org/ns/synapse">
    <log/>
    <property expression="//sam:getCertificateID/sam:vehicleNumber"
        name="getVehicleNo" scope="default" type="STRING" xmlns:sam="http://sample.esb.org"/>
    <log>
        <property expression="get-property('default','getVehicleNo')" name="VehicleNo"/>
    </log>
    <call>
        <endpoint>
            <wsdl port="EmissionTestServiceHttpSoap11Endpoint"
                service="EmissionTestService" uri="http://172.17.0.1:9763/services/EmissionTestService?wsdl"/>
        </endpoint>
    </call>
    <property expression="//ns:getCertificateIDResponse/ns:return"
        name="getCertificateIDResponse" scope="default" type="STRING" xmlns:ns="http://sample.esb.org"/>
    <log>
        <property
            expression="get-property('default','getCertificateIDResponse')" name="CertificateID"/>
    </log>
    <payloadFactory media-type="xml">
        <format>
            <soapenv:Envelope xmlns:sam="http://sample.esb.org" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
                <soapenv:Header/>
                <soapenv:Body>
                    <sam:getPolicyID>
                        <sam:vehicleNumber>$1</sam:vehicleNumber>
                    </sam:getPolicyID>
                </soapenv:Body>
            </soapenv:Envelope>
        </format>
        <args>
            <arg evaluator="xml" expression="get-property('default','getVehicleNo')"/>
        </args>
    </payloadFactory>
    <log/>
    <property name="messageType" scope="axis2" type="STRING" value="application/soap+xml"/>
    <call>
        <endpoint>
            <wsdl port="InsuranceServiceHttpSoap11Endpoint"
                service="InsuranceService" uri="http://172.17.0.1:9763/services/InsuranceService?wsdl"/>
        </endpoint>
    </call>
    <property expression="//ns:getPolicyIDResponse/ns:return"
        name="getPolicyIDResponse" scope="default" type="STRING" xmlns:ns="http://sample.esb.org"/>
    <log>
        <property
            expression="get-property('default','getPolicyIDResponse')" name="PolicyID"/>
    </log>
</inSequence>
</code>```

First endpoint is working fine and gave the specific log messages. But when going to call second endpoint, below error message is occurred.

```<code>Caused by: org.apache.axiom.soap.SOAPProcessingException: First Element must contain the local name, Envelope , but found faultstring
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.constructNode(StAXSOAPModelBuilder.java:305)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createOMElement(StAXSOAPModelBuilder.java:252)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createNextOMElement(StAXSOAPModelBuilder.java:234)
    at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:249)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.getSOAPEnvelope(StAXSOAPModelBuilder.java:204)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.<init>(StAXSOAPModelBuilder.java:154)
    at org.apache.axiom.om.impl.AbstractOMMetaFactory.createStAXSOAPModelBuilder(AbstractOMMetaFactory.java:73)
    at org.apache.axiom.om.impl.AbstractOMMetaFactory.createSOAPModelBuilder(AbstractOMMetaFactory.java:79)
    at org.apache.axiom.om.OMXMLBuilderFactory.createSOAPModelBuilder(OMXMLBuilderFactory.java:196)
    at org.apache.axis2.builder.SOAPBuilder.processDocument(SOAPBuilder.java:65)
    at org.apache.synapse.transport.passthru.util.DeferredMessageBuilder.getDocument(DeferredMessageBuilder.java:148)
    at org.apache.synapse.transport.passthru.util.RelayUtils.builldMessage(RelayUtils.java:137)
    ... 14 more
</code>```

Can you help me to solve this issue. Any help or workarounds are really appreciated.

答:
Your endpoint is not returning an soap Envelope. You can see what's happening if you set 'configure->logging->apache.synapse.tranport.http.wire' to 'debug'.

Because the endpoint is not returning SOAP, but likely plain old XML you can try setting

```<code><property name="messageType" value="application/xml" scope="axis2"/>
<property name="ContentType" value="application/xml" scope="axis2"/>
</code>```

before sending the message.

Body:
I used WSO2 ESB 5.0. I used two soap endpoints to get the response. Below mention the proxy service code.

 <?xml version="1.0" encoding="UTF-8"?>
<inSequence xmlns="http://ws.apache.org/ns/synapse">
    <log/>
    <property expression="//sam:getCertificateID/sam:vehicleNumber"
        name="getVehicleNo" scope="default" type="STRING" xmlns:sam="http://sample.esb.org"/>
    <log>
        <property expression="get-property('default','getVehicleNo')" name="VehicleNo"/>
    </log>
    <call>
        <endpoint>
            <wsdl port="EmissionTestServiceHttpSoap11Endpoint"
                service="EmissionTestService" uri="http://172.17.0.1:9763/services/EmissionTestService?wsdl"/>
        </endpoint>
    </call>
    <property expression="//ns:getCertificateIDResponse/ns:return"
        name="getCertificateIDResponse" scope="default" type="STRING" xmlns:ns="http://sample.esb.org"/>
    <log>
        <property
            expression="get-property('default','getCertificateIDResponse')" name="CertificateID"/>
    </log>
    <payloadFactory media-type="xml">
        <format>
            <soapenv:Envelope xmlns:sam="http://sample.esb.org" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
                <soapenv:Header/>
                <soapenv:Body>
                    <sam:getPolicyID>
                        <sam:vehicleNumber>$1</sam:vehicleNumber>
                    </sam:getPolicyID>
                </soapenv:Body>
            </soapenv:Envelope>
        </format>
        <args>
            <arg evaluator="xml" expression="get-property('default','getVehicleNo')"/>
        </args>
    </payloadFactory>
    <log/>
    <property name="messageType" scope="axis2" type="STRING" value="application/soap+xml"/>
    <call>
        <endpoint>
            <wsdl port="InsuranceServiceHttpSoap11Endpoint"
                service="InsuranceService" uri="http://172.17.0.1:9763/services/InsuranceService?wsdl"/>
        </endpoint>
    </call>
    <property expression="//ns:getPolicyIDResponse/ns:return"
        name="getPolicyIDResponse" scope="default" type="STRING" xmlns:ns="http://sample.esb.org"/>
    <log>
        <property
            expression="get-property('default','getPolicyIDResponse')" name="PolicyID"/>
    </log>
</inSequence>

First endpoint is working fine and gave the specific log messages. But when going to call second endpoint, below error message is occurred.

Caused by: org.apache.axiom.soap.SOAPProcessingException: First Element must contain the local name, Envelope , but found faultstring
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.constructNode(StAXSOAPModelBuilder.java:305)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createOMElement(StAXSOAPModelBuilder.java:252)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.createNextOMElement(StAXSOAPModelBuilder.java:234)
    at org.apache.axiom.om.impl.builder.StAXOMBuilder.next(StAXOMBuilder.java:249)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.getSOAPEnvelope(StAXSOAPModelBuilder.java:204)
    at org.apache.axiom.soap.impl.builder.StAXSOAPModelBuilder.<init>(StAXSOAPModelBuilder.java:154)
    at org.apache.axiom.om.impl.AbstractOMMetaFactory.createStAXSOAPModelBuilder(AbstractOMMetaFactory.java:73)
    at org.apache.axiom.om.impl.AbstractOMMetaFactory.createSOAPModelBuilder(AbstractOMMetaFactory.java:79)
    at org.apache.axiom.om.OMXMLBuilderFactory.createSOAPModelBuilder(OMXMLBuilderFactory.java:196)
    at org.apache.axis2.builder.SOAPBuilder.processDocument(SOAPBuilder.java:65)
    at org.apache.synapse.transport.passthru.util.DeferredMessageBuilder.getDocument(DeferredMessageBuilder.java:148)
    at org.apache.synapse.transport.passthru.util.RelayUtils.builldMessage(RelayUtils.java:137)
    ... 14 more

Can you help me to solve this issue. Any help or workarounds are really appreciated.

Body:
Your endpoint is not returning an soap Envelope. You can see what's happening if you set 'configure->logging->apache.synapse.tranport.http.wire' to 'debug'.

Because the endpoint is not returning SOAP, but likely plain old XML you can try setting

<property name="messageType" value="application/xml" scope="axis2"/>
<property name="ContentType" value="application/xml" scope="axis2"/>

before sending the message.


问:
Why less than operator is not giving the right answer?
I have two input fields and want to compare them using less than operator. If i insert value less than 10 in one field and greater than 10 in other field and use less operator between them its not showing the right answer

function myFunction() {
  var x = document.getElementById("myInput").value;
  var y = document.getElementById("h1").value;
  alert(x);
  if(y > x)
 alert("good");
  else
 alert("ok");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="myInput" onchange="myFunction()"/>
<input type="number" id="h1"/></code>```

答:
The typeof of both the input type='number' is string. So before doing comparison change to number. You can do that either using parseInt or by using unary operator

function myFunction() {
  var x = document.getElementById("myInput").value;
  var y = document.getElementById("h1").value;
  console.log(typeof(x), typeof(y))
  if (parseInt(y, 10) > parseInt(x, 10))
    alert("good");
  else
    alert("ok");
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="myInput" onchange="myFunction()" />
<input type="number" id="h1" /></code>```

Body:
I have two input fields and want to compare them using less than operator. If i insert value less than 10 in one field and greater than 10 in other field and use less operator between them its not showing the right answer

function myFunction() {
  var x = document.getElementById("myInput").value;
  var y = document.getElementById("h1").value;
  alert(x);
  if(y > x)
 alert("good");
  else
 alert("ok");
}

<input type="number" id="myInput" onchange="myFunction()"/>
<input type="number" id="h1"/>

Body:
The typeof of both the input type='number' is string. So before doing comparison change to number. You can do that either using parseInt or by using unary operator

function myFunction() {
  var x = document.getElementById("myInput").value;
  var y = document.getElementById("h1").value;
  console.log(typeof(x), typeof(y))
  if (parseInt(y, 10) > parseInt(x, 10))
    alert("good");
  else
    alert("ok");
}

<input type="number" id="myInput" onchange="myFunction()" />
<input type="number" id="h1" />


问:
Updating all packages with Npm
I have a fairly large number of packages that are outdated and I want to update. I tried running npm update as described in the npm documentation: npm update --depth 9999 -dev
The update took a long time and at the end it failed. I tried a few more time, I set the stack size to unlimited, etc, but it always takes hours and at the end it fails.

I tried updating a single package with --depth 999 (not 9999) and that failed as well.

Is there any recommended way how to update all packages that works?

```<code>**Edit:** At first I was getting  `MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit`
</code>```

Then I got a heap exceeded exception:

```<code>FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
</code>```

And finally, I got Max call stack size exceeded.

I set the stack size to unlimited and lowered the depth, but it's been running for hours with no result.

答:
It turns out I somehow had 4 npm update jobs running. I killed them, then ran npm outdated, took the output and ran npm install <package>@<version> for each package.

For good measure I then installed and ran npm-check-udates which installed another handful of packages.

Title: Updating all packages with Npm

Body:
I have a fairly large number of packages that are outdated and I want to update. I tried running npm update as described in the npm documentation: npm update --depth 9999 -dev
The update took a long time and at the end it failed. I tried a few more time, I set the stack size to unlimited, etc, but it always takes hours and at the end it fails.

I tried updating a single package with --depth 999 (not 9999) and that failed as well.

Is there any recommended way how to update all packages that works?

**Edit:** At first I was getting  `MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 error listeners added. Use emitter.setMaxListeners() to increase limit`

Then I got a heap exceeded exception:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

And finally, I got Max call stack size exceeded.

I set the stack size to unlimited and lowered the depth, but it's been running for hours with no result.


问:
What's the best way of parsing strings?
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet.

We'll need to support more 'formats' in the future too.

Do we go for a solution using:

Regex

Simply string searching (using string.IndexOf etc)

Lex/ Yacc

Other

The overall solution will be developed in C# 2.0 (hopefully 3.5)

答:
With as little information you provided, i would choose Regex.

But what kind of information you want to parse and what you would want to do will change the decision to Lex/Yacc maybe..

But it looks like you've already made your mind up with String search :)

Title: What's the best way of parsing strings?

LastEditorDisplayName: Torsten Marek

OwnerDisplayName: Prakash


问:
What's the best way to track unique visits to a page?
I want to log unique visits to a particular page on my site. What is a pretty accurate yet simple way to do this? Simply by IP? Suggestions?

Let me clarify a bit:

I have a list of articles on my site. Every article is actually the same page like article.aspx. However the content is different based on thee article being viewed. I want to track unique views of a particular article.

Thanks!

答:
Cookies. Check for a unique cookie value. If it already exists, the user has already visited your site. If not, track the unique visit and assign the cookie.

Optionally, you can also use the expiration date on a cookie to make sure it only happens once every n-th second/minute/hour/day, etc.

OwnerDisplayName: Micah

LastEditorDisplayName: Micah


问:
CLONE_VM undeclared (first use in this function)
I am using the clone feature in linux c.

However, I encountered the error CLONE_VM undeclared (first use in this function) when I tried to compile my code.

I went to google for solutions and one of the site mentioned that #include <sched.h> must be included inside the code. I have already included #include <sched.h> in my code but the compilation error still persists.

Any help? :)

```<code>int c = clone(child,p+STACKSIZE-1,CLONE_VM|SIGCHLD,NULL) ;
</code>```

答: sometime including #include <sched.h> will not work, so point sched.h file from linux. i.e. #include <linux/sched.h>

Body:
I am using the clone feature in linux c.

However, I encountered the error CLONE_VM undeclared (first use in this function) when I tried to compile my code.

I went to google for solutions and one of the site mentioned that #include <sched.h> must be included inside the code. I have already included #include <sched.h> in my code but the compilation error still persists.

Any help? :)

int c = clone(child,p+STACKSIZE-1,CLONE_VM|SIGCHLD,NULL) ;


问:
How to get the fingerprint of a public key?
In PHP, I have a public key (already as an OpenSSL resource). I'd like to calculate that public keys fingerprint (SHA1 or other hash).

How do I do this?

PHP version is 7.2 or older.

EDIT: This is not a duplicate of the other question, because that question is about doing this for an SSH key with SSH (and related) commands. I want to do the same thing using PHP and the PHP-extension openssl.

答:
I've found the solution myself. The basic idea:

Decode the base64 encoded part of the key in PEM format (after removing spaces from it)

Hash the resulting binary data.

In code (PHP):

```<code>function getPublicKeyFingerprint(string $pemEncodedKey, string $hashAlgorithm = 'sha1')
{
    $keyWithoutPemWrapper = \preg_replace(
        '/^-----BEGIN (?:[A-Z]+ )?PUBLIC KEY-----([A-Za-z0-9\\/\\+\\s=]+)-----END (?:[A-Z]+ )?PUBLIC KEY-----$/ms',
        '\\1',
        $pemEncodedKey
    );
    $keyDataWithoutSpaces = \preg_replace('/\\s+/', '', $keyWithoutPemWrapper);

    $binaryKey = \base64_decode($keyDataWithoutSpaces);

    return \hash($hashAlgorithm, $binaryKey);
}
</code>```

Body:
I've found the solution myself. The basic idea:

Decode the base64 encoded part of the key in PEM format (after removing spaces from it)

Hash the resulting binary data.

In code (PHP):

function getPublicKeyFingerprint(string $pemEncodedKey, string $hashAlgorithm = 'sha1')
{
    $keyWithoutPemWrapper = \preg_replace(
        '/^-----BEGIN (?:[A-Z]+ )?PUBLIC KEY-----([A-Za-z0-9\\/\\+\\s=]+)-----END (?:[A-Z]+ )?PUBLIC KEY-----$/ms',
        '\\1',
        $pemEncodedKey
    );
    $keyDataWithoutSpaces = \preg_replace('/\\s+/', '', $keyWithoutPemWrapper);

    $binaryKey = \base64_decode($keyDataWithoutSpaces);

    return \hash($hashAlgorithm, $binaryKey);
}


问:
To merge the value key:value RDD having common key
I am new to spark using python so forgive if the question sounds basic. If I have a RDD:

```<code>[(((1, 0), 0.0), (2, 0)),
 (((1, 0), 0.0), (3, 0)),
 (((2, 0), -0.0), (1, 0)),
 (((2, 0), -0.0), (3, 0)),
 (((3, 0), -0.0), (1, 0)),
 (((3, 0), -0.0), (2, 0))]
</code>```

I want to merge the values having the common key. So basically my output should be-

```<code>[(((1, 0), 0.0), [(2, 0),(3,0)])
 (((2, 0), -0.0), [(1, 0),(3,0)])
 (((3, 0), -0.0), [(1, 0),(2,0)])]
</code>```

I tried using groupByKey() but still unable to fetch the solution. Any help would be grateful. Thanks.

答:
This should do the trick:
rdd.groupByKey().mapValues(list).collect()

Body:
I am new to spark using python so forgive if the question sounds basic. If I have a RDD:

[(((1, 0), 0.0), (2, 0)),
 (((1, 0), 0.0), (3, 0)),
 (((2, 0), -0.0), (1, 0)),
 (((2, 0), -0.0), (3, 0)),
 (((3, 0), -0.0), (1, 0)),
 (((3, 0), -0.0), (2, 0))]

I want to merge the values having the common key. So basically my output should be-

[(((1, 0), 0.0), [(2, 0),(3,0)])
 (((2, 0), -0.0), [(1, 0),(3,0)])
 (((3, 0), -0.0), [(1, 0),(2,0)])]

I tried using groupByKey() but still unable to fetch the solution. Any help would be grateful. Thanks.


问:
How to print a meaningful firebase-dart exception
I can't get a meaningful exception error printed out to console. I get only [object Object]

```<code>@TestOn('browser')
import 'dart:io';

import 'package:firebase/firebase.dart';
import 'package:test/test.dart';

import 'package:workshop_participant_flutter/firebase_config.dart' as my_config;

void main() {
  test('too big images cant be uploaded', () async {
    App app;
    app = my_config.initFirebase();
    final ref = app.storage().ref('/storageTest/test.file');
    final image = File('./too_big_file.png');
    try {
      await ref.put(image).future;
    } on IOException catch (e) {
      print(e);
    } catch (e) {
      print(e.toString());
      print(e);
    }
  });
}
</code>```

I'm loading up an image to Firebase Storage and it fails because I have set the rules to reject all files bigger than x bytes. This is the wanted behaviour.

All other tests work fine. So the setup and configuration is OK. My problem now is, that I want to learn, what error message I get. I want to catch that exception and handle it.

I hope somebody has stumbled over the same phenomena and can advise me here.

In case you want to run the test code above you are going to need this file as well

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <title>Upload Test</title>
  </head>
  <body>
    <script src="https://www.gstatic.com/firebasejs/5.5.2/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.5.2/firebase-storage.js"></script>
    <script src="packages/test/dart.js"></script>
    <link rel="x-dart-test" href="upload_test.dart" />
  </body>
</html>
</code>```

答:
You must create a custom exception as per your need.Example of a custom exception.

```<code>class AmountException implements Exception {
  String get errorMessage => 'Amount should be greater than zero';
}
void main() {
  try {
    withdrawAmount(-1);
  } catch(e) {
    print(e.errorMessage);
  } finally {
    print('Ending requested operation.....');
  }
}
void withdrawAmount(int amount) {
  if (amount <= 0) {
    throw AmountException();
  }
}
</code>```

https://www.tutorialspoint.com/dart_programming/dart_programming_exceptions.htm

Body:
I can't get a meaningful exception error printed out to console. I get only [object Object]

@TestOn('browser')
import 'dart:io';

import 'package:firebase/firebase.dart';
import 'package:test/test.dart';

import 'package:workshop_participant_flutter/firebase_config.dart' as my_config;

void main() {
  test('too big images cant be uploaded', () async {
    App app;
    app = my_config.initFirebase();
    final ref = app.storage().ref('/storageTest/test.file');
    final image = File('./too_big_file.png');
    try {
      await ref.put(image).future;
    } on IOException catch (e) {
      print(e);
    } catch (e) {
      print(e.toString());
      print(e);
    }
  });
}

I'm loading up an image to Firebase Storage and it fails because I have set the rules to reject all files bigger than x bytes. This is the wanted behaviour.

All other tests work fine. So the setup and configuration is OK. My problem now is, that I want to learn, what error message I get. I want to catch that exception and handle it.

I hope somebody has stumbled over the same phenomena and can advise me here.

In case you want to run the test code above you are going to need this file as well

<!DOCTYPE html>

    <title>Upload Test</title>

    <link rel="x-dart-test" href="upload_test.dart" />

Body:
You must create a custom exception as per your need.Example of a custom exception.

class AmountException implements Exception {
  String get errorMessage => 'Amount should be greater than zero';
}
void main() {
  try {
    withdrawAmount(-1);
  } catch(e) {
    print(e.errorMessage);
  } finally {
    print('Ending requested operation.....');
  }
}
void withdrawAmount(int amount) {
  if (amount <= 0) {
    throw AmountException();
  }
}

https://www.tutorialspoint.com/dart_programming/dart_programming_exceptions.htm


问:
how to remove https links from a string column in pandas
I have the following dataframe:

```<code>import pandas as pd
df = pd.DataFrame({'col':['text https://random.website1.com text', 'text https://random.website2.com']})
</code>```

I would like to remove all the links from this column.

Any ideas ?

答:
Use list comprehension with split and test url, last join values by space:</p>

```<code>from urllib.parse import urlparse
#https://stackoverflow.com/a/52455972
def is_url(url):
  try:
    result = urlparse(url)
    return all([result.scheme, result.netloc])
  except ValueError:
    return False

df['new'] = [' '.join(y for y in x.split() if not is_url(y)) for x in df['col']]
print (df)
                                     col        new
0  text https://random.website1.com text  text text
1       text https://random.website2.com       text
</code>```

Body:
I have the following dataframe:

import pandas as pd
df = pd.DataFrame({'col':['text https://random.website1.com text', 'text https://random.website2.com']})

I would like to remove all the links from this column.

Any ideas ?

Body:
Use list comprehension with split and test url, last join values by space:

from urllib.parse import urlparse
#https://stackoverflow.com/a/52455972
def is_url(url):
  try:
    result = urlparse(url)
    return all([result.scheme, result.netloc])
  except ValueError:
    return False

df['new'] = [' '.join(y for y in x.split() if not is_url(y)) for x in df['col']]
print (df)
                                     col        new
0  text https://random.website1.com text  text text
1       text https://random.website2.com       text