问:
Attribute p:prefix not allowed here
I've created a project with spring mvc and in my dispatcherServlet.xml file

```<code><bean id="jspViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp"
            />
</code>```

p:prefix and p:suffix are not allowed. How can I solve this issue? I've used SpringVersion 3.2.3.RELEASE

答:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-4.1.xsd
               http://www.springframework.org/schema/util
               http://www.springframework.org/schema/util/spring-util-4.1.xsd
            ">```

Title: Attribute p:prefix not allowed here

Body:
I've created a project with spring mvc and in my dispatcherServlet.xml file

<bean id="jspViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/views/"
          p:suffix=".jsp"
            />

p:prefix and p:suffix are not allowed. How can I solve this issue? I've used SpringVersion 3.2.3.RELEASE


来源: stackexchange

问:
Object of type 'function' has no len() in python
I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.

Here is the code that I've wrote.

```<code>def main():
    while True:
        userInput()
        characterCount(userInput)
        middleLetter()
        spaceCount()
        letterReplace()
        displayOutput()

def userInput():
    sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
    if sentence == 'STOP':
        quit()
    return sentence

def characterCount(sentence):
    characterCount = len(sentence) - sentence.count(' ')
    if characterCount < 10:
        print('Sorry that is less than 10 letters')
    return characterCount

def middleLetter(sentence):
    sentence = len(sentence)/2
    middleLetter = [sentence +1]
    return middleLetter

def spaceCount(sentence):
    spaceCount = sentence.count(' ')
    return spaceCount

def letterReplace(sentence):
    letterReplace= sentence.replace("a", "&")
    return letterReplace

def displayOutput(characterCount,middleLetter,spaceCount,letterReplace):
    print('Number of letters: '(characterCount))
    print('Middle letter: '(middleLetter))
    print('Spaces counted: '(spaceCount))
    print('Sentence with letter replaced: '(letterReplace))

main()
</code>```

The problem I have is that when I run the program I get the error.

```<code>Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 18, in main
    characterCount(userInput)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 32, in characterCount
    characterCount = len(sentence) - sentence.count(' ')
TypeError: object of type 'function' has no len()
</code>```

Most of the times I have seen this error is because of a int being used instead of a string but I can not see what would be causing this error. Any help would be appreciated.

Using some of the given suggestions I have fixed the original error but now when I try to run it I receive the error.

```<code>Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 22, in main
    displayOutput(characterCount,middleLetter,spaceCount,letterReplace)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 53, in displayOutput
    print('Number of letters:'(characterCount))
TypeError: 'str' object is not callable
</code>```

答:
You need to capture the output of userInput():

```<code>while True:
    sentence = userInput()
    characterCount(sentence)
    ...
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have been searching for a solution for this error for a while but the solutions that have helped others have not been much help for me.

Here is the code that I've wrote.

def main():
    while True:
        userInput()
        characterCount(userInput)
        middleLetter()
        spaceCount()
        letterReplace()
        displayOutput()

def userInput():
    sentence = str(input('Enter a sentence at least 10 letters long, or type STOP to quit:'))
    if sentence == 'STOP':
        quit()
    return sentence

def characterCount(sentence):
    characterCount = len(sentence) - sentence.count(' ')
    if characterCount < 10:
        print('Sorry that is less than 10 letters')
    return characterCount

def middleLetter(sentence):
    sentence = len(sentence)/2
    middleLetter = [sentence +1]
    return middleLetter

def spaceCount(sentence):
    spaceCount = sentence.count(' ')
    return spaceCount

def letterReplace(sentence):
    letterReplace= sentence.replace("a", "&")
    return letterReplace

def displayOutput(characterCount,middleLetter,spaceCount,letterReplace):
    print('Number of letters: '(characterCount))
    print('Middle letter: '(middleLetter))
    print('Spaces counted: '(spaceCount))
    print('Sentence with letter replaced: '(letterReplace))

main()

The problem I have is that when I run the program I get the error.

Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 18, in main
    characterCount(userInput)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 32, in characterCount
    characterCount = len(sentence) - sentence.count(' ')
TypeError: object of type 'function' has no len()

Most of the times I have seen this error is because of a int being used instead of a string but I can not see what would be causing this error. Any help would be appreciated.

Using some of the given suggestions I have fixed the original error but now when I try to run it I receive the error.

Traceback (most recent call last):
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 59, in <module>
    main()
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 22, in main
    displayOutput(characterCount,middleLetter,spaceCount,letterReplace)
  File "C:\Users\wood\Desktop\Software design\Program 4\program3_4QuinnWood.py", line 53, in displayOutput
    print('Number of letters:'(characterCount))
TypeError: 'str' object is not callable

Body:
You need to capture the output of userInput():

while True:
    sentence = userInput()
    characterCount(sentence)
    ...


问:
API data is not getting at first loading ionic2, angular2
I am struggling from last couple days.I am using ionic2/3 angular 2 and wordpress for data.
I am trying to load categories data at home page at first load but i am not getting. In browser it's coming properly and also when i click on menu button entire data is showing properly. I checked all blogs but didn't get any proper solution.
Please help me if any one had same issues and solved.Thanks in advance.
I am attaching my codes here.</p>

```<code>enter code here
Home.ts-
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  woocommerce: any;
  categories: any[];

         //   Home=HomePage;

  constructor(public navCtrl: NavController) {
      this.categories=[];

  }

  ionViewDidLoad(){
     this.getCatData();
  }

  getCatData(){
    this.woocommerce = WC({
    url:'http://www.example.com/',
    consumerKey: 'ck_7dfe0aec65ahgcdhgcdhcdhf36288d1fa2e4c01',
    consumerSecret: 'cs_da53e5b228eb6235bshhcskhc7a68541ad809743'
  });
  this.woocommerce.getAsync("products/categories").then((data)=>{
        console.log(JSON.parse(data.body).product_categories);
        this.categories = JSON.parse(data.body).product_categories;

  },(err)=>{
    console.log(err);
  })
}

}
Home.html-
<ion-header>
  <ion-navbar color="header">
         <ion-buttons left>
              <button ion-button menuToggle>
                <ion-icon name="menu"></ion-icon>
              </button>
         </ion-buttons>
         <ion-buttons right>
              <button ion-button icon-only>
                 <ion-icon name="search"></ion-icon>
              </button>
          </ion-buttons>
    <ion-title>
      KAAIROS EXPORTS
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
  <!-- slider -->
    <ion-card>
        <ion-slides loop="true" autoplay="false" pager>
          <ion-slide *ngFor= "let number of [1,2,3,4,5]"><img src="./assets/img/{{number}}.jpg"/></ion-slide>
        </ion-slides>
        </ion-card>
     <!-- end-slider    -->
    <!-- <ion-grid> Hi this is second line
    </ion-grid> -->
    <ion-item *ngFor="let category of categories">
      <h2> {{ category.name }} </h2>
    </ion-item>
</ion-content>
app.component.ts-
import { TabsPage } from './../pages/tabs/tabs';
import { HomePage } from './../pages/home/home';
import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
//import { Menu } from '../pages/menu/menu';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

 // rootPage: any = Menu;
  rootPage = TabsPage;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
    this.initializeApp();

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
  // go_to_home(){
  //   this.nav.setRoot(HomePage);
  // }
}

app.html-
<ion-menu side="left" [content]="content">
    <ion-header>
        <ion-toolbar>
            <ion-title>Menu</ion-title>
        </ion-toolbar>
    </ion-header>
    <ion-content>
        <!-- <ion-list>
            <!-- <ion-item (click)="go_to_home()" menuClose>
                Home
            </ion-item> -->
           <!--  <ion-item (click)="go_to_about()" menuClose>
                About
            </ion-item> -->
             <!-- <ion-item (click)="go_to_contact()" menuClose>
                Contact Us
            <!-- </ion-item> -->

    </ion-content>
</ion-menu>
<!-- Disable swipe-to-go-back because it's poor UX to combine STGB with side menus -->
<ion-nav [root]="rootPage" #content swipeBackEnabled="true"></ion-nav>

