问:
Animation completion block goes haywire after dismissing view

I have a detail viewcontroller that contains a repeating carousel with an  animating image view like so:

```<code>func animateCarousel1(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 1 complete")
        self.animateCarousel2()
                  })
    }
func animateCarousel2(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 2 complete")
        self.animateCarousel1()
                  })
    }
</code>```

Upon popping this view and returning to the parent view, I see that in the debug console, the functions are continuing to be called in the background, repeatedly and simultaneously, infinitely.

CPU usage also jumps to 90% in the simulator as well.

Is there some sort of deinit I need to do before popping the viewcontroller? I can't seem to wrap my head around this one.

答:
The issue is that completion blocks are called even if the animation finishes. So there are a few possible solutions:

Check the finished parameter of the completion handlers:

```<code>func animateCarousel1() {
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations: {
        //image animation
    }, completion: { finished in
        print("animation 1 complete")
        if finished { self.animateCarousel2() }
    })
}

func animateCarousel2() {
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations: {
        //image animation
    }, completion: { finished in
        print("animation 2 complete")
        if finished { self.animateCarousel1() }
    })
}
</code>```

Use a different animation technique that doesn't require the circular references between these animation routines, e.g.:

```<code>func animateCarousel() {
    UIView.animateKeyframes(withDuration: 8, delay: 3, options: .repeat, animations: {
        UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.125) {
            // animation 1
        }
        UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.125) {
            // animation 2
        }
    }, completion: nil)
}
</code>```

Body:
I have a detail viewcontroller that contains a repeating carousel with an  animating image view like so:

func animateCarousel1(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 1 complete")
        self.animateCarousel2()
                  })
    }
func animateCarousel2(){
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations:
        //image animation
    },completion: { (_) -> Void in
        print("animation 2 complete")
        self.animateCarousel1()
                  })
    }

Upon popping this view and returning to the parent view, I see that in the debug console, the functions are continuing to be called in the background, repeatedly and simultaneously, infinitely.

CPU usage also jumps to 90% in the simulator as well.

Is there some sort of deinit I need to do before popping the viewcontroller? I can't seem to wrap my head around this one.

Body:
The issue is that completion blocks are called even if the animation finishes. So there are a few possible solutions:

Check the finished parameter of the completion handlers:

func animateCarousel1() {
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations: {
        //image animation
    }, completion: { finished in
        print("animation 1 complete")
        if finished { self.animateCarousel2() }
    })
}

func animateCarousel2() {
    UIView.animate(withDuration: 1, delay: 3, options: .curveEaseInOut, animations: {
        //image animation
    }, completion: { finished in
        print("animation 2 complete")
        if finished { self.animateCarousel1() }
    })
}

Use a different animation technique that doesn't require the circular references between these animation routines, e.g.:

func animateCarousel() {
    UIView.animateKeyframes(withDuration: 8, delay: 3, options: .repeat, animations: {
        UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.125) {
            // animation 1
        }
        UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.125) {
            // animation 2
        }
    }, completion: nil)
}


来源: stackexchange

问:
XML Specific Query
I'm currently learning XML and XPATH and I need help in constructing a specific XPATH Query.

Here's the code sample:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Backup_Jobs xmlns="http://www.w3.org">
<Jobs>
    <Job name="Daily_Backup" lastRunTime="2001-10-26+00:00">
        <Job_Items>
            <Item id="1">vm-Centos7</Item>
            <Item id="2">vm-sample</Item>
        </Job_Items>
    </Job>
    <Job name="replicate" lastRunTime="2004-08-01+00:00">
        <Job_Items>
            <Item id="3">VMWare Workstation</Item>
        </Job_Items>
    </Job>
</Jobs>
<Hosts>
    <Host name="vcenter.tech.local" id="1111">
        <S name="CLARiion" size="2XL"/>
        <Vm id="2122" name="vm-Centos7">
            <Drive id="1241" name="sample1" size="500"/>
        </Vm>
        <Vm id="2123" name="vm-sample">
            <Drive id="1123" name="sample2" size="500"/>
        </Vm>
        <Vm id="2124" name="VMWare Workstation">
            <Drive id="1124" name="sample3" size="950"/>
        </Vm>
    </Host>
</Hosts>
</Backup_Jobs>
</code>```

Here's the task:

Suppose we know the name of a [Job]; This Job contains an [Item] which has a name of a virtual machine. We want to get the name of the [Host] which has a [Vm] element which attribute is the name of a virtual machine we knew earlier.

I'm still learning, so any form of advice/solution is hugely appreciated!

答:
Replace Daily_Backup with the value for which you want to execute query

```<code>//Host[Vm[@name=//Job[@name="Daily_Backup"]/Job_Items/Item]]/@name
</code>```

ContentLicense: CC BY-SA 3.0

Title: XML Specific Query

Body:
I'm currently learning XML and XPATH and I need help in constructing a specific XPATH Query.

Here's the code sample:

<?xml version="1.0" encoding="UTF-8"?>
<Backup_Jobs xmlns="http://www.w3.org">
<Jobs>
    <Job name="Daily_Backup" lastRunTime="2001-10-26+00:00">
        <Job_Items>
            <Item id="1">vm-Centos7</Item>
            <Item id="2">vm-sample</Item>
        </Job_Items>
    </Job>
    <Job name="replicate" lastRunTime="2004-08-01+00:00">
        <Job_Items>
            <Item id="3">VMWare Workstation</Item>
        </Job_Items>
    </Job>
</Jobs>
<Hosts>
    <Host name="vcenter.tech.local" id="1111">
        <S name="CLARiion" size="2XL"/>
        <Vm id="2122" name="vm-Centos7">
            <Drive id="1241" name="sample1" size="500"/>
        </Vm>
        <Vm id="2123" name="vm-sample">
            <Drive id="1123" name="sample2" size="500"/>
        </Vm>
        <Vm id="2124" name="VMWare Workstation">
            <Drive id="1124" name="sample3" size="950"/>
        </Vm>
    </Host>
</Hosts>
</Backup_Jobs>

Here's the task:

Suppose we know the name of a [Job]; This Job contains an [Item] which has a name of a virtual machine. We want to get the name of the [Host] which has a [Vm] element which attribute is the name of a virtual machine we knew earlier.

I'm still learning, so any form of advice/solution is hugely appreciated!

Body:
Replace Daily_Backup with the value for which you want to execute query

//Host[Vm[@name=//Job[@name="Daily_Backup"]/Job_Items/Item]]/@name


问:
How do I crop internal HTML elements at CSS3 rounded borders?
I have a div inside another div. The outer div has rounded borders using CSS3. The problem is, if I set a background color on the inner div it bleeds through into the corners. Here's a test page to show what I mean: http://www.webdevout.net/test?0O

I suspect it's not a renderer issue, as the same thing happens in Chrome, FF, and Opera. How do I get the inner div to crop at the rounded borders? Setting border-radius on the inner div to inherit doesn't cut it, the borders don't match up.

EDIT: The inner div is actually a header for more content inside the outer div, so applying the rounded borders to the inner div instead will not work.

答:
Round your top corners on the inner div but don't round the bottom corners, like so:

http://www.webdevout.net/test?0T

ContentLicense: CC BY-SA 2.5


问:
Ways to apply an applicative functor multiple times
Hello fellow Haskellers.

Let's say I have an applicative functor (not an instance of monad) I
want to apply multiple times to a pure initial value. For example,

```<code>λ> Just (1+) <*> (Just (1+) <*> pure 0)
Just 2
</code>```

If I want to generalize this to any number of consecutive
applications, I can do it with a fold.

```<code>applyAppl :: Applicative f => f (a -> a) -> Int -> f a -> f a
applyAppl f n i = foldr (<*>) i $ replicate n f
</code>```

After this definition,

```<code>λ> applyAppl (Just (1+)) 10 $ pure 0
Just 10
</code>```

I have an awkward suspicion that the generalization could also be
done with one of the higher-order builtin applicative tools such as sequenceA or traverse. Can it?

(Edited to take into account the first two comments below.)

答:
You could use iterate:

```<code>applyAppl :: Applicative f => f (a -> a) -> Int -> f a -> f a
applyAppl f n i = iterate (f <*>) i !! n
</code>```

Loaded into GHCi:

```<code>ghci> applyAppl (Just (+1)) 10 (pure 0)
Just 10
</code>```

I'm not sure that's necessarily better than your implementation, since I suspect both implementations fuse into something with essentially the same performance profile (though I haven't tested that), but it is different.

I've seen this sort of "iterate with (!!)" pattern for memoization so I'm pretty sure that, at the very least, it won't have worse performance.

Body:
Hello fellow Haskellers.

Let's say I have an applicative functor (not an instance of monad) I
want to apply multiple times to a pure initial value. For example,

λ> Just (1+) <*> (Just (1+) <*> pure 0)
Just 2

If I want to generalize this to any number of consecutive
applications, I can do it with a fold.

applyAppl :: Applicative f => f (a -> a) -> Int -> f a -> f a
applyAppl f n i = foldr (<*>) i $ replicate n f

After this definition,

λ> applyAppl (Just (1+)) 10 $ pure 0
Just 10

I have an awkward suspicion that the generalization could also be
done with one of the higher-order builtin applicative tools such as sequenceA or traverse. Can it?

(Edited to take into account the first two comments below.)

Body:
You could use iterate:

applyAppl :: Applicative f => f (a -> a) -> Int -> f a -> f a
applyAppl f n i = iterate (f <*>) i !! n

Loaded into GHCi:

ghci> applyAppl (Just (+1)) 10 (pure 0)
Just 10

I'm not sure that's necessarily better than your implementation, since I suspect both implementations fuse into something with essentially the same performance profile (though I haven't tested that), but it is different.

I've seen this sort of "iterate with (!!)" pattern for memoization so I'm pretty sure that, at the very least, it won't have worse performance.


问:
Reduce size of PrimeNg Library with Angular Cli
PrimeNg is a big library containing many components. My angular application is using only few components out of it.
And I am using AngularCLI to build this application.
When I build it, vendor.bundle has entire content of primeng library. This makes huge size of bundle size (~4MB).

How can I include only necessary components instead of full library?

答:
Generally we import PrimeNg component using following syntax

import {DataTableModule,SharedModule} from 'primeng/primeng';

When we refer to this common namespace, it pulls entire library in vendor.bundle.js

Instead of this, pull it from specific module,
import { DataTableModule,  } from 'primeng/components/datatable/datatable';
import { SharedModule } from 'primeng/components/common/shared';

This will just include referred component (+ their dependencies) in vendor.bundle.js

To find your relevant path, download PrimeNg Code (https://github.com/primefaces/primeng) and check list of components listed in "primeng.d.ts" file.


问:
In UWP, how can I reset an app’s data?
I know that in order to reset an app’s data, I have to open the Settings app from Start menu. Head to System > Apps & Features, locate the app, then click the "Advance Options" and tap Reset but I want to achieve this by code. I think I have to call this line but I don't know if I have to do something else: Windows.Storage.ApplicationData.Current.ClearAsync()</p>

答:
To clear the Data, you should do:

find the settings file(and other temp files), only you know where these files is.
such as this:

delete these files in your reset code.

restart your app.

hope help.

Title: In UWP, how can I reset an app’s data?


问:
Find overlapping between intervals in Javascript/TypeScript
I have the following intervals with start time and end time:

```<code>{ status: 'A', start: 12:20, end: 12:35},
{ status: 'B', start: 12:21, end: 12:28},
{ status: 'C', start: 12:22, end: 12:30},
{ status: 'D', start: 12:30, end: 12:45},
{ status: 'E', start: 12:40, end: 12:48}
</code>```

As you can see, there are some overlaps, like: 12:22 -->12:28 that includes A, B, and C statuses. or D and E that have 12:40 -->12:45 overlap. All the data are sorted based on their start time. How can I write a program in Javascript to have the overlaps and their correspondent statuses?

Basically, the output would be the following:

```<code>[A, B, C] : {12:22 , 12:28}
[D, E] : {12:40 , 12:45}
...
</code>```

Current code finds two overlaps:

const schedule = [
      { status: 'A', start: '12:20', end: '12:35'},
      { status: 'B', start: '12:21', end: '12:28'},
      { status: 'C', start: '12:22', end: '12:30'},
      { status: 'D', start: '12:30', end: '12:45'},
      { status: 'E', start: '12:40', end: '12:48'}
    ]
    const intervali = {start: '', end:'', status:''};
    for (i = 0; i < schedule.length - 1; i++) {
      interval_i = schedule[i];
      for (j = i + 1; j < schedule.length; j++) {
         interval_j = schedule[j];
        if (interval_j.start < interval_i.end && interval_j.end > interval_i.start) {
          intervali['start'] = interval_i.start > interval_j.start ? interval_i.start : interval_j.start;
          intervali['end'] = interval_i.end < interval_j.end ? interval_i.end : interval_j.end;
          intervali['status'] = interval_i.status + ' - ' + interval_j.status;
          console.log(intervali)
        }
      }
    }```