app.module:-
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { AboutusPage } from '../pages/aboutus/aboutus';
import { ContactusPage } from '../pages/contactus/contactus';
import { CategoryPage } from '../pages/category/category';
import { ProductsByCategoryPage } from '../pages/products-by-category/products-by-category';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { WooCommerceProvider } from '../providers/woocommerce/woocommerce';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    //ProductListPage,
    ProductsByCategoryPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp,{
      mode:'ios'
}),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    ProductsByCategoryPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    WooCommerceProvider
  ]
})
export class AppModule {}
</code>```

答:
Simply call the ChangeDetectorRef after successfull API call to refresh the changes in UI. PFB the sample code where we have triggered change detector on subscribe call. You can check the working version here</p>

```<code>import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';
import { NavController, Content } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Content) content: Content;
  Arr = Array; //Array type captured in a variable
  num:number = 1000;
  toolbar_color: string;

  constructor(public navCtrl: NavController, public ref : ChangeDetectorRef) {
    this.toolbar_color="secondary";
  }

  changeColor(){
    this.toolbar_color="primary";
    this.ref.detectChanges();
  }

  ionViewDidLoad() {
    //this.content.enableJsScroll();
    this.content.ionScrollEnd.subscribe(() => {
        this.changeColor();
    });
}

}
</code>```

Body:
I am struggling from last couple days.I am using ionic2/3 angular 2 and wordpress for data.
I am trying to load categories data at home page at first load but i am not getting. In browser it's coming properly and also when i click on menu button entire data is showing properly. I checked all blogs but didn't get any proper solution.
Please help me if any one had same issues and solved.Thanks in advance.
I am attaching my codes here.

enter code here
Home.ts-
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as WC from 'woocommerce-api';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  woocommerce: any;
  categories: any[];

         //   Home=HomePage;

  constructor(public navCtrl: NavController) {
      this.categories=[];

  }

  ionViewDidLoad(){
     this.getCatData();
  }

  getCatData(){
    this.woocommerce = WC({
    url:'http://www.example.com/',
    consumerKey: 'ck_7dfe0aec65ahgcdhgcdhcdhf36288d1fa2e4c01',
    consumerSecret: 'cs_da53e5b228eb6235bshhcskhc7a68541ad809743'
  });
  this.woocommerce.getAsync("products/categories").then((data)=>{
        console.log(JSON.parse(data.body).product_categories);
        this.categories = JSON.parse(data.body).product_categories;

  },(err)=>{
    console.log(err);
  })
}

}
Home.html-
<ion-header>
  <ion-navbar color="header">
         <ion-buttons left>
              <button ion-button menuToggle>
                <ion-icon name="menu"></ion-icon>
              </button>
         </ion-buttons>
         <ion-buttons right>
              <button ion-button icon-only>
                 <ion-icon name="search"></ion-icon>
              </button>
          </ion-buttons>
    <ion-title>
      KAAIROS EXPORTS
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content>

    <ion-card>
        <ion-slides loop="true" autoplay="false" pager>
          <ion-slide *ngFor= "let number of [1,2,3,4,5]"></ion-slide>
        </ion-slides>
        </ion-card>

    <ion-item *ngFor="let category of categories">

 {{ category.name }}

    </ion-item>
</ion-content>
app.component.ts-
import { TabsPage } from './../pages/tabs/tabs';
import { HomePage } from './../pages/home/home';
import { Component, ViewChild } from '@angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
//import { Menu } from '../pages/menu/menu';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  @ViewChild(Nav) nav: Nav;

 // rootPage: any = Menu;
  rootPage = TabsPage;

  constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen) {
    this.initializeApp();

  }

  initializeApp() {
    this.platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }
  // go_to_home(){
  //   this.nav.setRoot(HomePage);
  // }
}

app.html-
<ion-menu side="left" [content]="content">
    <ion-header>
        <ion-toolbar>
            <ion-title>Menu</ion-title>
        </ion-toolbar>
    </ion-header>
    <ion-content>

    </ion-content>
</ion-menu>

<ion-nav [root]="rootPage" #content swipeBackEnabled="true"></ion-nav>

app.module:-
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { AboutusPage } from '../pages/aboutus/aboutus';
import { ContactusPage } from '../pages/contactus/contactus';
import { CategoryPage } from '../pages/category/category';
import { ProductsByCategoryPage } from '../pages/products-by-category/products-by-category';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { WooCommerceProvider } from '../providers/woocommerce/woocommerce';
import { HttpModule } from '@angular/http';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    //ProductListPage,
    ProductsByCategoryPage
  ],
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp,{
      mode:'ios'
}),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    TabsPage,
    AboutusPage,
    ContactusPage,
    CategoryPage,
    ProductsByCategoryPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    WooCommerceProvider
  ]
})
export class AppModule {}

Body:
Simply call the ChangeDetectorRef after successfull API call to refresh the changes in UI. PFB the sample code where we have triggered change detector on subscribe call. You can check the working version here

import { Component, ViewChild, ChangeDetectorRef } from '@angular/core';
import { NavController, Content } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild(Content) content: Content;
  Arr = Array; //Array type captured in a variable
  num:number = 1000;
  toolbar_color: string;

  constructor(public navCtrl: NavController, public ref : ChangeDetectorRef) {
    this.toolbar_color="secondary";
  }

  changeColor(){
    this.toolbar_color="primary";
    this.ref.detectChanges();
  }

  ionViewDidLoad() {
    //this.content.enableJsScroll();
    this.content.ionScrollEnd.subscribe(() => {
        this.changeColor();
    });
}

}


问:
Update data using Ajax + Modal + Laravel
Im trying to update datatable in laravelusing this artical LINK
when i click my edit button its fetching data but when i click update button im getting error :
i post my question in laracast so if anyone can tell me the idea https://laracasts.com/discuss/channels/general-discussion/update-data-ajax-modal-laravel</p>

答:
Update Using Laravel Ajax Modal Very Easy

Route Here

```<code>Route::get('class_routine', 'ClassRoutineController@routineEdit');
Route::resource('class_routine','ClassRoutineController',['parameters'=> ['class_routine'=>'id']]);
</code>```

Controller

```<code>public function routineEdit(Request $request)
    {
        if($request->ajax()){
            $editModeData = ClassRoutine::Find($request->id);
            return Response($editModeData);
        }
     }

public function update(Request $request, $id)
{

    $data = ClassRoutine::FindOrFail($id);
    $input = $request->all();
    $input['updated_by'] = Session('loggedSessionData.id');
    $class_id = $request->class_id;

    try {
        $data->update($input);
        $result = 0;
    } catch (\Exception $e) {
        $result = $e->errorInfo[1];
    }

    if ($result == 0) {
            $notification = array(
            'message' => 'Class Routine Successfully Updated.',
            'alert-type' => 'success'
        );
        return redirect('class_routine/'.$class_id)->with($notification);
    } else {
        $notification = array(
            'message' => 'Something Error Found !, Please try again.',
            'alert-type' => 'error'
        );
        return redirect('class_routine/'.$class_id)->with($notification);
    }
}
</code>```

Modal View Here

button

```<code><li>
    <a href="" class="editModalBtn" data-toggle="modal" data-id="{!! $value['id'] !!}">Edit</a>
</li>

<div id="editModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-hidden="true">
   <div class="modal-dialog modal-md">
      <div class="modal-content">
         <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
            </button>
            <h4 class="modal-title" id="myModalLabel2">Update Routine</h4>
         </div>
         <div class="modal-body">
            {{ Form::open(array('method' => 'PUT','id'=>'classForm','class'=>'form-horizontal classFormUpdate')) }}
            {{ Form::hidden('class_id', '', array('id' => 'class-id','class'=>'class-id')) }}
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-book"></i></span>
               {{ Form::select('subject_id', $subjectList, Input::old('required'), array('class' => 'form-control required subject_id', 'id'=>'subject_id')) }}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-calendar-check-o"></i></span>
               {{ Form::select('day_of_week', daysOfWeek(), Input::old('day_of_week'), array('class' => 'form-control day_of_week required', 'id'=>'day_of_week','style'=>'pointer-events: none !important')) }}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-user"></i></span>
               {{ Form::select('teacher_id', $teacherList, Input::old('teacher_id'), array('class' => 'form-control required teacher_id', 'id'=>'teacher_id')) }}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
               {!! Form::text('start_time','', $attributes = array('class'=>'form-control required myDatepicker3 start_time','id'=>'start_time','placeholder'=>'Start Time')) !!}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
               {!! Form::text('end_time','', $attributes = array('class'=>'form-control required myDatepicker3 end_time','id'=>'end_time','placeholder'=>'End Time')) !!}
            </div>
            <br />
            <button type="submit" class="btn btn-primary"><i class="fa fa-check-circle"></i> Update !</button>
            {{ Form::close() }}
         </div>
         <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
      </div>
   </div>
</div>
</code>```

js

```<code>$(document).ready(function() {
    $('.editModalBtn').click(function() {
      var id=$(this).data('id');
      var action ='{{URL::to('class_routine')}}/'+id;

      var url = '{{URL::to('class_routine')}}';
      $.ajax({
        type : 'get',
        url  : url,
        data : {'id':id},
        success:function(data){
          $('#id').val(data.id);
          $('.class-id').val(data.class_id);
          $('.subject_id').val(data.subject_id);
          $('.day_of_week').val(data.day_of_week);
          $('.teacher_id').val(data.teacher_id);
          $('.start_time').val(data.start_time);
          $('.end_time').val(data.end_time);
          $('.classFormUpdate').attr('action',action);
          $('#editModal').modal('show');
        }
      });
    });
});
</code>```

Body:
Update Using Laravel Ajax Modal Very Easy

Route Here

Route::get('class_routine', 'ClassRoutineController@routineEdit');
Route::resource('class_routine','ClassRoutineController',['parameters'=> ['class_routine'=>'id']]);

Controller

public function routineEdit(Request $request)
    {
        if($request->ajax()){
            $editModeData = ClassRoutine::Find($request->id);
            return Response($editModeData);
        }
     }

public function update(Request $request, $id)
{

    $data = ClassRoutine::FindOrFail($id);
    $input = $request->all();
    $input['updated_by'] = Session('loggedSessionData.id');
    $class_id = $request->class_id;

    try {
        $data->update($input);
        $result = 0;
    } catch (\Exception $e) {
        $result = $e->errorInfo[1];
    }

    if ($result == 0) {
            $notification = array(
            'message' => 'Class Routine Successfully Updated.',
            'alert-type' => 'success'
        );
        return redirect('class_routine/'.$class_id)->with($notification);
    } else {
        $notification = array(
            'message' => 'Something Error Found !, Please try again.',
            'alert-type' => 'error'
        );
        return redirect('class_routine/'.$class_id)->with($notification);
    }
}

Modal View Here

button

<li>
    <a href="" class="editModalBtn" data-toggle="modal" data-id="{!! $value['id'] !!}">Edit</a>
</li>

<div id="editModal" class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-hidden="true">
   <div class="modal-dialog modal-md">
      <div class="modal-content">
         <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span>
            </button>
            <h4 class="modal-title" id="myModalLabel2">Update Routine</h4>
         </div>
         <div class="modal-body">
            {{ Form::open(array('method' => 'PUT','id'=>'classForm','class'=>'form-horizontal classFormUpdate')) }}
            {{ Form::hidden('class_id', '', array('id' => 'class-id','class'=>'class-id')) }}
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-book"></i></span>
               {{ Form::select('subject_id', $subjectList, Input::old('required'), array('class' => 'form-control required subject_id', 'id'=>'subject_id')) }}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-calendar-check-o"></i></span>
               {{ Form::select('day_of_week', daysOfWeek(), Input::old('day_of_week'), array('class' => 'form-control day_of_week required', 'id'=>'day_of_week','style'=>'pointer-events: none !important')) }}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-user"></i></span>
               {{ Form::select('teacher_id', $teacherList, Input::old('teacher_id'), array('class' => 'form-control required teacher_id', 'id'=>'teacher_id')) }}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
               {!! Form::text('start_time','', $attributes = array('class'=>'form-control required myDatepicker3 start_time','id'=>'start_time','placeholder'=>'Start Time')) !!}
            </div>
            <div class="input-group">
               <span class="input-group-addon"><i class="fa fa-clock-o"></i></span>
               {!! Form::text('end_time','', $attributes = array('class'=>'form-control required myDatepicker3 end_time','id'=>'end_time','placeholder'=>'End Time')) !!}
            </div>
            <br />
            <button type="submit" class="btn btn-primary"><i class="fa fa-check-circle"></i> Update !</button>
            {{ Form::close() }}
         </div>
         <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
         </div>
      </div>
   </div>
</div>

js

$(document).ready(function() {
    $('.editModalBtn').click(function() {
      var id=$(this).data('id');
      var action ='{{URL::to('class_routine')}}/'+id;

      var url = '{{URL::to('class_routine')}}';
      $.ajax({
        type : 'get',
        url  : url,
        data : {'id':id},
        success:function(data){
          $('#id').val(data.id);
          $('.class-id').val(data.class_id);
          $('.subject_id').val(data.subject_id);
          $('.day_of_week').val(data.day_of_week);
          $('.teacher_id').val(data.teacher_id);
          $('.start_time').val(data.start_time);
          $('.end_time').val(data.end_time);
          $('.classFormUpdate').attr('action',action);
          $('#editModal').modal('show');
        }
      });
    });
});

ContentLicense: CC BY-SA 4.0


问:
Gps services to get current position
I want to know is there any services that device by using it could find it's current location?
for example tags that show current location , using any international or local
services.
thanks for any guides.
Regards
Ali</p>

答:
I found some thing more ,GPS is satellite network that send positions as a signal
to earth and receiver should get signal from at least four satellite to calculate
their current position.it is free and every receiver could use it.</p>

Title: Gps services to get current position


问:
Semantics of DataFrame groupby method
I find the behavior of the groupby method on a DataFrame object unexpected.

Let me explain with an example.

```<code>df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
                   'key2': ['one', 'two', 'one', 'two', 'one'],
                   'data1': np.random.randn(5),
                   'data2': np.random.randn(5)})
data1 = df['data1']