答:
You can use nested loops to loop over each item twice and run a comparison. Please see comments below.

const schedule = [
  { status: 'A', start: '12:20', end: '12:35'},
  { status: 'B', start: '12:21', end: '12:28'},
  { status: 'C', start: '12:22', end: '12:30'},
  { status: 'D', start: '12:30', end: '12:45'},
  { status: 'E', start: '12:40', end: '12:48'}
]

// convert a time string to integer of minutes
const toMinutes = time => {
  const [hour, minute] = time.split(':')
  return (Number(hour) * 60) + Number(minute)
}

function findOverlappying(schedule) {

  const l = schedule.length
  const ret = {}

  // loop over each item twice
  for (let i = 0; i < l; i++) {
    for (let j = 0; j < l; j++) {

      const left = schedule[j]
      const right = schedule[i]

      // set the status to the return object
      ret[left.status] = ret[left.status] || {
        ...left,
        overlap: []
      }

      // don't process for the same key
      if (i === j) {
        continue
      }

      // get the start and stop times as minutes to compare
      const leftStart = toMinutes(left.start)
      const leftStop = toMinutes(left.end)
      const rightStart = toMinutes(right.start)
      const rightStop = toMinutes(right.end)

      // compare the start and stop times for overlapping
      if (
        (leftStart > rightStart && leftStart < rightStop) ||
        (leftStop > rightStart && leftStop < rightStop)
      ) {
        // add time to overlapping status identifier
        ret[left.status].overlap.push(right.status)
      }
    }
  }
  return ret
}

console.log(
  findOverlappying(schedule)
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script></code>```

Body:
I have the following intervals with start time and end time:

{ status: 'A', start: 12:20, end: 12:35},
{ status: 'B', start: 12:21, end: 12:28},
{ status: 'C', start: 12:22, end: 12:30},
{ status: 'D', start: 12:30, end: 12:45},
{ status: 'E', start: 12:40, end: 12:48}

As you can see, there are some overlaps, like: 12:22 -->12:28 that includes A, B, and C statuses. or D and E that have 12:40 -->12:45 overlap. All the data are sorted based on their start time. How can I write a program in Javascript to have the overlaps and their correspondent statuses?

Basically, the output would be the following:

[A, B, C] : {12:22 , 12:28}
[D, E] : {12:40 , 12:45}
...

Current code finds two overlaps:

const schedule = [
      { status: 'A', start: '12:20', end: '12:35'},
      { status: 'B', start: '12:21', end: '12:28'},
      { status: 'C', start: '12:22', end: '12:30'},
      { status: 'D', start: '12:30', end: '12:45'},
      { status: 'E', start: '12:40', end: '12:48'}
    ]
    const intervali = {start: '', end:'', status:''};
    for (i = 0; i < schedule.length - 1; i++) {
      interval_i = schedule[i];
      for (j = i + 1; j < schedule.length; j++) {
         interval_j = schedule[j];
        if (interval_j.start < interval_i.end && interval_j.end > interval_i.start) {
          intervali['start'] = interval_i.start > interval_j.start ? interval_i.start : interval_j.start;
          intervali['end'] = interval_i.end < interval_j.end ? interval_i.end : interval_j.end;
          intervali['status'] = interval_i.status + ' - ' + interval_j.status;
          console.log(intervali)
        }
      }
    }

Body:
You can use nested loops to loop over each item twice and run a comparison. Please see comments below.

const schedule = [
  { status: 'A', start: '12:20', end: '12:35'},
  { status: 'B', start: '12:21', end: '12:28'},
  { status: 'C', start: '12:22', end: '12:30'},
  { status: 'D', start: '12:30', end: '12:45'},
  { status: 'E', start: '12:40', end: '12:48'}
]

// convert a time string to integer of minutes
const toMinutes = time => {
  const [hour, minute] = time.split(':')
  return (Number(hour) * 60) + Number(minute)
}

function findOverlappying(schedule) {

  const l = schedule.length
  const ret = {}

  // loop over each item twice
  for (let i = 0; i < l; i++) {
    for (let j = 0; j < l; j++) {

      const left = schedule[j]
      const right = schedule[i]

      // set the status to the return object
      ret[left.status] = ret[left.status] || {
        ...left,
        overlap: []
      }

      // don't process for the same key
      if (i === j) {
        continue
      }

      // get the start and stop times as minutes to compare
      const leftStart = toMinutes(left.start)
      const leftStop = toMinutes(left.end)
      const rightStart = toMinutes(right.start)
      const rightStop = toMinutes(right.end)

      // compare the start and stop times for overlapping
      if (
        (leftStart > rightStart && leftStart < rightStop) ||
        (leftStop > rightStart && leftStop < rightStop)
      ) {
        // add time to overlapping status identifier
        ret[left.status].overlap.push(right.status)
      }
    }
  }
  return ret
}

console.log(
  findOverlappying(schedule)
)

<script src="https://codepen.io/synthet1c/pen/KyQQmL.js"></script>


问:
How to share entity between REST service between two microservices?
I have created two micro-services using java. I need to make a REST api call from service A to service B. The data sent will be in JSON format. Using jax-rs I need to create entity class in both the service.

Since both the entity class be same in both the projects. Do i

Create an common jar and use is for all my entity/domain objects? Does this make my microservice more tightly coupled?

Do i create the same class in both the microservice projects? This will just mean repeating the work in both the projects?

Is there a better way to communicate between the sevices?

答:
I'd say it depends on the situation. If you use a shared package, this will introduce a coupling between the two projects. This makes sense, if both of the project build up on the same data classes and therefore will have the same dto objects to work with. Ideally you would have your own nexus which simplifies the usage of the shared artefact.
Otherwise, if only a few classes are redundant I probably would implement it in each sevice separately, which decouples them too.

I am afraid that you need to decide which one the right solution is for your project.


问:
ContactsComponent_Host.ngfactory.js? [sm]:1 ERROR TypeError: Cannot read property 'get' of undefined
I am going to develop a simple Angular 4 application. I have created a project with services, using Angular CLI and added service to the app using 'ng generate service ' command as following.

contactService :

```<code>import { Injectable } from '@angular/core';
import { Http} from '@angular/http';
import {HttpClient} from '@angular/http';
import  "rxjs/add/operator/map" ;

@Injectable()
export class ContactService {

  constructor (public http: Http) {}

 getContact() {

  return this.http.get('http://localhost:8080/contacts').map(resp=>resp.json());

}
</code>```

contacts.component :

```<code>import { Component, Injector, OnInit } from '@angular/core';
import { Http} from '@angular/http';
import  "rxjs/add/operator/map" ;
import { ContactService } from '../services/contact.service';
// import {HTTP_PROVIDERS} from '@angular/http';

@Component({
  selector: 'app-c',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css'],
  providers: [ContactService]
})

export class ContactsComponent implements OnInit {
pageContact:any;
motCle:string = "";
  constructor(public http: Http, public contactservice : ContactService) { }

  ngOnInit() {

    this.contactservice.getContact().subscribe(data => {this.pageContact = data},err=>{console.log(err)});

  }

}
</code>```

AppModule :

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { Http} from '@angular/http';
// import { ContactService } from '../services/contact.service';

import { AppComponent } from './app.component';
import { ContactsComponent } from './contacts/contacts.component';
import { AboutComponent } from './about/about.component';

const appRoutes : Routes = [
  {path : 'about', component : AboutComponent},
  {path : 'contacts', component : ContactsComponent},
  {path : '', redirectTo : '/about', pathMatch:'full'}
];

@NgModule({
  declarations: [
    AppComponent,
    ContactsComponent,
    AboutComponent,

  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    HttpClientModule,

  ],

  // providers: [ContactService],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

Am I doing anything wrong? Any help would be appreciated. Thanks in advance.

答:
You have wrong accessing:

```<code>@Injectable()
export class ContactService {

constructor (public http: HttpClient) {} //Not Http

getContact() {

  return  this.http.get('http://localhost:8080/contacts')
    .map(resp=>resp.json());
 }
</code>```

If you are using Angular 4.3+ , you are no need to use HttpModule, Http, use HttpClientModule, HttpClient instead of this

Body:
I am going to develop a simple Angular 4 application. I have created a project with services, using Angular CLI and added service to the app using 'ng generate service ' command as following.

contactService :

import { Injectable } from '@angular/core';
import { Http} from '@angular/http';
import {HttpClient} from '@angular/http';
import  "rxjs/add/operator/map" ;

@Injectable()
export class ContactService {

  constructor (public http: Http) {}

 getContact() {

  return this.http.get('http://localhost:8080/contacts').map(resp=>resp.json());

}

contacts.component :

import { Component, Injector, OnInit } from '@angular/core';
import { Http} from '@angular/http';
import  "rxjs/add/operator/map" ;
import { ContactService } from '../services/contact.service';
// import {HTTP_PROVIDERS} from '@angular/http';

@Component({
  selector: 'app-c',
  templateUrl: './contacts.component.html',
  styleUrls: ['./contacts.component.css'],
  providers: [ContactService]
})

export class ContactsComponent implements OnInit {
pageContact:any;
motCle:string = "";
  constructor(public http: Http, public contactservice : ContactService) { }

  ngOnInit() {

    this.contactservice.getContact().subscribe(data => {this.pageContact = data},err=>{console.log(err)});

  }

}

AppModule :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { Http} from '@angular/http';
// import { ContactService } from '../services/contact.service';

import { AppComponent } from './app.component';
import { ContactsComponent } from './contacts/contacts.component';
import { AboutComponent } from './about/about.component';

const appRoutes : Routes = [
  {path : 'about', component : AboutComponent},
  {path : 'contacts', component : ContactsComponent},
  {path : '', redirectTo : '/about', pathMatch:'full'}
];

@NgModule({
  declarations: [
    AppComponent,
    ContactsComponent,
    AboutComponent,

  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
    HttpModule,
    HttpClientModule,

  ],

  // providers: [ContactService],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Am I doing anything wrong? Any help would be appreciated. Thanks in advance.

Body:
You have wrong accessing:

@Injectable()
export class ContactService {

constructor (public http: HttpClient) {} //Not Http

getContact() {

  return  this.http.get('http://localhost:8080/contacts')
    .map(resp=>resp.json());
 }

If you are using Angular 4.3+ , you are no need to use HttpModule, Http, use HttpClientModule, HttpClient instead of this


问:
Maven/Tycho SWTBot Eclipse RCP
I would like to run my UI Tests SWTBot with Maven/Tycho and Tycho can't get my .product.
This my log:

```<code>!ENTRY org.eclipse.equinox.app 0 0 2017-12-02 16:36:32.573
!MESSAGE Product tychodemo.bundle.product could not be found.
***WARNING: Display must be created on main thread due to Cocoa restrictions.

!ENTRY org.eclipse.osgi 4 0 2017-12-02 16:36:32.760
!MESSAGE Application error
!STACK 1
...
</code>```

This is my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>tychodemo.swtbot.test</artifactId>
  <packaging>eclipse-test-plugin</packaging>
  <parent>
    <groupId>tychodemo</groupId>
    <artifactId>tychodemo.parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <relativePath>../tychodemo.parent</relativePath>
  </parent>
  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-surefire-plugin</artifactId>
        <version>${tycho-version}</version>
        <configuration>
          <useUIHarness>true</useUIHarness>
          <useUIThread>false</useUIThread>

          <product>tychodemo.bundle.product</product>
          <application>org.eclipse.e4.ui.workbench.swt.E4Application</application>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>```

Is it the right place to put my .product?

Thank you,
Antoine

答:
The error seems to be indicative of an issue on the MacOS platform.

To launch the tests on a mac you need to specify the -XstartOnFirstThread command line option in a separate profile:

```<code><profile>
  <id>macosx</id>
  <activation>
    <os>
      <name>macosx</name>
      <family>mac</family>
    </os>
  </activation>
  <properties>
    <ui.test.vmargs>-Xmx512m -XX:MaxPermSize=256m -XstartOnFirstThread</ui.test.vmargs>
  </properties>
</profile>
</code>```

Title: Maven/Tycho SWTBot Eclipse RCP

Body:
I would like to run my UI Tests SWTBot with Maven/Tycho and Tycho can't get my .product.
This my log:

!ENTRY org.eclipse.equinox.app 0 0 2017-12-02 16:36:32.573
!MESSAGE Product tychodemo.bundle.product could not be found.
***WARNING: Display must be created on main thread due to Cocoa restrictions.

!ENTRY org.eclipse.osgi 4 0 2017-12-02 16:36:32.760
!MESSAGE Application error
!STACK 1
...

This is my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <artifactId>tychodemo.swtbot.test</artifactId>
  <packaging>eclipse-test-plugin</packaging>
  <parent>
    <groupId>tychodemo</groupId>
    <artifactId>tychodemo.parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <relativePath>../tychodemo.parent</relativePath>
  </parent>
  <build>
    <plugins>
      <plugin>
        <groupId>org.eclipse.tycho</groupId>
        <artifactId>tycho-surefire-plugin</artifactId>
        <version>${tycho-version}</version>
        <configuration>
          <useUIHarness>true</useUIHarness>
          <useUIThread>false</useUIThread>

          <product>tychodemo.bundle.product</product>
          <application>org.eclipse.e4.ui.workbench.swt.E4Application</application>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Is it the right place to put my .product?

Thank you,
Antoine

Body:
The error seems to be indicative of an issue on the MacOS platform.

To launch the tests on a mac you need to specify the -XstartOnFirstThread command line option in a separate profile:

<profile>
  <id>macosx</id>
  <activation>
    <os>
      <name>macosx</name>
      <family>mac</family>
    </os>
  </activation>
  <properties>
    <ui.test.vmargs>-Xmx512m -XX:MaxPermSize=256m -XstartOnFirstThread</ui.test.vmargs>
  </properties>
</profile>


问:
How to replicate ora-12155 Exception?
How can I replicate Ora-12155 Exception?

I want to replicate Ora-12155 Exception in a Test environment using Spring JDBCtemplate.

答:
What do you mean by "replicate". In general you can raise any exception like this:</p>

```<code>DECLARE
    INTERNAL_TNS_ERROR EXCEPTION;
    PRAGMA EXCEPTION_INIT(INTERNAL_TNS_ERROR, -12155);
BEGIN
    NULL;
    RAISE INTERNAL_TNS_ERROR;
END;
</code>```

Title: How to replicate ora-12155 Exception?

Body:
What do you mean by "replicate". In general you can raise any exception like this:

DECLARE
    INTERNAL_TNS_ERROR EXCEPTION;
    PRAGMA EXCEPTION_INIT(INTERNAL_TNS_ERROR, -12155);
BEGIN
    NULL;
    RAISE INTERNAL_TNS_ERROR;
END;


问:
Changing the Value of an Input Box with JS
I am trying to change the value of an input box to 3.  What I have done so far is create the variable for an input box.  This variable is named "input".  Currently, the value of the input box is "20".  When I type "input" into console, here is what is returned:

```<code><input value = "20">
</code>```

Then I try to change the value of the input box by doing this:

```<code>input.value = 3;
</code>```

Then when I type "input" into console, it tells me that the value is still 20.

```<code><input value = "20">
</code>```

So my question is, how can I make it return the value of 3 to me?

答:
Here is that you can do:

In your HTML, give your input an ID

```<code><input id="input1" value = "20">
</code>```

Then in your JS:

```<code>document.getElementById("input1").value = 3;
</code>```

Body:
I am trying to change the value of an input box to 3.  What I have done so far is create the variable for an input box.  This variable is named "input".  Currently, the value of the input box is "20".  When I type "input" into console, here is what is returned:

<input value = "20">

Then I try to change the value of the input box by doing this:

input.value = 3;

Then when I type "input" into console, it tells me that the value is still 20.

<input value = "20">

So my question is, how can I make it return the value of 3 to me?

Body:
Here is that you can do:

In your HTML, give your input an ID

<input id="input1" value = "20">

Then in your JS:

document.getElementById("input1").value = 3;


问:
Can I predict on continues target value in keras?
This is the example of data that I have.
Length of df is 1778360.
The search term is the queries that people type on Search Engine.
CR (Conversion Rate) is a continuous number. It starts from 0 to no limit.

```<code>    Search term                         CR
0   asos french connection lined mac    100
1   hugo boss polo black                50
2   women's pale grey trousers uk       47
3   military jacket                     8
4   girls adidas red tracksuit top      0
</code>```

What I want is to predict the CR with the text as the input.

```<code>texts = df['Search term']
tags = df['CR']
num_max = 1000

# preprocess
le = LabelEncoder()
tags = le.fit_transform(tags)
token = Tokenizer(num_words=num_max)
token.fit_on_texts(texts)
mat_texts = token.texts_to_matrix(texts, mode='freq')
print(tags[:5])
print(mat_texts[:5])
print(tags.shape, mat_texts.shape)

# split data to train and test
X_train, X_test, y_train, y_test = train_test_split(mat_texts, tags, train_size=0.8, random_state=1)

# create model
model = Sequential()
model.add(Dense(512, input_dim=num_max, kernel_initializer='normal', activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(100, kernel_initializer='normal', activation='softmax'))

# compile model
model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

# fit the model
model.fit(X_train, y_train, epochs=10, batch_size=32, verbose=0, validation_data=(X_test, y_test))

# evaluate the model
train_scores = model.evaluate(X_train, y_train, verbose=0)
print("Train %s: %.2f%%" % (model.metrics_names[1], train_scores[1]*100))
test_scores = model.evaluate(X_test, y_test, verbose=0)
print("Test %s: %.2f%%" % (model.metrics_names[1], test_scores[1]*100))
</code>```

I got this as result:
Train acc: 82.53%
Test acc: 82.48%

I'm not sure if the last dense and the loss function is correct. This is more like a linear regression but I couldn't find a suitable keras model for linear regression.

Can somebody help, please? Thanks.

P.s. I'm very new to deep learning and neural network.

答: For regression problem, the activation of the last dense layer should be 'linear' or 'sigmoid', and the loss should be 'mean_squared_error'.

Body:
This is the example of data that I have.
Length of df is 1778360.
The search term is the queries that people type on Search Engine.
CR (Conversion Rate) is a continuous number. It starts from 0 to no limit.

    Search term                         CR
0   asos french connection lined mac    100
1   hugo boss polo black                50
2   women's pale grey trousers uk       47
3   military jacket                     8
4   girls adidas red tracksuit top      0

What I want is to predict the CR with the text as the input.

texts = df['Search term']
tags = df['CR']
num_max = 1000

# preprocess
le = LabelEncoder()
tags = le.fit_transform(tags)
token = Tokenizer(num_words=num_max)
token.fit_on_texts(texts)
mat_texts = token.texts_to_matrix(texts, mode='freq')
print(tags[:5])
print(mat_texts[:5])
print(tags.shape, mat_texts.shape)

# split data to train and test
X_train, X_test, y_train, y_test = train_test_split(mat_texts, tags, train_size=0.8, random_state=1)

# create model
model = Sequential()
model.add(Dense(512, input_dim=num_max, kernel_initializer='normal', activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(100, kernel_initializer='normal', activation='softmax'))

# compile model
model.compile(loss='sparse_categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])

# fit the model
model.fit(X_train, y_train, epochs=10, batch_size=32, verbose=0, validation_data=(X_test, y_test))

# evaluate the model
train_scores = model.evaluate(X_train, y_train, verbose=0)
print("Train %s: %.2f%%" % (model.metrics_names[1], train_scores[1]*100))
test_scores = model.evaluate(X_test, y_test, verbose=0)
print("Test %s: %.2f%%" % (model.metrics_names[1], test_scores[1]*100))

I got this as result:
Train acc: 82.53%
Test acc: 82.48%

I'm not sure if the last dense and the loss function is correct. This is more like a linear regression but I couldn't find a suitable keras model for linear regression.

Can somebody help, please? Thanks.

P.s. I'm very new to deep learning and neural network.


问:
Sending email to customer on cancelled order in Woocommerce
I am trying to send an email to the client when an order gets cancelled. By default, woocommerce only sends this email only to the admin of the site.
This code has solved the issue for related posts on the web:

```<code>function wc_cancelled_order_add_customer_email( $recipient, $order ){
   return $recipient . ',' . $order->billing_email;
}
add_filter( 'woocommerce_email_recipient_cancelled_order', 'wc_cancelled_order_add_customer_email', 10, 2 );
add_filter( 'woocommerce_email_recipient_failed_order', 'wc_cancelled_order_add_customer_email', 10, 2 );
</code>```

However, it seems like woocommerce removed those filter hooks completely.
Is there any way of doing this?

Thanks in advance!

答:
In this custom function hooked in woocommerce_order_status_changed action hook, I am targeting "cancelled" and "failed" orders sending an the corresponding email notification to the customer (as admin will receive it on his side by WooCommerce automated notifications):

```<code>add_action('woocommerce_order_status_changed', 'send_custom_email_notifications', 10, 4 );
function send_custom_email_notifications( $order_id, $old_status, $new_status, $order ){
    if ( $new_status == 'cancelled' || $new_status == 'failed' ){
        $wc_emails = WC()->mailer()->get_emails(); // Get all WC_emails objects instances
        $customer_email = $order->get_billing_email(); // The customer email
    }

    if ( $new_status == 'cancelled' ) {
        // change the recipient of this instance
        $wc_emails['WC_Email_Cancelled_Order']->recipient = $customer_email;
        // Sending the email from this instance
        $wc_emails['WC_Email_Cancelled_Order']->trigger( $order_id );
    }
    elseif ( $new_status == 'failed' ) {
        // change the recipient of this instance
        $wc_emails['WC_Email_Failed_Order']->recipient = $customer_email;
        // Sending the email from this instance
        $wc_emails['WC_Email_Failed_Order']->trigger( $order_id );
    }
}
</code>```

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This should works in WooCommerce 3+

If you need, instead of changing the email, you can add it, to existing recipients:

```<code>// Add a recipient in this instance
$wc_emails['WC_Email_Failed_Order']->recipient .= ',' . $customer_email;
</code>```

Related answer: Send an email notification when order status change from pending to cancelled

ContentLicense: CC BY-SA 4.0

Body:
I am trying to send an email to the client when an order gets cancelled. By default, woocommerce only sends this email only to the admin of the site.
This code has solved the issue for related posts on the web:

function wc_cancelled_order_add_customer_email( $recipient, $order ){
   return $recipient . ',' . $order->billing_email;
}
add_filter( 'woocommerce_email_recipient_cancelled_order', 'wc_cancelled_order_add_customer_email', 10, 2 );
add_filter( 'woocommerce_email_recipient_failed_order', 'wc_cancelled_order_add_customer_email', 10, 2 );

However, it seems like woocommerce removed those filter hooks completely.
Is there any way of doing this?

Thanks in advance!

Body:
In this custom function hooked in woocommerce_order_status_changed action hook, I am targeting "cancelled" and "failed" orders sending an the corresponding email notification to the customer (as admin will receive it on his side by WooCommerce automated notifications):

add_action('woocommerce_order_status_changed', 'send_custom_email_notifications', 10, 4 );
function send_custom_email_notifications( $order_id, $old_status, $new_status, $order ){
    if ( $new_status == 'cancelled' || $new_status == 'failed' ){
        $wc_emails = WC()->mailer()->get_emails(); // Get all WC_emails objects instances
        $customer_email = $order->get_billing_email(); // The customer email
    }

    if ( $new_status == 'cancelled' ) {
        // change the recipient of this instance
        $wc_emails['WC_Email_Cancelled_Order']->recipient = $customer_email;
        // Sending the email from this instance
        $wc_emails['WC_Email_Cancelled_Order']->trigger( $order_id );
    }
    elseif ( $new_status == 'failed' ) {
        // change the recipient of this instance
        $wc_emails['WC_Email_Failed_Order']->recipient = $customer_email;
        // Sending the email from this instance
        $wc_emails['WC_Email_Failed_Order']->trigger( $order_id );
    }
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This should works in WooCommerce 3+

If you need, instead of changing the email, you can add it, to existing recipients:

// Add a recipient in this instance
$wc_emails['WC_Email_Failed_Order']->recipient .= ',' . $customer_email;

Related answer: Send an email notification when order status change from pending to cancelled


问:
How to do a multi-line class attribute with slim-rails?
Element needs a lot of class attributes but I don't want them to be chucked in one line, as the line length will be too long and it would require heavy side scrolling.

Preferably, I don't want to use the delimiter syntax [class= ""] as this syntax would be entirely inconsistent with the whole file.

I tried doing this way:

```<code>span.select2.select2-container.select2-container--default \
  .select2-container--below.select2-container--focus
</code>```

But the \ and the remaining class attribute names just gets rendered as text.

Is there any possible way that I can chain class attributes in slim-lang a la ruby style, like this?

```<code>span.select2.select2-container.select2-container--default
    .additional-cssklass
    .whatever-class
</code>```

答:
You need to use splat attribute that allows you to turn a hash into attribute/value pairs and then append a backslash to do multiline : </p>

```<code>.first-class *{class: ["second-class", \
                       "third-class"]}
</code>```

Body:
Element needs a lot of class attributes but I don't want them to be chucked in one line, as the line length will be too long and it would require heavy side scrolling.

Preferably, I don't want to use the delimiter syntax [class= ""] as this syntax would be entirely inconsistent with the whole file.

I tried doing this way:

span.select2.select2-container.select2-container--default \
  .select2-container--below.select2-container--focus

But the \ and the remaining class attribute names just gets rendered as text.

Is there any possible way that I can chain class attributes in slim-lang a la ruby style, like this?

span.select2.select2-container.select2-container--default
    .additional-cssklass
    .whatever-class

Body:
You need to use splat attribute that allows you to turn a hash into attribute/value pairs and then append a backslash to do multiline :

.first-class *{class: ["second-class", \
                       "third-class"]}


问:
binarize input for pytorch
may I ask how to make data loaded in pytorch become binarized once it is loaded?
Like Tensorflow can done this through:

```<code>train_data  = mnist.input_data.read_data_sets(data_directory, one_hot=True)
</code>```

How can pytorch achieve the one_hot=True effect.

The data_loader I have now is:

```<code>torch.set_default_tensor_type('torch.FloatTensor')
train_loader = torch.utils.data.DataLoader(
        datasets.MNIST('data/', train=True, download=True,
                       transform=transforms.Compose([
                         # transforms.RandomHorizontalFlip(),
                           transforms.ToTensor()])),
        batch_size=batch_size, shuffle=False)
</code>```

I want to make data in train_loader be binarized.
Now what I am doing is: After loading the data,

```<code>for data,_ in train_loader:
    torch.round(data)
    data = Variable(data)
</code>```

Use the torch.round() function. Is this correct?

答:
The one-hot encoding idea is used for classification. It sounds like you are trying to create an autoencoder perhaps.

If you are creating an autoencoder then there is no need to round as BCELoss can handle values between 0 and 1. Note when training it is better not to apply the sigmoid and instead to use BCELossWithLogits as it provides numerical stability.

Here is an example of an autoencoder with MNIST

If instead you are attempting to do classifcation then there is no need for a one hot vector, you simply output the number of neurons equal to the number of classes i.e for MNIST output 10 neurons and then pass it to CrossEntropyLoss along with a LongTensor with corresponding expected class values

Here is an example of classification on MNIST

Title: binarize input for pytorch

Body:
may I ask how to make data loaded in pytorch become binarized once it is loaded?
Like Tensorflow can done this through:

train_data  = mnist.input_data.read_data_sets(data_directory, one_hot=True)

How can pytorch achieve the one_hot=True effect.

The data_loader I have now is:

torch.set_default_tensor_type('torch.FloatTensor')
train_loader = torch.utils.data.DataLoader(
        datasets.MNIST('data/', train=True, download=True,
                       transform=transforms.Compose([
                         # transforms.RandomHorizontalFlip(),
                           transforms.ToTensor()])),
        batch_size=batch_size, shuffle=False)

I want to make data in train_loader be binarized.
Now what I am doing is: After loading the data,

for data,_ in train_loader:
    torch.round(data)
    data = Variable(data)

Use the torch.round() function. Is this correct?


问:
Unsupported method: BaseConfig.getApplicationIdSuffix()
So I'm reading Android 6 for Programmers: An App-Driven Approach and the first two app examples I had no issues with the examples, this time the FlagQuiz example when loaded in Android Studio 3.0 Canary-3 I'm getting this error which isn't letting me build the project:

Error:Unsupported method: BaseConfig.getApplicationIdSuffix().
  The version of Gradle you connect to does not support that method.
  To resolve the problem you can change/upgrade the target version of Gradle you connect to.
  Alternatively, you can ignore this exception and read other information from the model.

You can download the source from the book site here to test with the same code base that I'm testing from.

答:
Change your gradle version or update it

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
}
</code>```

alt+enter and choose "replace with specific version".

Body:
Change your gradle version or update it

dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
}

alt+enter and choose "replace with specific version".


问:
What does the "X2[,Out]" and " = <ufunc 'copysign'>" mean in this doc page?
numpy.copysign

I know how this function works, but I can't fully understand what this title description mean.

Like

x2[, out]

what does this parameter mean? Is it a datatype in python?

and

" = <  ufunc 'copysign'> "

I have see something like this several times when I look through the documents.
Can anybody help? Thank you so much.

答:
The brackets are standard Python documentation syntax for optional parameters to a function call. From the Python Language Reference Introduction:

a phrase enclosed in square brackets ([ ]) means zero or one occurrences (in other words, the enclosed phrase is optional)

You'll notice it all over the place in Python & its libraries' documentation.

The = <ufunc 'func_name'> bit is to let you know that the function is an instance of the numpy.ufunc class. From the NumPy docs on Universal Functions:

A universal function (or ufunc for short) is a function that operates
  on ndarrays in an element-by-element fashion, supporting array
  broadcasting, type casting, and several other standard features. That
  is, a ufunc is a “vectorized” wrapper for a function that takes a
  fixed number of scalar inputs and produces a fixed number of scalar
  outputs.

In NumPy, universal functions are instances of the numpy.ufunc class. Many of the built-in functions are implemented in compiled C code, but ufunc instances can also be produced using the frompyfunc factory function.


答:
Try the following way:

var el = document.getElementsByTagName('input');
el[0].setAttribute('value', '3');
console.log(document.getElementsByTagName('input')[0])```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input value = "20"></code>```

Title: Changing the Value of an Input Box with JS

Body:
Try the following way:

var el = document.getElementsByTagName('input');
el[0].setAttribute('value', '3');
console.log(document.getElementsByTagName('input')[0])

<input value = "20">


答:
Then when I type "input" into console, it tells me that the value is still 20.

```<code><input value = "20">
</code>```

This is a common point of confusion.

The value attribute that the console is showing you is not the same as the input's current value. It's the input's default value. The current value isn't held in an attribute at all.

You're successfully setting the inputs current value by assigning to value. If you wanted to change its value attribute, you'd do that by assigning to its defaultValue property, or by using setAttribute.

```<code>input.defaultValue = 3;
// or
input.setAttribute("value", 3);
</code>```

...assuming (as it appears from your question), that input is a reference to the input in question.

Body:
Then when I type "input" into console, it tells me that the value is still 20.

<input value = "20">

This is a common point of confusion.

The value attribute that the console is showing you is not the same as the input's current value. It's the input's default value. The current value isn't held in an attribute at all.

You're successfully setting the inputs current value by assigning to value. If you wanted to change its value attribute, you'd do that by assigning to its defaultValue property, or by using setAttribute.

input.defaultValue = 3;
// or
input.setAttribute("value", 3);

...assuming (as it appears from your question), that input is a reference to the input in question.


问:
Disable dropdown option after selecting (even for new visitors)
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superhero's. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left. These six will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

```<code><form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">
                                                <div class="cc-m-form-loading"></div>

                                                <div class="cc-m-form-view-sortable">
                                                    <div class="cc-m-form-view-element cc-m-form-select" data-action="element" required>
                                                        <label for="ma6b8be54cf86a6410">
    <div>Kies welke held jouw team is!</div>
    </label>
                                                        <div class="cc-m-form-view-input-wrapper">
                                                            <select name="teamnaam" class="cc-m-form-element-input" required>
                                                                <option value="" selected disabled hidden>Selecteer</option>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="MegaMindy">Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="TheHulk">The Hulk</option>
<option value="HitGirl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select></div></div>
<input type="submit" value="Naar betalen" data-action="formButton">
</code>```

So if you make a selection and submit the form, it wil link to inschrijfformulie.php, this .php file contains:

```<code><?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
 exit;
?>
</code>```

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

答:
There is only one way to do it and it is related with server side. First you pick the user's choice:

Let's assume that your selectbox id is "heroes-combo" and you are using jQuery.

```<code>// this gives you the selected option's value.
$("#heroes-combo option:selected").attr("value");
</code>```

Now send it to server side via ajax.

When a user enters the website you need to query your database which heroes are already selected. Lets say the database returns Ironman.

You then need to mark it as disabled like this:

```<code>$("#heroes-combo option[value='Ironman']").attr("disabled", true)
</code>```

Body:
I'm working on a website where people can sign up for an event. We've got 8 different teams, based on superhero's. Every team should choose 1 of the 8 superheroes, but non of them should choose the same one.

Is it possible to write some code to disable an option (for every new visitor of the website) after someone has chosen that superhero?

So if 2 people has chosen a superhero, there will only be 6 choices left. These six will be visible, but non-clickable.

So my html form code is (some titles/names are Dutch;)):

<form action="inschrijfformulier.php" method="post" id="cc-m-form-6876142651" target="_blank" class="cc-m-form cc-m-form-layout-1" onsubmit="javascript: setTimeout(function(){location.reload();}, 1000);return true;">

Kies welke held jouw team is!

                                                            <select name="teamnaam" class="cc-m-form-element-input" required>
                                                                <option value="" selected disabled hidden>Selecteer</option>
<option value="Superman">Superman</option>
<option value="Batman">Batman</option>
<option value="X-Men">X-Men</option>
<option value="MegaMindy">Mega Mindy</option>
<option value="Spiderman">Spiderman</option>
<option value="TheHulk">The Hulk</option>
<option value="HitGirl">Hit Girl</option>
<option value="Meerminman">Meerminman</option></select>

<input type="submit" value="Naar betalen" data-action="formButton">

So if you make a selection and submit the form, it wil link to inschrijfformulie.php, this .php file contains:

<?php
$name = $_POST['teamnaam'];
$email = $_POST['email'];
$rekeninghouder = $_POST['rekeninghouder'];
$aantalspelers = $_POST['aantalspelers'];
$spelernamen = $_POST['spelernamen'];
$formcontent="Teamnaam: $name \nEmail: $email \nRekeninghouder: $rekeninghouder \nAantal spelers: $aantalspelers \nSpelers: $spelernamen";
$recipient = "info@sidekickevents.nl";
$subject = "Inschrijfformulier";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
header("Location: https://www.ticketkantoor.nl/shop/bubbelvoetbal");
 exit;
?>

This makes sure that I'm getting an email with the information they fill in. This works great, I also can see which superhero they've chosen.
Hopefully someone can explain it, because I'm new to PHP!
Thanks in advance!

Body:
There is only one way to do it and it is related with server side. First you pick the user's choice:

Let's assume that your selectbox id is "heroes-combo" and you are using jQuery.

// this gives you the selected option's value.
$("#heroes-combo option:selected").attr("value");

Now send it to server side via ajax.

When a user enters the website you need to query your database which heroes are already selected. Lets say the database returns Ironman.

You then need to mark it as disabled like this:

$("#heroes-combo option[value='Ironman']").attr("disabled", true)


问:
Heroku does not see my fragments
I successfully deployed my Spring app on Heroku, but when I try to test my app in action I receive
Error resolving template "/fragments/head.html", template might not exist or might not be accessible by any of the configured Template Resolvers (home:4) Error.
It's odd, because locally my app works well without any problem.

Home.html code:

```<code><!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <div th:replace="/fragments/head.html"></div>
  <title>Personal blog - Home</title>
</head>
<body>
<div class="container">
  <div th:replace="/fragments/header" th:class="row"></div>

  <div class="container">
    <div class="container border w-100 post" th:each="post : ${posts}">
      <div class="container">
        <h1 class="display-5">
          <a th:href="@{/post/} + ${post.id}" th:text="${post.title}"></a>
        </h1>
        <small class="text-muted" th:text="${post.creationDate}"></small>
      </div>
      <div class="container">
        <p class="lead text-justify" th:text="${post.contents}"></p>
      </div>
    </div>
    <nav>
      <ul class="pagination justify-content-center" th:if="${lastPageIndex} gt 1">
        <li class="page-item">
          <a class="page-link"
             th:if="${currentPage gt 1}"
             th:href="@{/home/} + ${currentPage-1}">Previous</a>
        </li>
        <li class="page-item">
          <a class="page-link" th:if="${currentPage-3} ge 1"
             th:href="@{/home/} + ${currentPage-3}"
             th:text="${currentPage-3}"></a>
        </li>
        <li class="page-item">
          <a class="page-link"
             th:if="${currentPage-2} ge 1"
             th:href="@{/home/} + ${currentPage-2}"
             th:text="${currentPage-2}"></a>
        </li>
        <li class="page-item">
          <a class="page-link"
             th:if="${currentPage-1} ge 1"
             th:href="@{/home/} + ${currentPage-1}"
             th:text="${currentPage-1}"></a>
        </li>
        <li class="page-item">
          <a class="page-link" th:text="${currentPage}"></a>
        </li>
        <li class="page-item">
          <a class="page-link"
             th:if="${currentPage+1} le ${lastPageIndex}"
             th:href="@{/home/} + ${currentPage+1}"
             th:text="${currentPage+1}"></a>
        </li>
        <li class="page-item">
          <a class="page-link"
             th:if="${currentPage+2} le ${lastPageIndex}"
             th:href="@{/home/} + ${currentPage+2}"
             th:text="${currentPage+2}"></a>
        </li>
        <li class="page-item">
          <a class="page-link"
             th:if="${currentPage+3} le ${lastPageIndex}"
             th:href="@{/home/} + ${currentPage+3}"
             th:text="${currentPage+3}"></a>
        </li>
        <li class="page-item">
          <a class="page-link"
             th:if="${currentPage} lt ${lastPageIndex}"
             th:href="@{/home/} + ${currentPage+1}">Next</a>
        </li>
      </ul>
    </nav>
  </div>

  <div th:replace="/fragments/footer"></div>
</div>
</body>
</html>
</code>```

Head.html code:

```<code><!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
  <div th:fragment="head">
    <meta charset="UTF-8"/>
    <link rel="stylesheet" type="text/css" href="/css/style.css"/>
    <link rel="stylesheet" type="text/css" crossorigin="anonymous"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
          integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"/>
  </div>
</head>
</html>
</code>```

As you can see, my Head.html contains links to CSS files, one with bootstrap, second with my own fixes. Locally, everything works fine. Every view is loaded perfectly I got only little half-second lag between loading page and applying css to it, but I think on heroku it will be fine.

My aspp is available under this link: https://spring-personal-blog.herokuapp.com

Also entire code of my app is available in repository on github.

答:
You have invalid th:replace syntax. Should use

```<code>th:replace="fragments/head :: head"
// or
th:replace="fragments/head"  // instead of th:replace="/fragments/head"

th:replace="directory/filename :: fragmentName"
</code>```

And similar changes for every other fragment in your template

 inside you , you should probably use th:remove="tag".

```<code>//home.html
<div th:replace="fragments/head :: head" th:remove="tag"></div>

//fragments/head.html
<head th:fragment="head">...</head>
</code>```

PS. I played with your github project and its kinda strange that your notation actually works on localhost but breaks on heroku. And the above fixes solved it for me on heroku DEMO. Btw I also had to put passwordEncoder bean in different config file, because it could not start on heroku otherwise

Title: Heroku does not see my fragments

Body:
I successfully deployed my Spring app on Heroku, but when I try to test my app in action I receive
Error resolving template "/fragments/head.html", template might not exist or might not be accessible by any of the configured Template Resolvers (home:4) Error.
It's odd, because locally my app works well without any problem.

Home.html code:

<!DOCTYPE html>

  <title>Personal blog - Home</title>

          Previous

          Next

Head.html code:

<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <link rel="stylesheet" type="text/css" href="/css/style.css"/>
    <link rel="stylesheet" type="text/css" crossorigin="anonymous"
          href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css"
          integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb"/>

As you can see, my Head.html contains links to CSS files, one with bootstrap, second with my own fixes. Locally, everything works fine. Every view is loaded perfectly I got only little half-second lag between loading page and applying css to it, but I think on heroku it will be fine.

My aspp is available under this link: https://spring-personal-blog.herokuapp.com

Also entire code of my app is available in repository on github.

Body:
You have invalid th:replace syntax. Should use

th:replace="fragments/head :: head"
// or
th:replace="fragments/head"  // instead of th:replace="/fragments/head"

th:replace="directory/filename :: fragmentName"

And similar changes for every other fragment in your template

<div> inside you <head>, you should probably use th:remove="tag".

//home.html
<div th:replace="fragments/head :: head" th:remove="tag"></div>

//fragments/head.html
<head th:fragment="head">...</head>

PS. I played with your github project and its kinda strange that your notation actually works on localhost but breaks on heroku. And the above fixes solved it for me on heroku DEMO. Btw I also had to put passwordEncoder bean in different config file, because it could not start on heroku otherwise


问:
Kotlin - Transform value at initialisation
i'm new in kotlin and i want to know if we can transform a content value at initialisation : with this example :

```<code>@Document
data class Category(
    @Id val id: Id? = null,
    val label: String
)
</code>```

Category is a document (entity for mongodb) and when i'm instanciating this object, i want to transform label property in uppercase. How can i do that to stay idiomatic with the language ? The point is to keep the immutable properties of the val keyword.

```<code>val categ = Category(label = "Test")
println(categ.label) // --> TEST
</code>```

Thanks.

答:
You can encapsulate the "upperCasing" into a factory:

```<code>data class Category constructor(val label: String) {

    init {
        if (label != label.toUpperCase()) {
            throw IllegalStateException("Label must be uppercase")
        }
    }

    companion object {
        fun createInstance(str: String) = Category(str.toUpperCase())
    }

}
</code>```

The init block ensures, that clients don't create unwanted instances with non-upper labels (which should be documented).

Create an instance like this:

val instance = Category.createInstance("xy")

You might want to make explicit that you do transformations if the parameter is not upper case already by naming the factory accordingly, e.g. withTransformedLabel or simply add some documentation ;-)

Body:
i'm new in kotlin and i want to know if we can transform a content value at initialisation : with this example :

@Document
data class Category(
    @Id val id: Id? = null,
    val label: String
)

Category is a document (entity for mongodb) and when i'm instanciating this object, i want to transform label property in uppercase. How can i do that to stay idiomatic with the language ? The point is to keep the immutable properties of the val keyword.

val categ = Category(label = "Test")
println(categ.label) // --> TEST

Thanks.

Body:
You can encapsulate the "upperCasing" into a factory:

data class Category constructor(val label: String) {

    init {
        if (label != label.toUpperCase()) {
            throw IllegalStateException("Label must be uppercase")
        }
    }

    companion object {
        fun createInstance(str: String) = Category(str.toUpperCase())
    }

}

The init block ensures, that clients don't create unwanted instances with non-upper labels (which should be documented).

Create an instance like this:

val instance = Category.createInstance("xy")

You might want to make explicit that you do transformations if the parameter is not upper case already by naming the factory accordingly, e.g. withTransformedLabel or simply add some documentation ;-)


问:
MS- Access VBA Converting multiple characters to Asc
For a homework project I am trying to enter characters in a single textbox as (eg:"AbC" no spaces) and have the output in a captioned label as the corresponding ASCII value written out with commas and spaces. (eg: 65, 98, 67)

```<code>Private Sub cmdCode_Click()
Dim codeInt As Integer
strInput = txtInput.value
codeInt = Asc(strInput)
lblAnswer.Caption = codeInt & ", "
End Sub
</code>```

I would like the result to look like: 65, 98, 67

I'm getting no errors but only receiving "65," as my output.

答:
This can be done for generic usage - and a little smarter:

```<code>Public Function StrToAscList( _
    ByVal Text As String) _
    As String

    Dim Chars() As Byte
    Dim Item    As Integer
    Dim List    As String

    Chars() = StrConv(Text, vbFromUnicode)
    For Item = LBound(Chars) To UBound(Chars)
        If Item > 0 Then List = List & ", "
        List = List & CStr(Chars(Item))
    Next

    StrToAscList = List

End Function
</code>```

Then:

```<code>Me!lblAnswer.Caption = StrToAscList(strInput)
</code>```

Body:
For a homework project I am trying to enter characters in a single textbox as (eg:"AbC" no spaces) and have the output in a captioned label as the corresponding ASCII value written out with commas and spaces. (eg: 65, 98, 67)

Private Sub cmdCode_Click()
Dim codeInt As Integer
strInput = txtInput.value
codeInt = Asc(strInput)
lblAnswer.Caption = codeInt & ", "
End Sub

I would like the result to look like: 65, 98, 67

I'm getting no errors but only receiving "65," as my output.

Body:
This can be done for generic usage - and a little smarter:

Public Function StrToAscList( _
    ByVal Text As String) _
    As String

    Dim Chars() As Byte
    Dim Item    As Integer
    Dim List    As String

    Chars() = StrConv(Text, vbFromUnicode)
    For Item = LBound(Chars) To UBound(Chars)
        If Item > 0 Then List = List & ", "
        List = List & CStr(Chars(Item))
    Next

    StrToAscList = List

End Function

Then:

Me!lblAnswer.Caption = StrToAscList(strInput)


问:
how to display 3 random pictures out of 8 using bash
I have 8 images in a directory.

the path is /blabla.com/img.

I need to access this path and choose 3 out of 8 randomly and display those.

If 3 pics are the same, it should echo "yeeey".

Otherwise, "neeey" and record these responses in a text file.

答:
let's array an array of distinct elements (for example 8):

```<code>array=({A..H})
</code>```

(1) use RANDOM special variable modulo the number of elements to get a random number between 0 and number-1 inclusive

```<code>number=$((RANDOM%${#array[@]}))
</code>```

the first random element is

```<code>first=${array[number]}
</code>```

remove the element from array and reassign the array to reindex without gap (declare -p array to see)

```<code>unset array[number]
array=("${array[@]}")
</code>```

restart from (1)

Body:
let's array an array of distinct elements (for example 8):

array=({A..H})

(1) use RANDOM special variable modulo the number of elements to get a random number between 0 and number-1 inclusive

number=$((RANDOM%${#array[@]}))

the first random element is

first=${array[number]}

remove the element from array and reassign the array to reindex without gap (declare -p array to see)

unset array[number]
array=("${array[@]}")

restart from (1)


问:
Send Ajaxcall to server with Arduino
I'am creating a project for which I get data from an force sensing resistor into my Arduino. Now I want to send the data from the force sensing resistor to my server trough an ajaxcall. How do I peform an ajaxcall with my arduino?
The arduino I use is a: Arduino Uno Wifi Developer Edition</p>

答:
with Arduino Uno Wifi Developer Edition factory firmware use the Arduino_Uno_WiFi_Dev_Ed_Library from Library Manager. look at RestClient example. (because arduino.org doesn't exist the example doesn't work.)

if you do not like the factory firmware because it is slow and the the library is strange, you can change to WiFi Link or AT firmware with my Uno WiFi Serial1 library

Title: Send Ajaxcall to server with Arduino


问:
how to know if a $string ends with ','?

Possible Duplicate:

Find last character in a string in PHP

How can I know if the last char of a $string is ',' ?

答:
For the micro optimizers:</p>

```<code>$string[strlen($string)-1] == ","
</code>```

Title: how to know if a $string ends with ','?

Body:
For the micro optimizers:

$string[strlen($string)-1] == ","


问:
Getting Windows OS version programmatically
I am trying to fetch Windows version with C# on my Windows 10 machine.

I always get those values (with C#\C++):

Major: 6

Minor: 2

Which is Windows 8 OS, accordingly to MSDN

C# code:

```<code>var major = OperatingSystem.Version.Major
var minor  = OperatingSystem.Version.Minor
</code>```

C++ code

```<code>void print_os_info()
{
    //http://stackoverflow.com/questions/1963992/check-windows-version
    OSVERSIONINFOW info;
    ZeroMemory(&info, sizeof(OSVERSIONINFOW));
    info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);

    LPOSVERSIONINFOW lp_info = &info;
    GetVersionEx(lp_info);

    printf("Windows version: %u.%u\n", info.dwMajorVersion, info.dwMinorVersion);
}
</code>```

Windows 10 suppose to be with those:

Major: 10

Minor: 0*

(When I am taking a dump file from running process I can see that the OS version of that file is set to 10.0)

built by: 10.0.10586.0 (th2_release.151029-1700)

What am I missing here?

答:
```<code>Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber", string.Empty).ToString()
</code>```

same code for all OSes from XP till current 10.16299,
over scenarios not properly work from windows 8

The OSVersion property reports the same version number (6.2.0.0) for both Windows 8 and Windows 8.1 and the same major and minor version number for Windows 10.

https://msdn.microsoft.com/library/system.environment.osversion.aspx

Body:
I am trying to fetch Windows version with C# on my Windows 10 machine.

I always get those values (with C#\C++):

Major: 6

Minor: 2

Which is Windows 8 OS, accordingly to MSDN

C# code:

var major = OperatingSystem.Version.Major
var minor  = OperatingSystem.Version.Minor

C++ code

void print_os_info()
{
    //http://stackoverflow.com/questions/1963992/check-windows-version
    OSVERSIONINFOW info;
    ZeroMemory(&info, sizeof(OSVERSIONINFOW));
    info.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);

    LPOSVERSIONINFOW lp_info = &info;
    GetVersionEx(lp_info);

    printf("Windows version: %u.%u\n", info.dwMajorVersion, info.dwMinorVersion);
}

Windows 10 suppose to be with those:

Major: 10

Minor: 0*

(When I am taking a dump file from running process I can see that the OS version of that file is set to 10.0)

built by: 10.0.10586.0 (th2_release.151029-1700)

What am I missing here?

Body:
Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CurrentBuildNumber", string.Empty).ToString()

same code for all OSes from XP till current 10.16299,
over scenarios not properly work from windows 8

The OSVersion property reports the same version number (6.2.0.0) for both Windows 8 and Windows 8.1 and the same major and minor version number for Windows 10.

https://msdn.microsoft.com/library/system.environment.osversion.aspx


问:
getUserMedia and MediaRecorder - 416 Requested Range Not Satisfiable
I have a HTML5 media recorder allowing users to record themselves live inside a web application, playback, and upload the recording.

It uses standard code with getUserMedia for getting a handle on the webcam and microphone, <video> to playback the webcam, and MediaRecorder to record the stream from getUserMedia.

So, to the problem...

On some Macbook Air devices, Google Chrome throws error 416 (Requested Range Not Satisfiable) when trying to playback the recorded stream in the <video> element. The issue seems so far to only occur on OSX with Chrome, but it's not occurring on all devices of that combination.

There's a Chromium bug open that references this issue but it is marked as 'Fixed'.
https://bugs.chromium.org/p/chromium/issues/detail?id=615940
I'm not convinced however that the full problem is resolved based on the ticket commentary. I recent commenter mentioned this affects Facebook Messenger too!

Have you seen this issue before, and do you know of a workaround for OSX with Chrome users that doesn't involve use Windows or use Firefox?

答:
I dug in this a little bit and found that the developers of Chromium are aware of the issue and they confirmed that it's mostly affecting Mac OS users. Seems like there is no workaround for it at the moment.

The good news is that they are shipping an update with Chrome 63, which is coming in December 2017, that should fix it.

MediaRecorder Gets into Bad State and Raises Empty Data Events

WebRTC Update 2017


问:
Laravel - Ajax : multiple inputs in 1 form
Trying to make a multi-input form, including json, text and image .. each in a specific column in the database, and update it in case of edit.

Categories is json column.
Image is image column.
rest is text.

Retrieving part is working well as it is pure Laravel, but i cannot send anything to database, whether update or create.

I'm stuck in the Json, so I didn't start the image uploading yet.

Json is generated in chrome console and is working fine, however I'm getting error 500 and the console log is giving me undefined for my variable Categories.

not sure why it is not reflecting in Laravel database, below are my Ajax, routes and Controller

jQuery

```<code>$(document).ready(function(){

var myUrl;
var Categories;
var type;

//create new task / update existing task
$("#reset").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})

e.preventDefault();

var myUrl = window.location.href;
var Categories = JSON.stringify($('#form-fields-tags').val());
var type = "POST";
console.log(Categories);
$.ajax({

type: type,
url: myUrl,
data: Categories,
dataType: 'json',
success: function (data) {
console.log(Categories);
},
error: function (data) {
var errors = $.parseJSON(data.responseText);
$.each(errors, function (key, value) {
$('#' + key).parent().addClass('error');
});
}
});
});
});
</code>```

Controller

```<code>public function postCreate(Request $request)
     {
     $post = new blog([
     'title'=>$request->input('title'),
     'Smaller'=>$request->input('Smaller'),
     'Categories'=>$request->input('Categories'),
     'BodyS'=>$request->input('BodyS'),
     'Status'=>$request->input('Status')
     ]);
$post->save();
     return redirect()->route('admin.blog')->with('info', 'Post created, Title is: ' . $request->input('title'));
      }
public function postUpdate(Request $request)
     {
     $post = blog::find($request->input('Bid'));
     $post->title = $request->input('title');
     $post->Smaller = $request->input('Smaller');
     $Cat = json_decode($post->Categories);
     $Cat = $request->input('Categories');
     $post->BodyS = $request->input('BodyS');
     $post->Status = $request->input('Status');
$post->save();
     return redirect()->route('admin.blog')->with('info', 'Post edited, new Title is: ' . $request->input('title'));
}
</code>```

Blade Blog.edit/update view

```<code> <div class="form-group">
      <label class="col-sm-3 control-label no-padding-right" for="form-field-tags">Categories</label>

      <div class="container-fluid">
      <div class="inline">
      <input type="text" name="Categories" id="form-field-tags" value="{{ $post->Categories }}" placeholder="Enter tags ..." name="Categories" />
      </div>
 </div>
 </div>
</code>```

Blade Create view

```<code> <div class="container-fluid">
 <div class="inline">
 <label>
 <input type="text" name="Categories" id="form-field-tags"value="" placeholder="Enter tags ..." name="Categories" />

 </label>

 </div>
 </div>
</code>```

Routes

```<code> Route::group(['prefix'=> 'blog'], function(){

      Route::get('/', [
      'uses'=>'BlogController@getBlogIndex',
      'as'=>'admin.blog'
      ]);
      Route::get('/create',[
      'uses'=>'BlogController@getPostCreate',
      'as'=>'admin.createB'
      ]);
      Route::get('/edit/{Bid}',[
      'uses'=>'BlogController@getPostEdit',
      'as'=>'admin.editB'
      ]);
      Route::post('/create', [
      'uses'=>'BlogController@postCreate',
      'as'=>'admin.createB'
      ]);
      Route::post('/edit', [
      'uses'=>'BlogController@postUpdate',
      'as'=>'admin.updateB'
      ]);
 });
</code>```

Thanks

答:
if you want to make a new entry in database use create method

make sure you've imported the model at the top of the controller page

rename the model class name to Blog instead of blog

change the model file name accordingly to Blog.php

then use:

```<code>use App\Blog;

public function postCreate(Request $request)
{
    Blog::create(['title'=>$request->input('title'), ..]);

    return redirect()->route('admin.blog')->with('info', 'Post created, Title is: ' . $request->input('title'));
}
</code>```

Body:
Trying to make a multi-input form, including json, text and image .. each in a specific column in the database, and update it in case of edit.

Categories is json column.
Image is image column.
rest is text.

Retrieving part is working well as it is pure Laravel, but i cannot send anything to database, whether update or create.

I'm stuck in the Json, so I didn't start the image uploading yet.

Json is generated in chrome console and is working fine, however I'm getting error 500 and the console log is giving me undefined for my variable Categories.

not sure why it is not reflecting in Laravel database, below are my Ajax, routes and Controller

jQuery

$(document).ready(function(){

var myUrl;
var Categories;
var type;

//create new task / update existing task
$("#reset").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})

e.preventDefault();

var myUrl = window.location.href;
var Categories = JSON.stringify($('#form-fields-tags').val());
var type = "POST";
console.log(Categories);
$.ajax({

type: type,
url: myUrl,
data: Categories,
dataType: 'json',
success: function (data) {
console.log(Categories);
},
error: function (data) {
var errors = $.parseJSON(data.responseText);
$.each(errors, function (key, value) {
$('#' + key).parent().addClass('error');
});
}
});
});
});

Controller

public function postCreate(Request $request)
     {
     $post = new blog([
     'title'=>$request->input('title'),
     'Smaller'=>$request->input('Smaller'),
     'Categories'=>$request->input('Categories'),
     'BodyS'=>$request->input('BodyS'),
     'Status'=>$request->input('Status')
     ]);
$post->save();
     return redirect()->route('admin.blog')->with('info', 'Post created, Title is: ' . $request->input('title'));
      }
public function postUpdate(Request $request)
     {
     $post = blog::find($request->input('Bid'));
     $post->title = $request->input('title');
     $post->Smaller = $request->input('Smaller');
     $Cat = json_decode($post->Categories);
     $Cat = $request->input('Categories');
     $post->BodyS = $request->input('BodyS');
     $post->Status = $request->input('Status');
$post->save();
     return redirect()->route('admin.blog')->with('info', 'Post edited, new Title is: ' . $request->input('title'));
}

Blade Blog.edit/update view

      Categories

      <input type="text" name="Categories" id="form-field-tags" value="{{ $post->Categories }}" placeholder="Enter tags ..." name="Categories" />

Blade Create view

 <input type="text" name="Categories" id="form-field-tags"value="" placeholder="Enter tags ..." name="Categories" />

Routes

 Route::group(['prefix'=> 'blog'], function(){

      Route::get('/', [
      'uses'=>'BlogController@getBlogIndex',
      'as'=>'admin.blog'
      ]);
      Route::get('/create',[
      'uses'=>'BlogController@getPostCreate',
      'as'=>'admin.createB'
      ]);
      Route::get('/edit/{Bid}',[
      'uses'=>'BlogController@getPostEdit',
      'as'=>'admin.editB'
      ]);
      Route::post('/create', [
      'uses'=>'BlogController@postCreate',
      'as'=>'admin.createB'
      ]);
      Route::post('/edit', [
      'uses'=>'BlogController@postUpdate',
      'as'=>'admin.updateB'
      ]);
 });

Thanks

Body:
if you want to make a new entry in database use create method

make sure you've imported the model at the top of the controller page

rename the model class name to Blog instead of blog

change the model file name accordingly to Blog.php

then use:

use App\Blog;

public function postCreate(Request $request)
{
    Blog::create(['title'=>$request->input('title'), ..]);

    return redirect()->route('admin.blog')->with('info', 'Post created, Title is: ' . $request->input('title'));
}


问:
SSE 2 and above - Why floating point data types store only 2 floating point numbers
I am attempting to optimise my code using SSE intrinsic functions. After going through the documentation, I see that there is __m128 datatype in SSE for floating point variables, capable of storing 4 float numbers. There is a __m128d in SSE2 capable of only storing 2 floating point numbers? What is the difference between these variables? Isn't SSE2 supposed to be faster than SSE?

答:
SSE instructions use 128 bit registers.

A float uses 4 bytes = 32 bits -> hence you can store 4 floats (4*32=128), these are the __m128.

A double uses 8 bytes = 64 bits -> hence you can store 2 doubles (2*64=128), these are the __m128d.

-> Further information https://felix.abecassis.me/2011/09/cpp-getting-started-with-sse/


问:
nodejs fs.exists (fs.access) has strange things happen in for-loop
my code:

```<code>for(var i=0; i<2; i++)
{
    console.log("idx: " + i);

    fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
      console.log(err ? 'no access!'+i : 'can read/write'+i);
    });

    fs.exists('/etc/passwd', (exists) => {
      console.log(exists ? 'it\'s there'+i : 'no passwd!'+i);
    });
}
</code>```

result:

idx: 0

idx: 1

no access!2

it's there2

no access!2

it's there2

why the i =2?

how can i fix it ?

答:
The key of your problem is the asyncrhony. Both fs methods are asynchronous and will be executed later, and when they are going to be executed the value of i is 2, because the loop has finished.

The easiest way to solve it is changing the declaration of the loop   var by let

```<code>for(let i=0; i<2; i++)
</code>```

It limits the scope of i to one iteration

Body:
my code:

for(var i=0; i<2; i++)
{
    console.log("idx: " + i);

    fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
      console.log(err ? 'no access!'+i : 'can read/write'+i);
    });

    fs.exists('/etc/passwd', (exists) => {
      console.log(exists ? 'it\'s there'+i : 'no passwd!'+i);
    });
}

result:

idx: 0

idx: 1

no access!2

it's there2

no access!2

it's there2

why the i =2?

how can i fix it ?

Body:
The key of your problem is the asyncrhony. Both fs methods are asynchronous and will be executed later, and when they are going to be executed the value of i is 2, because the loop has finished.

The easiest way to solve it is changing the declaration of the loop   var by let

for(let i=0; i<2; i++)

It limits the scope of i to one iteration


问:
Use regex to add empty groups
I'm a beginner python programmer. I'm trying to use a regular expression to build groups to append to a list. I'm not sure whether what I want to do can be covered with a single regex, or if I need to pass the text through more than one regex.

Test data:

yada yada 0.003 40 40.00

yadayada ya 55

yaaaaaaya 100.0000 4

My regex:

```<code>(\w+ *\w* *\w*) (\d*\.*\d*) *(\d*\.*\d*) *(\d*\.*\d*)\n
</code>```

The groups that I get:

'yada yada','0.003','40','40.00'

'yadayada ya','55',empty,empty

'yaaaaaaya','100.0000','4',empty

BUT the groups that I want are:

'yada yada','0.003','40','40.00'

'yadayada ya',empty,empty,'55'

'yaaaaaaya',empty,'100.0000','4'

Is it possible to change the regex to introduce empty (\d*.*\d*) groups into those lines that have less than 3 of those groups? So that the number groups are "right-justified"?

I tried to add ? to the end of the first two (\d*) groups, but get the same empty groups.

答:
Your regex has several problems, one of which is a high risk of catastrophic backtracking because there is an exponentially growing number of permutations that the regex engine needs to test in non-matching cases. Another problematic thing is that \w will also match digits, so the first group may contain numbers you didn't want it to contain.

Furthermore, for such a "dynamically growing" regex, you'd need a "match continuation" feature like the \G or \K anchors, but Python does not support those.

The best way would be to .split() the string into substrings, then check each substring if it contains a number (for example by trying to convert it to a float) and behave accordingly.

Added bonus: You have a readable Python script instead of a very complicated regex.

Title: Use regex to add empty groups

Body:
I'm a beginner python programmer. I'm trying to use a regular expression to build groups to append to a list. I'm not sure whether what I want to do can be covered with a single regex, or if I need to pass the text through more than one regex.

Test data:

yada yada 0.003 40 40.00

yadayada ya 55

yaaaaaaya 100.0000 4

My regex:

(\w+ *\w* *\w*) (\d*\.*\d*) *(\d*\.*\d*) *(\d*\.*\d*)\n

The groups that I get:

'yada yada','0.003','40','40.00'

'yadayada ya','55',empty,empty

'yaaaaaaya','100.0000','4',empty

BUT the groups that I want are:

'yada yada','0.003','40','40.00'

'yadayada ya',empty,empty,'55'

'yaaaaaaya',empty,'100.0000','4'

Is it possible to change the regex to introduce empty (\d*.*\d*) groups into those lines that have less than 3 of those groups? So that the number groups are "right-justified"?

I tried to add ? to the end of the first two (\d*) groups, but get the same empty groups.


问:
MySQL table size
If I had a table with 500 million rows and good indexing would the DB suffer any performance degredation? I am wondering if I need to shard table over multiple DBs even if they might be on the same server. Each row might be 1k in size as it has a couple of text fields. Even if I foreign keyed them they would still be 500 million row table that comprises of say 700 bytes of data.

Also, any tips on engine selection for tables of this size would be great.
Any advise would be greatly appreciated.

Cheers

Rich

答:
MySQL supports user-defined partitioning for large tables.

As for whether or not you need it, it depends on your application and what queries you make. Have a look at the advantages of partitioning and see if any of them apply to your situation:

Partitioning makes it possible to store more data in one table than can be held on a single disk or file system partition.

Data that loses its usefulness can often be easily removed from a partitioned table by dropping the partition (or partitions) containing only that data. Conversely, the process of adding new data can in some cases be greatly facilitated by adding one or more new partitions for storing specifically that data.

Some queries can be greatly optimized in virtue of the fact that data satisfying a given WHERE clause can be stored only on one or more partitions, which automatically excluding any remaining partitions from the search. Because partitions can be altered after a partitioned table has been created, you can reorganize your data to enhance frequent queries that may not have been often used when the partitioning scheme was first set up. This ability to exclude non-matching partitions (and thus any rows they contain) is often referred to as partition pruning, and was implemented in MySQL 5.1.6. For more information, see Section 18.4, “Partition Pruning”.

Title: MySQL table size


答: fs.access and fs.exists are async calls and when they get their callbacks executed the accumulator has been already set to 2, because of the loop.

Title: nodejs fs.exists (fs.access) has strange things happen in for-loop


问:
Drag div content by grabbing its background
When the content goes outside the div, we use scrollbars to see it. How can I scroll the div content by grabbing and dragging its background? I've searched the solution but did not find what I need. Here is my fiddle:

https://jsfiddle.net/vaxobasilidze/xhn49e1j/

Drag any item to the right div and move it outside the container to the right or bottom. scrollbars appear to help you to scroll. Here is an example of what I want to achieve. See the first diagram on the link and drag it:

https://jsplumbtoolkit.com/

Any tips on how to do this?

答:
You should just need to detect when the mouse is down and then when the mouse is moving afterwards you can store the previous mouse coordinates and reference the current coordinates.  Finally you can scroll the div in question by an amount based on the difference in drag since the last mousemove call.

```<code>var mouseDown = false;
var prevCoords = { x: 0, y: 0 };

$("#mainDiv").mousedown(function() {
  mouseDown = true;
}).mousemove(function(e) {
  var currentScrollX = $('#mainDiv').scrollLeft();
  var currentScrollY = $('#mainDiv').scrollTop();
  if(mouseDown) {
    $('#mainDiv').scrollLeft(currentScrollX + prevCoords.x - (e.clientX + currentScrollX))
    $('#mainDiv').scrollTop(currentScrollY + prevCoords.y - e.clientY)
  };
  prevCoords.x = e.clientX + currentScrollX;
  prevCoords.y = e.clientY;
}).mouseup(function() {
  mouseDown = false;
});
</code>```

https://jsfiddle.net/6rx30muh/

EDIT: Fixed bug with wiggling tables when dragging:

```<code>            var mouseDown = false;
            var prevCoords = { x: 0, y: 0 };

            $("#mainDiv").mousedown(function() {
                mouseDown = true;
            }).mousemove(function(e) {
                var currentScrollX = $('#mainDiv').scrollLeft();
                var currentScrollY = $('#mainDiv').scrollTop();
                if(mouseDown) {
                    $('#mainDiv').scrollLeft(currentScrollX + prevCoords.x - e.clientX)
                    $('#mainDiv').scrollTop(currentScrollY + prevCoords.y - e.clientY)
                };
                prevCoords.x = e.clientX;
                prevCoords.y = e.clientY;
            }).mouseup(function() {
                mouseDown = false;
            });
</code>```

Body:
You should just need to detect when the mouse is down and then when the mouse is moving afterwards you can store the previous mouse coordinates and reference the current coordinates.  Finally you can scroll the div in question by an amount based on the difference in drag since the last mousemove call.

var mouseDown = false;
var prevCoords = { x: 0, y: 0 };

$("#mainDiv").mousedown(function() {
  mouseDown = true;
}).mousemove(function(e) {
  var currentScrollX = $('#mainDiv').scrollLeft();
  var currentScrollY = $('#mainDiv').scrollTop();
  if(mouseDown) {
    $('#mainDiv').scrollLeft(currentScrollX + prevCoords.x - (e.clientX + currentScrollX))
    $('#mainDiv').scrollTop(currentScrollY + prevCoords.y - e.clientY)
  };
  prevCoords.x = e.clientX + currentScrollX;
  prevCoords.y = e.clientY;
}).mouseup(function() {
  mouseDown = false;
});

https://jsfiddle.net/6rx30muh/

EDIT: Fixed bug with wiggling tables when dragging:

            var mouseDown = false;
            var prevCoords = { x: 0, y: 0 };

            $("#mainDiv").mousedown(function() {
                mouseDown = true;
            }).mousemove(function(e) {
                var currentScrollX = $('#mainDiv').scrollLeft();
                var currentScrollY = $('#mainDiv').scrollTop();
                if(mouseDown) {
                    $('#mainDiv').scrollLeft(currentScrollX + prevCoords.x - e.clientX)
                    $('#mainDiv').scrollTop(currentScrollY + prevCoords.y - e.clientY)
                };
                prevCoords.x = e.clientX;
                prevCoords.y = e.clientY;
            }).mouseup(function() {
                mouseDown = false;
            });


问:
Best way to store locators in Robotramework
I am building a Robotframework automation project.

As the project grows, it also becomes more difficult to maintain, with the increasing of selectors number in project.

+10K selectors in project (a big one) and almost no changes occur in each one;

Now I have the following structure:

```<code> .
 |-- Project
 |   |-- Generic Keywords
 |   |   |-- Web App A
 |   |   |   `-- GUI_Actions.robot
 |   |   |-- Web App B
 |   |   |   |-- GUI_Actions.robot
 |   |   |   |-- DB_Actions.robot
 |   |   |   |-- ...
 |   |   `-- ...
 |   |-- Tests
 |   |   `-- Web App A
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...
 |   |   `-- Web App B
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...
</code>```

What is the best way to keep these locators(separate from the code) in a way that makes the project scalable and maintainable?

Separated folder "Locators" (in root) with files (resources) and one variable per locator?

One locators file (one by application) inside "Generic Keywords" and "Web App" folders?

... etc

There are many ways to do that, which one is the best?

I appreciate some ideas/suggestions. Thank you.

答:
There will not be a single answer that fits your question as much of it depends on your application, level of technical capabilities and your (organisations) coding style.

If your application's UI is quite repetitive in the form of pages or page parts, with static ID's, then a Page Object model is a good fit. There is a PageObject Library that you can use or take inspiration from.

Another way of centralising your locators is to use a custom locator like Click Element   abc=SomeVirtualId. An example of this approach can be found in the answer to another SO question. This approach is also useful when the Id's to your elements are predictable and can be generated. Then it centralises the logic without the need for many custom keywords.

Body:
I am building a Robotframework automation project.

As the project grows, it also becomes more difficult to maintain, with the increasing of selectors number in project.

+10K selectors in project (a big one) and almost no changes occur in each one;

Now I have the following structure:

 .
 |-- Project
 |   |-- Generic Keywords
 |   |   |-- Web App A
 |   |   |   `-- GUI_Actions.robot
 |   |   |-- Web App B
 |   |   |   |-- GUI_Actions.robot
 |   |   |   |-- DB_Actions.robot
 |   |   |   |-- ...
 |   |   `-- ...
 |   |-- Tests
 |   |   `-- Web App A
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...
 |   |   `-- Web App B
 |   |       |-- Suite1.robot
 |   |       |-- Suite2.robot
 |   |       |-- ...

What is the best way to keep these locators(separate from the code) in a way that makes the project scalable and maintainable?

Separated folder "Locators" (in root) with files (resources) and one variable per locator?

One locators file (one by application) inside "Generic Keywords" and "Web App" folders?

... etc

There are many ways to do that, which one is the best?

I appreciate some ideas/suggestions. Thank you.