data1
# Out[14]:
# 0    1.989430
# 1   -0.250694
# 2   -0.448550
# 3    0.776318
# 4   -1.843558
# Name: data1, dtype: float64
</code>```

data1 does not have the 'key1' column anymore.
So I would expect to get an error if I applied the following operation:

```<code>grouped = data1.groupby(df['key1'])
</code>```

But I don't, and I can further apply the mean method on grouped to get the expected result.

```<code>grouped.mean()
# Out[13]:
# key1
# a   -0.034941
# b    0.163884
# Name: data1, dtype: float64
</code>```

However, the above operation does create a group using the 'key1' column of df.

How can this happen? Does the interpreter store information of the originating DataFrame (df in this case) with the created DataFrame/series (data1 in this case)?

Thank you.

答:
Although the grouping columns are typically from the same dataframe or series, they don't have to be.

Your statement data1.groupby(df['key1']) is equivalent to data1.groupby(['a', 'a', 'b', 'b', 'a']).  In fact, you can inspect the actual groups:

```<code>>>> data1.groupby(['a', 'a', 'b', 'b', 'a']).groups
{'a': [0, 1, 4], 'b': [2, 3]}
</code>```

This means that your groupby on data1 will have a group a using rows 0, 1, and 4 from data1 and a group b using rows 2 and 3.

Title: Semantics of DataFrame groupby method

Body:
I find the behavior of the groupby method on a DataFrame object unexpected.

Let me explain with an example.

df = pd.DataFrame({'key1': ['a', 'a', 'b', 'b', 'a'],
                   'key2': ['one', 'two', 'one', 'two', 'one'],
                   'data1': np.random.randn(5),
                   'data2': np.random.randn(5)})
data1 = df['data1']

data1
# Out[14]:
# 0    1.989430
# 1   -0.250694
# 2   -0.448550
# 3    0.776318
# 4   -1.843558
# Name: data1, dtype: float64

data1 does not have the 'key1' column anymore.
So I would expect to get an error if I applied the following operation:

grouped = data1.groupby(df['key1'])

But I don't, and I can further apply the mean method on grouped to get the expected result.

grouped.mean()
# Out[13]:
# key1
# a   -0.034941
# b    0.163884
# Name: data1, dtype: float64

However, the above operation does create a group using the 'key1' column of df.

How can this happen? Does the interpreter store information of the originating DataFrame (df in this case) with the created DataFrame/series (data1 in this case)?

Thank you.

Body:
Although the grouping columns are typically from the same dataframe or series, they don't have to be.

Your statement data1.groupby(df['key1']) is equivalent to data1.groupby(['a', 'a', 'b', 'b', 'a']).  In fact, you can inspect the actual groups:

>>> data1.groupby(['a', 'a', 'b', 'b', 'a']).groups
{'a': [0, 1, 4], 'b': [2, 3]}

This means that your groupby on data1 will have a group a using rows 0, 1, and 4 from data1 and a group b using rows 2 and 3.


问:
Parsing two messy numbers with .NET regex
I have an interesting dataset of numbers that I need to replace. How can I use .NET flavored regex (probably with a lookaround) to parse the first and second number from each row using the following algorithm:

Strings larger than 15 symbols that contain two numbers separated by the first occurrence of [\s\p{P}] after 7th symbol should be split in two. One regex should extract the first substring (containing numbers, spaces, punctuations). The second regex extracts the second half.

There is not much I can do about numbers that do not have a reasonably well defined separator. In example below the first 10 rows are subjects to be split. Strings that can't be split should be picked up by either of the two regex statements. No worries about \n; these strings are processed individually.

```<code>42977424427-77927299
62 92764949 44922672
96649274796/46262299
62-96247469,74292792
69227679/69267664
47694274/42929726
42977424427/77927299
97247-2666/7224-4767
89 3644-883436749503
78-99733017785-01627
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722
</code>```

So, the first regex would return:

```<code>42977424427
62 92764949
96649274796
62-96247469
69227679
47694274
42977424427
97247-2666
89 3644
78-99733017785
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722
</code>```

and the second regex statement would return

```<code>77927299
44922672
46262299
74292792
69267664
42929726
77927299
7224-4767
883436749503
01627
</code>```

Here is my (failing) attempt to extract the second group of numbers:

```<code>(?=[\d \p{P}]{15,})[\s\p{P}][\d\p{P}]{,8}
</code>```

Body:
I have an interesting dataset of numbers that I need to replace. How can I use .NET flavored regex (probably with a lookaround) to parse the first and second number from each row using the following algorithm:

Strings larger than 15 symbols that contain two numbers separated by the first occurrence of [\s\p{P}] after 7th symbol should be split in two. One regex should extract the first substring (containing numbers, spaces, punctuations). The second regex extracts the second half.

There is not much I can do about numbers that do not have a reasonably well defined separator. In example below the first 10 rows are subjects to be split. Strings that can't be split should be picked up by either of the two regex statements. No worries about \n; these strings are processed individually.

42977424427-77927299
62 92764949 44922672
96649274796/46262299
62-96247469,74292792
69227679/69267664
47694274/42929726
42977424427/77927299
97247-2666/7224-4767
89 3644-883436749503
78-99733017785-01627
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722

So, the first regex would return:

42977424427
62 92764949
96649274796
62-96247469
69227679
47694274
42977424427
97247-2666
89 3644
78-99733017785
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722

and the second regex statement would return

77927299
44922672
46262299
74292792
69267664
42929726
77927299
7224-4767
883436749503
01627

Here is my (failing) attempt to extract the second group of numbers:

(?=[\d \p{P}]{15,})[\s\p{P}][\d\p{P}]{,8}

Body:
I ended up with a quiet similar pattern

^([\d\s\p{P}]{7}\d*)(?:[^\d\n]([\d\p{P}]+))?$

that allows you to get the values from the capture groups as needed:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"^([\d\s\p{P}]{7}\d*)(?:[^\d\n]([\d\p{P}]+))?$";
        string input = @"42977424427-77927299
62 92764949 44922672
96649274796/46262299
62-96247469,74292792
69227679/69267664
47694274/42929726
42977424427/77927299
97247-2666/7224-4767
89 3644-883436749503
78-99733017785-01627
967224267
6672-2222
97694629646797496
962 44776699
942 76699466
24796427466476967
99 98448999068440722";
        RegexOptions options = RegexOptions.Multiline;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("{0}.....{1}", m.Groups[1].Value, m.Groups[2].Value);
        }
    }
}

Just use the groups or glue the final string together as needed.

And here is a pattern that enables your original idea of splitting:

(?=(?:(?:[\d\s\p{P}]{15,}).))(?<=.{7})[\s\p{P}]


问:
How to pick a contact in Android Studio with AppCompatActivity?
```<code>Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);
</code>```

This basic intent works when I extend Activity (i.e. "MainActivity extends Activity"), but not when I extend AppCompatActivity. Can someone explain why, please :| I've been trying to figure it out for days.

I just really want to keep the action bar I already have in an existing app while being able to let the user pick a contact.

Logcat spouted a lot of stuff, not sure how much to copy&paste but here's a log when I clicked the button with a try/catch block:

```<code>11-17 18:37:36.386 2790-2790/com.danie.contactstesting1 W/System.err: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
11-17 18:37:36.389 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.BaseFragmentActivityApi14.checkForValidRequestCode(BaseFragmentActivityApi14.java:79)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:717)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at com.danie.contactstesting1.MainActivity$1.onClick(MainActivity.java:31)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View.performClick(View.java:6294)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View$PerformClick.run(View.java:24770)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.handleCallback(Handler.java:790)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Looper.loop(Looper.java:164)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
11-17 18:37:36.392 1378-3101/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 489826 , only wrote 489600
11-17 18:37:37.668 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_STATUS_SMS_TIME_OUT
11-17 18:37:37.669 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - discarding deferred status: configuration_state=4
11-17 18:37:37.672 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - no more tasks, stopping service if no task are added in 5000 millis
11-17 18:37:37.685 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - task received
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - TaskExecutor already running
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: Task.createTask - create task:com.android.voicemail.impl.ActivationTask
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - retry #2 for com.android.voicemail.impl.ActivationTask@66adaa2 queued, executing in 5000
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - com.android.voicemail.impl.ActivationTask@66adaa2 added
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - minimal wait time:4999
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - sleep for 4999 millis
11-17 18:37:39.618 1378-1528/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 797294 , only wrote 644400
11-17 18:37:42.695 2064-3590/com.google.android.dialer I/Dialer: VvmTaskExecutor - executing task com.android.voicemail.impl.ActivationTask@66adaa2
11-17 18:37:42.697 2064-3590/com.google.android.dialer I/Dialer: PreOMigrationHandler - ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}, [e2f7d48dd2b5ca523e7313cf4ba0f6ea830b6281], UserHandle{0} already migrated
11-17 18:37:42.740 2064-3590/com.google.android.dialer I/Dialer: VvmActivationTask - VVM content provider configured - vvm_type_cvvm
11-17 18:37:42.741 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_ACTIVATING
11-17 18:37:42.763 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.setVisualVoicemailSmsFilterSettings - using TelephonyManager
11-17 18:37:42.767 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.sendVisualVoicemailSms - using TelephonyManager
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Do partial code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: After code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Increasing code cache capacity to 512KB
11-17 18:38:00.026 1388-1413/? D/hwcomposer: hw_composer sent 18 syncs in 60s
11-17 18:38:08.586 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.587 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.609 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.609 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.621 1585-1599/system_process E/memtrack: Couldn't load memtrack module
</code>```

Uhh okay embarrassing, I just had to use a lower request code (RESULT_PICK_CONTACT was 85500). Thanks CommonsWare for pointing me towards Logcat. Haha... Thanks everyone for quick responses as well!

答:
This work for me</p>

```<code>@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
             case RESULT_PICK_CONTACT:
                  Cursor cursorPickPhoneNo = null;
                  try {
                    String phonenumber = null ;
                    String name = null;
                    Uri uri = data.getData();
                    cursorPickPhoneNo = getContentResolver().query(uri, null, null, null, null);
                    cursorPickPhoneNo.moveToFirst();
                    int  index =cursorPickPhoneNo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    phonenumber = cursorPickPhoneNo.getString(index);
                    Toast.makeText(this, ""+phonenumber, Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}
</code>```

Body:
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI);
            startActivityForResult(contactPickerIntent, RESULT_PICK_CONTACT);

This basic intent works when I extend Activity (i.e. "MainActivity extends Activity"), but not when I extend AppCompatActivity. Can someone explain why, please :| I've been trying to figure it out for days.

I just really want to keep the action bar I already have in an existing app while being able to let the user pick a contact.

Logcat spouted a lot of stuff, not sure how much to copy&paste but here's a log when I clicked the button with a try/catch block:

11-17 18:37:36.386 2790-2790/com.danie.contactstesting1 W/System.err: java.lang.IllegalArgumentException: Can only use lower 16 bits for requestCode
11-17 18:37:36.389 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.BaseFragmentActivityApi14.checkForValidRequestCode(BaseFragmentActivityApi14.java:79)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:717)
11-17 18:37:36.390 2790-2790/com.danie.contactstesting1 W/System.err:     at com.danie.contactstesting1.MainActivity$1.onClick(MainActivity.java:31)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View.performClick(View.java:6294)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.view.View$PerformClick.run(View.java:24770)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.handleCallback(Handler.java:790)
11-17 18:37:36.391 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:99)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.os.Looper.loop(Looper.java:164)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:6494)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
11-17 18:37:36.392 2790-2790/com.danie.contactstesting1 W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
11-17 18:37:36.392 1378-3101/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 489826 , only wrote 489600
11-17 18:37:37.668 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_STATUS_SMS_TIME_OUT
11-17 18:37:37.669 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - discarding deferred status: configuration_state=4
11-17 18:37:37.672 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - no more tasks, stopping service if no task are added in 5000 millis
11-17 18:37:37.685 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - task received
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: VvmTaskReceiver - TaskExecutor already running
11-17 18:37:37.688 2064-2064/com.google.android.dialer I/Dialer: Task.createTask - create task:com.android.voicemail.impl.ActivationTask
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: RetryPolicy - retry #2 for com.android.voicemail.impl.ActivationTask@66adaa2 queued, executing in 5000
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - com.android.voicemail.impl.ActivationTask@66adaa2 added
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - minimal wait time:4999
11-17 18:37:37.689 2064-2064/com.google.android.dialer I/Dialer: VvmTaskExecutor - sleep for 4999 millis
11-17 18:37:39.618 1378-1528/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 797294 , only wrote 644400
11-17 18:37:42.695 2064-3590/com.google.android.dialer I/Dialer: VvmTaskExecutor - executing task com.android.voicemail.impl.ActivationTask@66adaa2
11-17 18:37:42.697 2064-3590/com.google.android.dialer I/Dialer: PreOMigrationHandler - ComponentInfo{com.android.phone/com.android.services.telephony.TelephonyConnectionService}, [e2f7d48dd2b5ca523e7313cf4ba0f6ea830b6281], UserHandle{0} already migrated
11-17 18:37:42.740 2064-3590/com.google.android.dialer I/Dialer: VvmActivationTask - VVM content provider configured - vvm_type_cvvm
11-17 18:37:42.741 2064-3590/com.google.android.dialer I/Dialer: OmtpVvmCarrierCfgHlpr - OmtpEvent:CONFIG_ACTIVATING
11-17 18:37:42.763 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.setVisualVoicemailSmsFilterSettings - using TelephonyManager
11-17 18:37:42.767 2064-3590/com.google.android.dialer I/Dialer: TelephonyMangerCompat.sendVisualVoicemailSms - using TelephonyManager
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Do partial code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: After code cache collection, code=121KB, data=83KB
11-17 18:38:00.025 1716-1729/com.android.systemui I/zygote: Increasing code cache capacity to 512KB
11-17 18:38:00.026 1388-1413/? D/hwcomposer: hw_composer sent 18 syncs in 60s
11-17 18:38:08.586 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.587 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.609 1585-1599/system_process E/memtrack: Couldn't load memtrack module
11-17 18:38:08.609 1585-1599/system_process W/android.os.Debug: failed to get memory consumption info: -1
11-17 18:38:08.621 1585-1599/system_process E/memtrack: Couldn't load memtrack module

Uhh okay embarrassing, I just had to use a lower request code (RESULT_PICK_CONTACT was 85500). Thanks CommonsWare for pointing me towards Logcat. Haha... Thanks everyone for quick responses as well!

Body:
This work for me

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent
data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
             case RESULT_PICK_CONTACT:
                  Cursor cursorPickPhoneNo = null;
                  try {
                    String phonenumber = null ;
                    String name = null;
                    Uri uri = data.getData();
                    cursorPickPhoneNo = getContentResolver().query(uri, null, null, null, null);
                    cursorPickPhoneNo.moveToFirst();
                    int  index =cursorPickPhoneNo.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    phonenumber = cursorPickPhoneNo.getString(index);
                    Toast.makeText(this, ""+phonenumber, Toast.LENGTH_SHORT).show();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }
}


问:
Label each output of a multidimensional array being plotted
Working example:

```<code>%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def BoatFishSystem(state, t, *args):
    '''http://www.danham.me/r/2015/10/29/differential-eq.html'''
    A = args[0]
    B = args[1]
    C = args[2]
    fish, boat = state
    d_fish = fish * (A - boat - fish)
    d_boat = -boat * (B - C * fish)
    return [d_fish, d_boat]

A = 2.0
B = 1.0
C = 1.5
params = (A, B, C)
n_steps = 100000
t = np.linspace(0, 20, n_steps)
init_state = [1, 1]
species = odeint(BoatFishSystem, init_state, t, args = (params))

plt.plot(t, species, label = ['a', 'b'])
plt.legend()
plt.show()
</code>```

Desired result:
One output line is labelled 'a', the other one 'b'

Current result:
Both lines are labelled ['a', 'b']

答:
Move the labels into plt.legend():

```<code>plt.plot(t, species)
plt.legend(['a', 'b'])
</code>```

Body:
Working example:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

def BoatFishSystem(state, t, *args):
    '''http://www.danham.me/r/2015/10/29/differential-eq.html'''
    A = args[0]
    B = args[1]
    C = args[2]
    fish, boat = state
    d_fish = fish * (A - boat - fish)
    d_boat = -boat * (B - C * fish)
    return [d_fish, d_boat]

A = 2.0
B = 1.0
C = 1.5
params = (A, B, C)
n_steps = 100000
t = np.linspace(0, 20, n_steps)
init_state = [1, 1]
species = odeint(BoatFishSystem, init_state, t, args = (params))

plt.plot(t, species, label = ['a', 'b'])
plt.legend()
plt.show()

Desired result:
One output line is labelled 'a', the other one 'b'

Current result:
Both lines are labelled ['a', 'b']

Body:
Move the labels into plt.legend():

plt.plot(t, species)
plt.legend(['a', 'b'])


问:
Update and flashdata message not working on CodeIgniter
I've been working on a new CodeIgniter application and so far I've been able to create "page_categories" into the table, now my problem is when I try to update a certain category.

Let's say that I have two records on page_categories table:

Ok, now to be more specific when I try to change the name of "Page Category Two" rather than changing that name, my form updates the first record "Page Category One". Any idea how to fix this?

This is what I have on my controller:

```<code>public function edit($id){
    $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]');

    if($this->form_validation->run() == FALSE){
        // Get Current Subject
        $data['item'] = $this->Pages_categories_model->get($id);

        // Load template
        $this->template->load('admin', 'default', 'pages_categories/edit', $data);
    } else {
        $old_name = $this->Pages_categories_model->get($id)->name;
        $new_name = $this->input->post('name');

        // Create Post Array
        $data = array(
            'name'  => $this->input->post('name')
        );

        // Insert Subject
        $this->Pages_categories_model->update($id, $data);

        // Activity Array
        $data = array(
            'resource_id'   => $this->db->insert_id(),
            'type'          => 'subject',
            'action'        => 'updated',
            'user_id'       => 1,
            'message'       => 'A page category ('.$old_name.') was renamed to ('.$new_name.')'
        );

        // Insert Activity
        $this->Activity_model->add($data);

        // Set Message
        $this->session->set_flashdata('success', 'Page category has been updated');

        //Redirect
        redirect('admin/pages_categories');
    }
}
</code>```

and this is what I have on my model:

```<code><?php
class Pages_categories_model extends CI_MODEL{
    function __construct(){
        parent::__construct();
        $this->table = 'pages_categories';
    }

    public function get_list(){
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id){
        $query = $this->db->get($this->table);
        $this->db->where('id', $id);
        return $query->row();
    }

    public function add($data){
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data){
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id){
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }
}
</code>```

and finally my view:

```<code><h2 class="page-header">Edit Page Category</h2>

<?php echo form_open('admin/pages_categories/edit/'.$item->id); ?>
    <div class="form-group">
        <?php echo form_label('Page Category Name', 'name'); ?>
        <?php
            $data = array(
                'name' => 'name',
                'id'    => 'name',
                'maxlength' => '100',
                'class'     => 'form-control',
                'value'     => $item->name,
            );
        ?>
        <?php echo form_input($data); ?>
    </div>

    <?php echo form_submit('mysubmit', 'Update Page Category', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>
</code>```

I would like to say that my flash data message is not working as I expected. (It's not that important though.)

I want the flash-data message to be displayed in a different view; here it is my view:

Page Categories

<?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>

              Success!! <?php echo $this->session->flashdata('success'); ?>

     <?php } ?>
<?php if($this->session->flashdata('error')) : ?>
 <?php echo '
'.$this->session->flashdata('error').'
'; ?>
<?php endif; ?>

<?php if($subjects) : ?>

  ID
  Name
  Date Created

 <?php foreach($subjects as $subject) : ?>
 <?php $date = strtotime($subject->create_date); ?>
 <?php $formatted_date = date('F j, Y, g:i a', $date); ?>

   <?php echo $subject->id; ?>
   <?php echo $subject->name; ?>
   <?php echo $formatted_date; ?>

    <?php echo anchor('admin/pages_categories/edit/'.$subject->id.'', 'Edit', 'class="btn btn-default"'); ?>
    <?php echo anchor('admin/pages_categories/delete/'.$subject->id.'', 'Delete', 'class="btn btn-danger"'); ?>

 <?php endforeach; ?>

<?php else : ?>

No Page Category Found

<?php endif; ?>```

答:
Have you tried echoing the $id in the controller? Your code doesn't seem like having any problem.

About flash data, you are not using it anywhere in the view. That's why it is not getting displayed.

```<code><?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>
           <div class="alert alert-success">
              <strong>Success!! </strong><?php echo $this->session->flashdata('success'); ?>
           </div>
     <?php } ?>
</code>```

This will work fine.

Body:
I've been working on a new CodeIgniter application and so far I've been able to create "page_categories" into the table, now my problem is when I try to update a certain category.

Let's say that I have two records on page_categories table:

Ok, now to be more specific when I try to change the name of "Page Category Two" rather than changing that name, my form updates the first record "Page Category One". Any idea how to fix this?

This is what I have on my controller:

public function edit($id){
    $this->form_validation->set_rules('name', 'Name', 'trim|required|min_length[3]');

    if($this->form_validation->run() == FALSE){
        // Get Current Subject
        $data['item'] = $this->Pages_categories_model->get($id);

        // Load template
        $this->template->load('admin', 'default', 'pages_categories/edit', $data);
    } else {
        $old_name = $this->Pages_categories_model->get($id)->name;
        $new_name = $this->input->post('name');

        // Create Post Array
        $data = array(
            'name'  => $this->input->post('name')
        );

        // Insert Subject
        $this->Pages_categories_model->update($id, $data);

        // Activity Array
        $data = array(
            'resource_id'   => $this->db->insert_id(),
            'type'          => 'subject',
            'action'        => 'updated',
            'user_id'       => 1,
            'message'       => 'A page category ('.$old_name.') was renamed to ('.$new_name.')'
        );

        // Insert Activity
        $this->Activity_model->add($data);

        // Set Message
        $this->session->set_flashdata('success', 'Page category has been updated');

        //Redirect
        redirect('admin/pages_categories');
    }
}

and this is what I have on my model:

<?php
class Pages_categories_model extends CI_MODEL{
    function __construct(){
        parent::__construct();
        $this->table = 'pages_categories';
    }

    public function get_list(){
        $query = $this->db->get($this->table);
        return $query->result();
    }

    public function get($id){
        $query = $this->db->get($this->table);
        $this->db->where('id', $id);
        return $query->row();
    }

    public function add($data){
        $this->db->insert($this->table, $data);
    }

    public function update($id, $data){
        $this->db->where('id', $id);
        $this->db->update($this->table, $data);
    }

    public function delete($id){
        $this->db->where('id', $id);
        $this->db->delete($this->table);
    }
}

and finally my view:

Edit Page Category

<?php echo form_open('admin/pages_categories/edit/'.$item->id); ?>

        <?php echo form_label('Page Category Name', 'name'); ?>
        <?php
            $data = array(
                'name' => 'name',
                'id'    => 'name',
                'maxlength' => '100',
                'class'     => 'form-control',
                'value'     => $item->name,
            );
        ?>
        <?php echo form_input($data); ?>

    <?php echo form_submit('mysubmit', 'Update Page Category', array('class' => 'btn btn-primary')); ?>
<?php echo form_close(); ?>

I would like to say that my flash data message is not working as I expected. (It's not that important though.)

I want the flash-data message to be displayed in a different view; here it is my view:

Page Categories

<?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>

              Success!! <?php echo $this->session->flashdata('success'); ?>

     <?php } ?>
<?php if($this->session->flashdata('error')) : ?>
 <?php echo '
'.$this->session->flashdata('error').'
'; ?>
<?php endif; ?>

<?php if($subjects) : ?>

  ID
  Name
  Date Created

 <?php foreach($subjects as $subject) : ?>
 <?php $date = strtotime($subject->create_date); ?>
 <?php $formatted_date = date('F j, Y, g:i a', $date); ?>

   <?php echo $subject->id; ?>
   <?php echo $subject->name; ?>
   <?php echo $formatted_date; ?>

    <?php echo anchor('admin/pages_categories/edit/'.$subject->id.'', 'Edit', 'class="btn btn-default"'); ?>
    <?php echo anchor('admin/pages_categories/delete/'.$subject->id.'', 'Delete', 'class="btn btn-danger"'); ?>

 <?php endforeach; ?>

<?php else : ?>

No Page Category Found

<?php endif; ?>

Body:
Have you tried echoing the $id in the controller? Your code doesn't seem like having any problem.

About flash data, you are not using it anywhere in the view. That's why it is not getting displayed.

<?php $CI =& get_instance(); if($CI->session->flashdata('success'){ ?>
           <div class="alert alert-success">
              <strong>Success!! </strong><?php echo $this->session->flashdata('success'); ?>
           </div>
     <?php } ?>

This will work fine.


问:
What are the downsides of sqlserver 2008 (vs 2005)
I'm starting a new project and I'm considering using sqlserver 2008.

I've had a lot of trouble getting teamsystem to work with it, and I'm wondering if sql server 2008 is widely used in productions environment yet.

What whould you choose? How do you compare sqlserver 2005 and 2008?

EDIT : I agree about the obvious and general tradeoff between new (new features, one painfull migration avoided in the future) and old (less bugs, more documentation). I've already browse the web about differences between 2005 and 2008. My question is more specific : Are YOU using 2008? are YOU experiencing problems (such as the FTS mentionned below?)

答:
This is always a risk in moving to a new version of a program.  These are some questions you should be asking yourself:

Have you already completed a lot of manual testing on the old version?

Can you cope with a bug in the new version?

How long has the new version been in use by other people?

Are you at the start or end of a project cycle?

The big risk in not moving to the new version now is that:

You will be forced to move later and that may not be such a good time for you.  (But you may be able to skip a release so not having to repeat the pain as many times)

You can’t use what has been added to the new version

In the long term a lot less people will know how to use the old version

It is not good for your staff’s CV to be using too many very old versions of different things – hence it may affect your staff turnover etc.

So you need to plot, “pain” and “benefit” against time and then you will clearly see the right time to move; however we can’t see forward in time, and we can’t move back in time!

OwnerDisplayName: Brann

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Brann


问:
how to modify the width of search container column text?
how to modify the width of search container column text?

I want to change the width of the  table.

I used the attribute cssClass of <liferay-ui:search-container-column-text> liferay taglib but I did not work for me.

Table header:

table

view.jsp:

```<code>    <liferay-ui:search-container orderByCol="<%=sortByCol%>"
     orderByType="<%=sortByType%>" iteratorURL="<%=url%>"
     delta="10" emptyResultsMessage="no-result">
    <liferay-ui:search-container-results>
      <% //some code %>
    </liferay-ui:search-container-results>
    <liferay-ui:search-container-row modelVar="file"
                            className="DLFileEntry">
        <liferay-ui:search-container-column-text name="Val1"
                                    cssClass="txt-capitalize width-11" value="<%=value1%>" />
        <liferay-ui:search-container-column-text name="Val2"
                                    cssClass="txt-capitalize width-11" value="<%=value2%>" />
        <liferay-ui:search-container-column-text name="Val3"
                                    cssClass="txt-capitalize width-11" value="<%=value3%>" />
        <liferay-ui:search-container-column-text name="Value4"
                                    cssClass="txt-capitalize width-11" value="<%=value4%>" />
        <liferay-ui:search-container-column-text name="Val5"
                                    cssClass="txt-capitalize width-11" value="<%=value5%>" />
<!-- some other search-container-column-text -->
    </liferay-ui:search-container-row>
    <liferay-ui:search-iterator
        searchContainer="<%= searchContainer %>"
        paginate="${fn:length(listFiles) ge 10}" />
    </liferay-ui:search-container>
</code>```

main.css:

```<code>.width-11{
    width:11%;
    padding-left: 5px;
    padding-right: 0;

}
</code>```

Update

If I inspect the code in the browser we can see the css class that exist.

inspect table row

答:
You need to distribute width % properly so that it aggregate to 100%;

width: 11% would be only 55% (as there are 5 column in your table) and remaing 45% will be evenly distributed.

Body:
how to modify the width of search container column text?

I want to change the width of the  table.

I used the attribute cssClass of <liferay-ui:search-container-column-text> liferay taglib but I did not work for me.

Table header:

table

view.jsp:

    <liferay-ui:search-container orderByCol="<%=sortByCol%>"
     orderByType="<%=sortByType%>" iteratorURL="<%=url%>"
     delta="10" emptyResultsMessage="no-result">
    <liferay-ui:search-container-results>
      <% //some code %>
    </liferay-ui:search-container-results>
    <liferay-ui:search-container-row modelVar="file"
                            className="DLFileEntry">
        <liferay-ui:search-container-column-text name="Val1"
                                    cssClass="txt-capitalize width-11" value="<%=value1%>" />
        <liferay-ui:search-container-column-text name="Val2"
                                    cssClass="txt-capitalize width-11" value="<%=value2%>" />
        <liferay-ui:search-container-column-text name="Val3"
                                    cssClass="txt-capitalize width-11" value="<%=value3%>" />
        <liferay-ui:search-container-column-text name="Value4"
                                    cssClass="txt-capitalize width-11" value="<%=value4%>" />
        <liferay-ui:search-container-column-text name="Val5"
                                    cssClass="txt-capitalize width-11" value="<%=value5%>" />

    </liferay-ui:search-container-row>
    <liferay-ui:search-iterator
        searchContainer="<%= searchContainer %>"
        paginate="${fn:length(listFiles) ge 10}" />
    </liferay-ui:search-container>

main.css:

.width-11{
    width:11%;
    padding-left: 5px;
    padding-right: 0;

}

Update

If I inspect the code in the browser we can see the css class that exist.

inspect table row


问:
Adding AWG Noise with standard deviation of 1.75, to the signal generated in Matlab
I'm quite new to Matlab and I'm kind of stuck.

This is what the question is asking for.

Add AWG Noise with standard deviation of 1.75, to the signal you just generated.

This is the signal code:

```<code>fs = 20000; %Sample Rate (Hz)
f = 1200; %frequency of signal
A = 2.5; % amplitude of signal
phi = pi / 4;
t = [0:(1/fs):0.05] ;
y = A * sin ( 2 * pi * f * t + phi ) + 3;
% sine wave 1 [Hz], phase shift 0°, amplitude of 1 vpp
plot ( t, y ); %Plot the waveform you just created
%Label the axis and title the plot
xlabel ( 'time [sec]' );
ylabel ( 'amplitude [volt]' );
xlim([0 0.05])
ylim([0 6])
</code>```

答:
You can generate Gaussian noise samples with a standard deviation of 1.75 as '1.75 * randn(1, numel(y))'. The command 'randn' generates Gaussian pseudorandom numbers with mean = 0 and standard deviation = 1. Here is your code with added Gaussian noise:

```<code>        fs = 20000; %Sample Rate (Hz)

        f = 1200; %frequency of signal

        A = 2.5; % amplitude of signal

        phi = pi / 4;

        t = [0:(1/fs):0.05] ;

        y = A * sin ( 2 * pi * f * t + phi ) + 3; % sine wave 1 [Hz], phase shift 0°, amplitude of 1 vpp

        n = 1.75 * randn(1, numel(y)); % AWGN with a standard deviation of 1.75

        fprintf('The standard deviation of the added noise is %f \n ', std(n));

        figure;

        plot ( t, y ); %Plot the waveform you just created

        %Label the axis and title the plot

        xlabel ( 'time [sec]' );

        ylabel ( 'amplitude [volt]' );

        xlim([0 0.05])

        ylim([0 6])

        figure;

        plot(t, y + n);

        xlabel ( 'time [sec]' );

        ylabel ( 'amplitude [volt]' );
</code>```

The standard deviation of the noise changes significantly with every run. If you increase the number of samples in 't', the standard deviation of the generated noise will be very stable.

Body:
I'm quite new to Matlab and I'm kind of stuck.

This is what the question is asking for.

Add AWG Noise with standard deviation of 1.75, to the signal you just generated.

This is the signal code:

fs = 20000; %Sample Rate (Hz)
f = 1200; %frequency of signal
A = 2.5; % amplitude of signal
phi = pi / 4;
t = [0:(1/fs):0.05] ;
y = A * sin ( 2 * pi * f * t + phi ) + 3;
% sine wave 1 [Hz], phase shift 0°, amplitude of 1 vpp
plot ( t, y ); %Plot the waveform you just created
%Label the axis and title the plot
xlabel ( 'time [sec]' );
ylabel ( 'amplitude [volt]' );
xlim([0 0.05])
ylim([0 6])

Body:
You can generate Gaussian noise samples with a standard deviation of 1.75 as '1.75 * randn(1, numel(y))'. The command 'randn' generates Gaussian pseudorandom numbers with mean = 0 and standard deviation = 1. Here is your code with added Gaussian noise:

        fs = 20000; %Sample Rate (Hz)

        f = 1200; %frequency of signal

        A = 2.5; % amplitude of signal

        phi = pi / 4;

        t = [0:(1/fs):0.05] ;

        y = A * sin ( 2 * pi * f * t + phi ) + 3; % sine wave 1 [Hz], phase shift 0°, amplitude of 1 vpp

        n = 1.75 * randn(1, numel(y)); % AWGN with a standard deviation of 1.75

        fprintf('The standard deviation of the added noise is %f \n ', std(n));

        figure;

        plot ( t, y ); %Plot the waveform you just created

        %Label the axis and title the plot

        xlabel ( 'time [sec]' );

        ylabel ( 'amplitude [volt]' );

        xlim([0 0.05])

        ylim([0 6])

        figure;

        plot(t, y + n);

        xlabel ( 'time [sec]' );

        ylabel ( 'amplitude [volt]' );

The standard deviation of the noise changes significantly with every run. If you increase the number of samples in 't', the standard deviation of the generated noise will be very stable.


问:
How to auto scroll UIScrollView using timer?
I have a UIScrollView to show images. I need a timer to show the images one after another, after every 5 seconds. How to initiate UIScrollView event to move to the next image after 5 seconds using the timer?

答:
Swift version

Add the following properties

```<code>var offSet: CGFloat = 0

@IBOutlet weak var imagePageControl: UIPageControl!
@IBOutlet weak var imageScrollView: UIScrollView!

let imageArray = [your images]
</code>```

Modify the viewDidLoad()

```<code>    override func viewDidLoad() {
    super.viewDidLoad()
    self.offSet = 0
    let timer = Timer.scheduledTimer(timeInterval: 8, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

    imagePageControl.numberOfPages = bannerArray.count
    imageScrollView.isPagingEnabled = true
    imageScrollView.contentSize.height = 200
    imageScrollView.contentSize.width = self.view.bounds.width * CGFloat(bannerArray.count)
    imageScrollView.showsHorizontalScrollIndicator = false

    imageScrollView.delegate = self

    for (index, image) in imageArray.enumerated() {
        let image = image
        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFill
        imageView.frame.size.width = self.view.bounds.size.width
        imageView.frame.size.height = 200
        imageView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width
        imageScrollView.addSubview(imageView)
    }
}
</code>```

create this function for automatic scroll

```<code>    func autoScroll() {
    let totalPossibleOffset = CGFloat(imageArray.count - 1) * self.view.bounds.size.width
    if offSet == totalPossibleOffset {
        offSet = 0 // come back to the first image after the last image
    }
    else {
    offSet += self.view.bounds.size.width
    }
    DispatchQueue.main.async() {
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
            self.imageScrollView.contentOffset.x = CGFloat(self.offSet)
        }, completion: nil)
    }
}
</code>```

Add this function for manual scroll

```<code>    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let page = scrollView.contentOffset.x / scrollView.frame.size.width
    imagePageControl.currentPage = Int(page)
    self.offSet = page * scrollView.frame.size.width // this updates offset value so that automatic scroll begins from the image you arrived at manually
}
</code>```

Note: Though the question is specific to automatic scroll, I have added manual scroll as well. So that both automatic scroll and manual scroll work in tandem.
Also, I have added a UIPageControl. Please remove the imagePageControl if you don't need it.

Body:
Swift version

Add the following properties

var offSet: CGFloat = 0

@IBOutlet weak var imagePageControl: UIPageControl!
@IBOutlet weak var imageScrollView: UIScrollView!

let imageArray = [your images]

Modify the viewDidLoad()

    override func viewDidLoad() {
    super.viewDidLoad()
    self.offSet = 0
    let timer = Timer.scheduledTimer(timeInterval: 8, target: self, selector: #selector(autoScroll), userInfo: nil, repeats: true)

    imagePageControl.numberOfPages = bannerArray.count
    imageScrollView.isPagingEnabled = true
    imageScrollView.contentSize.height = 200
    imageScrollView.contentSize.width = self.view.bounds.width * CGFloat(bannerArray.count)
    imageScrollView.showsHorizontalScrollIndicator = false

    imageScrollView.delegate = self

    for (index, image) in imageArray.enumerated() {
        let image = image
        let imageView = UIImageView(image: image)
        imageView.contentMode = .scaleAspectFill
        imageView.frame.size.width = self.view.bounds.size.width
        imageView.frame.size.height = 200
        imageView.frame.origin.x = CGFloat(index) * self.view.bounds.size.width
        imageScrollView.addSubview(imageView)
    }
}

create this function for automatic scroll

    func autoScroll() {
    let totalPossibleOffset = CGFloat(imageArray.count - 1) * self.view.bounds.size.width
    if offSet == totalPossibleOffset {
        offSet = 0 // come back to the first image after the last image
    }
    else {
    offSet += self.view.bounds.size.width
    }
    DispatchQueue.main.async() {
        UIView.animate(withDuration: 0.3, delay: 0, options: UIViewAnimationOptions.curveLinear, animations: {
            self.imageScrollView.contentOffset.x = CGFloat(self.offSet)
        }, completion: nil)
    }
}

Add this function for manual scroll

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let page = scrollView.contentOffset.x / scrollView.frame.size.width
    imagePageControl.currentPage = Int(page)
    self.offSet = page * scrollView.frame.size.width // this updates offset value so that automatic scroll begins from the image you arrived at manually
}

Note: Though the question is specific to automatic scroll, I have added manual scroll as well. So that both automatic scroll and manual scroll work in tandem.
Also, I have added a UIPageControl. Please remove the imagePageControl if you don't need it.


问:
Can't receive UDP Packets in Java
I'm trying to receive some UDP packets on a Java MulticastSocket.

I can see the packets arriving in wireshark and the code works for other people, but not for me.

I honestly don't know what I'm doing wrong.

I have disabled my firewall and antivirus.

I'm running Windows 10 and IntelliJ 2017.2.5.

I'm creating a MulticastSocket with a portnumber (2000 or 2001) as a parameter.

My JRE is 1.8.0_152 and I'm using the JDK supplied by JetBrains.

This is how I'm creating the MulticastSocket:

```<code>this.socket = new MulticastSocket(this.portNum);
//this.socket = new MulticastSocket();
this.socket.setReceiveBufferSize(1 << 17);
this.socket.joinGroup(InetAddress.getByName(this.ip));
</code>```

And, in a while loop, I try to receive data like this:

```<code>while(!this.socket.isClosed())
    {
        byte[] buffer = new byte[500];
        DatagramPacket incomingPacket = new DatagramPacket(buffer, buffer.length);
        try
        {
            this.socket.receive(incomingPacket);
            ...
</code>```

答: The problem has been solved, it was an unrelated concurrency issue. </p>

Title: Can't receive UDP Packets in Java

Body:
I'm trying to receive some UDP packets on a Java MulticastSocket.

I can see the packets arriving in wireshark and the code works for other people, but not for me.

I honestly don't know what I'm doing wrong.

I have disabled my firewall and antivirus.

I'm running Windows 10 and IntelliJ 2017.2.5.

I'm creating a MulticastSocket with a portnumber (2000 or 2001) as a parameter.

My JRE is 1.8.0_152 and I'm using the JDK supplied by JetBrains.

This is how I'm creating the MulticastSocket:

this.socket = new MulticastSocket(this.portNum);
//this.socket = new MulticastSocket();
this.socket.setReceiveBufferSize(1 << 17);
this.socket.joinGroup(InetAddress.getByName(this.ip));

And, in a while loop, I try to receive data like this:

while(!this.socket.isClosed())
    {
        byte[] buffer = new byte[500];
        DatagramPacket incomingPacket = new DatagramPacket(buffer, buffer.length);
        try
        {
            this.socket.receive(incomingPacket);
            ...


问:
Why doesn't C++ support range based for loop for dynamic arrays?
Why doesn't C++ support range based for loop over dynamic arrays?  That is, something like this:

```<code>int* array = new int[len];
for[] (int i : array) {};
</code>```

I just invented the for[] statement to rhyme with new[] and delete[].  As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work) so in theory, range based for loop could also be made to work.  What is the reason that it's not made to work?

答:
This is not related to dynamic arrays, it is more general. Of course for dynamic arrays there exists somewhere the size to be able to call destructors (but remember that standard doesn't says anything about that, just that calling delete [] works as intended).

The problem is with pointers in general as given a pointer you can't tell if it correspond to any kind of...what?

Arrays decay to pointers but given a pointer what can you say?

Body:
Why doesn't C++ support range based for loop over dynamic arrays?  That is, something like this:

int* array = new int[len];
for[] (int i : array) {};

I just invented the for[] statement to rhyme with new[] and delete[].  As far as I understand, the runtime has the size of the array available (otherwise delete[] could not work) so in theory, range based for loop could also be made to work.  What is the reason that it's not made to work?


问:
Caused by: java.lang.IllegalArgumentException: Comparison method violates its general contract
I'm trying to sort a collection of loans where the statuses of loans are  Active, Rejected, Pending and Approved.Active loans should get the highest priority and the others in any order.I implemented the Comparator interface's compare().

here 's the implementation of compare()

```<code>@Override
public int compare(Object o1, Object o2) {
    LoanAccountData loanAccountData1 = (LoanAccountData) o1;
    LoanAccountData loanAccountData2 = (LoanAccountData) o2;

    if (loanAccountData1.getStatusStringValue().equals("Active")) {
        return -1;
    } else {
        return 1;
    }
}
</code>```

答:
Here :

```<code>if (loanAccountData1.getStatusStringValue().equals("Active")) {
    return -1;
</code>```

You never compare with the second object.

If both loanAccountData1.getStatusStringValue().equals("Active")
and loanAccountData2.getStatusStringValue().equals("Active") are true, you violate the symmetric principle as you should return 0.

With a Generic Comparator you could write :

```<code>public class LoanAccountDataComparatorByStatusActive implements Comparator<LoanAccountData> {

    @Override
    public int compare(LoanAccountData  o1, LoanAccountData o2) {

        boolean isData1StatusActive = o1.getStatusStringValue().equals("Active");
        boolean isData2StatusActive = o2.getStatusStringValue().equals("Active");

        // if both status active, these have the same rank
        if (isData1StatusActive && isData2StatusActive){
           return 0;
        }

        if (isData1StatusActive){
           return -1;
        }

        if (isData2StatusActive){
           return 1;
        }
        // if no status active, these have the same rank
        return 0;
    }

}
</code>```

Note that it assumes that getStatusStringValue() never returns null.

Otherwise add required checks before referencing it.

Body:
I'm trying to sort a collection of loans where the statuses of loans are  Active, Rejected, Pending and Approved.Active loans should get the highest priority and the others in any order.I implemented the Comparator interface's compare().

here 's the implementation of compare()

@Override
public int compare(Object o1, Object o2) {
    LoanAccountData loanAccountData1 = (LoanAccountData) o1;
    LoanAccountData loanAccountData2 = (LoanAccountData) o2;

    if (loanAccountData1.getStatusStringValue().equals("Active")) {
        return -1;
    } else {
        return 1;
    }
}

Body:
Here :

if (loanAccountData1.getStatusStringValue().equals("Active")) {
    return -1;

You never compare with the second object.

If both loanAccountData1.getStatusStringValue().equals("Active")
and loanAccountData2.getStatusStringValue().equals("Active") are true, you violate the symmetric principle as you should return 0.

With a Generic Comparator you could write :

public class LoanAccountDataComparatorByStatusActive implements Comparator<LoanAccountData> {

    @Override
    public int compare(LoanAccountData  o1, LoanAccountData o2) {

        boolean isData1StatusActive = o1.getStatusStringValue().equals("Active");
        boolean isData2StatusActive = o2.getStatusStringValue().equals("Active");

        // if both status active, these have the same rank
        if (isData1StatusActive && isData2StatusActive){
           return 0;
        }

        if (isData1StatusActive){
           return -1;
        }

        if (isData2StatusActive){
           return 1;
        }
        // if no status active, these have the same rank
        return 0;
    }

}

Note that it assumes that getStatusStringValue() never returns null.

Otherwise add required checks before referencing it.


问:
Windows C++ multibyte / unicode
In Windows C++ multibyte / unicode considerations, I notice that _tcslen() and lstrlen() both provide a string's length correctly regardless of whether you're compiling to multibyte or unicode.

_tcslen() is defined in TCHAR.H based on the def _UNICODE and lstrlen() is defined in WINBASE.H based on the def UNICODE.

Did someone just re-invent the wheel at some point or is there a reason for this apparent duplication?

答:
lstrlen and other lstrxxx functions are Windows APIs. They have ANSI and Unicode versions lstrlenA and lstrenW. They had some advantages over strlen back in the days of Windows 3.1. They don't have any advantages now. If you write your code with these functions it will not be compatible with any standard in C, it will only compile in Windows.

_tstrlen is a macro for either ANSI strlen or Unicode wcslen which are standard C. This was useful in the 1990s and early 2000s because you could write one set of code which could be compiled in ANSI for Windows 95, and Unicode for Windows NT. It's also useful because Microsoft can write one set of documentation for both ANSI and Unicode.

Otherwise these _tstrxxx string macros and TCHAR etc. are no longer useful. There is no point to go through all this pain to write code which is compatible for Windows 95. You can just use "wide c-string" wcsxxx functions which are standard C.

But then, the *nix operating systems use UTF-8 and strxxx functions. As opposed to Windows which uses UTF-16 and wcsxxx. I suppose you could use the _tstrxxx macros to write code which is Unicode compatible in both *nix and Windows. Other programmers will be confused by your _tstrxxx macros but at least the code has a better chance to compile!

Title: Windows C++ multibyte / unicode


问:
Error: lexical error in RQGIS R statistics QGIS integration
I am new to this forum and also new to the package RQGIS which I am trying to use in R.

I installed the latest QGIS, R, Rstudio versions and downloaded & installed the RQGIS library with all dependencies on Windows 10.

I followed the instructions of the vignette("install_guide", package = "RQGIS"). But i didn't got far because when I run:

```<code>vignette("install_guide", package = "RQGIS")
library("RQGIS")

set_env(root = "C:\\Programme\\QGIS 2.18\\")
find_algorithms(search_term = "([Pp]olygon)(centroid")
</code>```

I get an error message:

```<code>Error: lexical error: invalid char in json text.
                                   Traceback (most recent call las
                 (right here) ------^
In addition: Warning messages:
1: running command '"C:\ANACON~1/Scripts/conda.exe" info --json' had   status 1
2: running command '"C:\ANACON~1/Scripts/conda.exe" info --json' had status 1
</code>```

traceback shows:

```<code>13: .Call(R_parse, txt, bigint_as_char)
12: parse_string(txt, bigint_as_char)
11: parseJSON(txt, bigint_as_char)
10: fromJSON_string(txt = txt, simplifyVector = simplifyVector, simplifyDataFrame = simplifyDataFrame,
    simplifyMatrix = simplifyMatrix, flatten = flatten, ...)
9: fromJSON(conda_envs)
8: conda_list(conda = conda)
7: rbind(conda_envs, conda_list(conda = conda))
6: python_environment_versions()
5: py_discover_config(required_module, use_environment)
4: initialize_python(required_module, use_environment)
3: ensure_python_initialized()
2: py_capture_output(py_run_string("processing.alglist()"))
1: find_algorithms(search_term = "([Pp]olygon)(centroid")
</code>```

the set_env detected the installation path:

```<code>$root
[1] "C:\\Program Files\\QGIS 2.18"

$qgis_prefix_path
[1] "C:\\Program Files\\QGIS 2.18\\apps\\qgis"

$python_plugins
[1] "C:\\Program Files\\QGIS 2.18\\apps\\qgis\\python\\plugins"
</code>```

but I have a version of Anaconda2 installed in a different folder. Is it possible that the PATH variable is set wrong? And if so what to change/add to the PATH?

thanks in advance for help!

Cheers,
Nils

答:
Actually, open_app() looks for Python binaries installed on your system, and will use the one shipped with QGIS (under Windows) while ignoring Anaconda installations.
But there was one problem when reticulate was updated to v1.1 which was solved with https://github.com/rstudio/reticulate/issues/100. Since then it should be possible again to run RQGIS (in conjunction with reticulate >= v1.2) while having also installed Anaconda Python.

Body:
I am new to this forum and also new to the package RQGIS which I am trying to use in R.

I installed the latest QGIS, R, Rstudio versions and downloaded & installed the RQGIS library with all dependencies on Windows 10.

I followed the instructions of the vignette("install_guide", package = "RQGIS"). But i didn't got far because when I run:

vignette("install_guide", package = "RQGIS")
library("RQGIS")

set_env(root = "C:\\Programme\\QGIS 2.18\\")
find_algorithms(search_term = "([Pp]olygon)(centroid")

I get an error message:

Error: lexical error: invalid char in json text.
                                   Traceback (most recent call las
                 (right here) ------^
In addition: Warning messages:
1: running command '"C:\ANACON~1/Scripts/conda.exe" info --json' had   status 1
2: running command '"C:\ANACON~1/Scripts/conda.exe" info --json' had status 1

traceback shows:

13: .Call(R_parse, txt, bigint_as_char)
12: parse_string(txt, bigint_as_char)
11: parseJSON(txt, bigint_as_char)
10: fromJSON_string(txt = txt, simplifyVector = simplifyVector, simplifyDataFrame = simplifyDataFrame,
    simplifyMatrix = simplifyMatrix, flatten = flatten, ...)
9: fromJSON(conda_envs)
8: conda_list(conda = conda)
7: rbind(conda_envs, conda_list(conda = conda))
6: python_environment_versions()
5: py_discover_config(required_module, use_environment)
4: initialize_python(required_module, use_environment)
3: ensure_python_initialized()
2: py_capture_output(py_run_string("processing.alglist()"))
1: find_algorithms(search_term = "([Pp]olygon)(centroid")

the set_env detected the installation path:

$root
[1] "C:\\Program Files\\QGIS 2.18"

$qgis_prefix_path
[1] "C:\\Program Files\\QGIS 2.18\\apps\\qgis"

$python_plugins
[1] "C:\\Program Files\\QGIS 2.18\\apps\\qgis\\python\\plugins"

but I have a version of Anaconda2 installed in a different folder. Is it possible that the PATH variable is set wrong? And if so what to change/add to the PATH?

thanks in advance for help!

Cheers,
Nils


问:
C++ template using multidimensional arrays
Is it possible in C++ to write this:

```<code>template <typename T, size_t dim, size_t len>
using A = /* something */;
</code>```

that will make these two lines equivalent:

```<code>/* 1 */ A<int, 3, 5> a;   A<char, 5, 3> c;

/* 2 */ int a[5][5][5];   char c[3][3][3][3][3];
</code>```

?

答:
Is it possible? Yes, you can do arbitrarily complex calculations at compile-time, so there certainly is a solution.

The most straightforward way is to just use template recursion, like so:

```<code>template <class T, size_t dim, size_t len>
struct A_helper {
    using type = typename A_helper<T, dim - 1, len>::type[len];
};

template <class T, size_t len>
struct A_helper<T, 0, len> {
    using type = T;
};

template <class T, size_t dim, size_t len>
using A = typename A_helper<T, dim, len>::type;
</code>```

See it on Coliru: http://coliru.stacked-crooked.com/a/bfc9052b30bce553

Body:
Is it possible in C++ to write this:

template <typename T, size_t dim, size_t len>
using A = /* something */;

that will make these two lines equivalent:

/* 1 */ A<int, 3, 5> a;   A<char, 5, 3> c;

/* 2 */ int a[5][5][5];   char c[3][3][3][3][3];

?

Body:
Is it possible? Yes, you can do arbitrarily complex calculations at compile-time, so there certainly is a solution.

The most straightforward way is to just use template recursion, like so:

template <class T, size_t dim, size_t len>
struct A_helper {
    using type = typename A_helper<T, dim - 1, len>::type[len];
};

template <class T, size_t len>
struct A_helper<T, 0, len> {
    using type = T;
};

template <class T, size_t dim, size_t len>
using A = typename A_helper<T, dim, len>::type;

See it on Coliru: http://coliru.stacked-crooked.com/a/bfc9052b30bce553


问:
Concatenate in SQL Server 2008 R2 failing when the monthid is 2 digits
I have a table like and server is SQL Server 2008 R2 where we cannot use concat function

```<code>YearID  |   MonthId
--------+----------
2017    |    1
2014    |    5
2014    |   10
2016    |   12
</code>```

I want to have the output as

```<code>201701
201405
201410
201612
</code>```

What I tried so far

```<code>select
    cast(YearId as varchar(50)) + '0' + cast(MonthId as varchar(50))
from
    TEST
</code>```

I am getting the output as

```<code>201701
201405
2014010
2016012
</code>```

When the monthID is 2 digits, it is failing.

How to tackle this situation?

答:
the simplest way is (imho):

```<code>SELECT CONVERT(VARCHAR(4), YearID) + RIGHT('0' + CONVERT(VARCHAR(2), MOnthId), 2)
FROM TEST;
</code>```

test here

Body:
I have a table like and server is SQL Server 2008 R2 where we cannot use concat function

YearID  |   MonthId
--------+----------
2017    |    1
2014    |    5
2014    |   10
2016    |   12

I want to have the output as

201701
201405
201410
201612

What I tried so far

select
    cast(YearId as varchar(50)) + '0' + cast(MonthId as varchar(50))
from
    TEST

I am getting the output as

201701
201405
2014010
2016012

When the monthID is 2 digits, it is failing.

How to tackle this situation?

Body:
the simplest way is (imho):

SELECT CONVERT(VARCHAR(4), YearID) + RIGHT('0' + CONVERT(VARCHAR(2), MOnthId), 2)
FROM TEST;

test here