问:
How to pass value from activity to Tab Fragment using replace Fragment?
I have activity , which I take a value from it and pass it to Tab Fragment
.. in the Tab Fragment ,I want to use this value to setText

The Problem is How to take this value to the Tab Fragment ?
I always get this Exception   java.lang.IllegalArgumentException: No view found for id ....for fragment Tab1 .. How to solve it ?

I used normal Tab activity in android studio and modified this method

homee.java

```<code>public Fragment getItem(int position) {
        switch (position){
            case 0:
                Tab1 tab1 =new Tab1();
                return tab1;
            case 1:
                Tab2 tab2 =new Tab2();
                return tab2;
            case 2:
                Tab3 tab3 =new Tab3();
                return tab3;
        }
        return null ;
    }
</code>```

this is my activity number.java

```<code>public class number extends AppCompatActivity {
Button add,save;
TextView num;
int n;
String stringNum;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_number);

    add =  findViewById(R.id.idadd);
    save =  findViewById(R.id.idsave);
    num = findViewById(R.id.idnum);

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //simple method
            n = Integer.parseInt(num.getText().toString());
            num.setText(++n +"");
        }
    });

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stringNum= num.getText().toString();
// I want to pass this value to Tab1 Fragment by replaceFragment or by any
//way
            Bundle bundle = new Bundle();
            bundle.putString("key", stringNum);
            Tab1 myFragment = new Tab1();
            myFragment.setArguments(bundle);

     getSupportFragmentManager().beginTransaction().replace
     (R.id.container,myFragment).commit();
            finish();
        }
    });
}}
</code>```

this is Tab1 child of Tab activity

```<code>public class Tab1 extends Fragment {

Button get,update;
TextView txt;

public Tab1(){}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1, container, false);

    get = view.findViewById(R.id.idget);
    update = view.findViewById(R.id.idup);
    txt = view.findViewById(R.id.textView);

    get.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent in = new Intent(getContext(), number.class);
            startActivity(in);
        }
    });

    update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String Number= getArguments().getString("key").toString();
            //here the problem
            txt.setText(Number);
        }
    });

        return view;
        }
    }
</code>```

activity_homee.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="eg.noname.opo.homee">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_weight="1"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="@string/app_name">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_1" />

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_2" />

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_3" />

    </android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
</code>```

tab1.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fra">

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="111dp"
    android:text="TextView"
    android:textAlignment="center"
    android:textSize="30sp" />

<Button
    android:id="@+id/idget"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="88dp"
    android:text="get" />

<Button
    android:id="@+id/idup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="update" />
</LinearLayout>
</code>```

Edit I solved it by call static method which return this value , but still I should press on Button in Fragment to update the value to the new one , I am trying to find a way to update the value automatically when I pass it from my  activity .. any help ?

答:
in activity number.java</p>

```<code>  in onCreate method just call
  String Number= getArguments().getString("key").toString();
        //here the problem
        txt.setText(Number)
</code>```

Body:
I have activity , which I take a value from it and pass it to Tab Fragment
.. in the Tab Fragment ,I want to use this value to setText

The Problem is How to take this value to the Tab Fragment ?
I always get this Exception   java.lang.IllegalArgumentException: No view found for id ....for fragment Tab1 .. How to solve it ?

I used normal Tab activity in android studio and modified this method

homee.java

public Fragment getItem(int position) {
        switch (position){
            case 0:
                Tab1 tab1 =new Tab1();
                return tab1;
            case 1:
                Tab2 tab2 =new Tab2();
                return tab2;
            case 2:
                Tab3 tab3 =new Tab3();
                return tab3;
        }
        return null ;
    }

this is my activity number.java

public class number extends AppCompatActivity {
Button add,save;
TextView num;
int n;
String stringNum;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_number);

    add =  findViewById(R.id.idadd);
    save =  findViewById(R.id.idsave);
    num = findViewById(R.id.idnum);

    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //simple method
            n = Integer.parseInt(num.getText().toString());
            num.setText(++n +"");
        }
    });

    save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            stringNum= num.getText().toString();
// I want to pass this value to Tab1 Fragment by replaceFragment or by any
//way
            Bundle bundle = new Bundle();
            bundle.putString("key", stringNum);
            Tab1 myFragment = new Tab1();
            myFragment.setArguments(bundle);

     getSupportFragmentManager().beginTransaction().replace
     (R.id.container,myFragment).commit();
            finish();
        }
    });
}}

this is Tab1 child of Tab activity

public class Tab1 extends Fragment {

Button get,update;
TextView txt;

public Tab1(){}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.tab1, container, false);

    get = view.findViewById(R.id.idget);
    update = view.findViewById(R.id.idup);
    txt = view.findViewById(R.id.textView);

    get.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent in = new Intent(getContext(), number.class);
            startActivity(in);
        }
    });

    update.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String Number= getArguments().getString("key").toString();
            //here the problem
            txt.setText(Number);
        }
    });

        return view;
        }
    }

activity_homee.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="eg.noname.opo.homee">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_weight="1"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:title="@string/app_name">

    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_1" />

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_2" />

        <android.support.design.widget.TabItem
            android:id="@+id/tabItem3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/tab_text_3" />

    </android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

tab1.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/fra">

<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="111dp"
    android:text="TextView"
    android:textAlignment="center"
    android:textSize="30sp" />

<Button
    android:id="@+id/idget"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="88dp"
    android:text="get" />

<Button
    android:id="@+id/idup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="update" />
</LinearLayout>

Edit I solved it by call static method which return this value , but still I should press on Button in Fragment to update the value to the new one , I am trying to find a way to update the value automatically when I pass it from my  activity .. any help ?

Body:
in activity number.java

  in onCreate method just call
  String Number= getArguments().getString("key").toString();
        //here the problem
        txt.setText(Number)


来源: stackexchange

问:
Dagger with Mvp on Kotlin - Android
I am an Android developer that is just getting into Kotlin, and I have been trying to setup an Mvp Dagger application in Kotlin, but I cannot figure out what is going on.  I continue to get this error:

```<code>Error:dagger.internal.codegen.ComponentProcessor was unable to process this interface
because not all of its dependencies could be resolved.
Check for compilation errors or a circular dependency with generated code.
</code>```

Here is my code:

KotlinApplication:

```<code>class KotlinApplication: MultiDexApplication(), HasActivityInjector {

    @Inject lateinit var injector: DispatchingAndroidInjector<Activity>

    override fun onCreate() {
        super.onCreate()
        inject()
    }

    override fun activityInjector(): AndroidInjector<Activity> {
        return injector
    }

    fun inject() {
        DaggerAppComponent.builder().application(this).build().inject(this);
    }

}
</code>```

AppComponent:

```<code>@Singleton
@Component(modules = arrayOf(AppModule::class, InjectionModule::class))
interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(app: KotlinApplication): Builder

        fun build(): AppComponent
    }

    fun inject(app: KotlinApplication)

}
</code>```

AppModule:

```<code>@Module
class AppModule {
    @Singleton
    @Provides
    fun provideAppContext(app: KotlinApplication): Context {
        return app
    }

    @Singleton
    @Provides
    fun provideApplication(app: KotlinApplication): Application {
        return app
    }
}
</code>```

InjectionModule:

```<code>@Module
abstract class InjectionModule {

    @ActivityScope
    @ContributesAndroidInjector(modules = arrayOf(MainModule::class))
    internal abstract fun bindMainActivity(): MainActivity

}
</code>```

MainActivity:

```<code>class MainActivity : AppCompatActivity(), MainMvp.View {

    @Inject lateinit var presenter: MainMvp.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
</code>```

MainMvp:

```<code>interface MainMvp {
    interface View {

    }

    interface Presenter {

    }
}
</code>```

MainPresenter:

```<code>class MainPresenter(view: MainMvp.View): MainMvp.Presenter {

    var view: MainMvp.View

    init {
        this.view = view
    }

}
</code>```

MainBindModule:

```<code>@Module
interface MainBindModule {
    @ActivityScope
    @Binds
    fun bindView(activity: MainActivity): MainMvp.View
}
</code>```

MainModule:

```<code>@Module(includes = arrayOf(MainBindModule::class))
class MainModule {

    @ActivityScope
    @Provides
    fun providePresenter(view: MainMvp.View): MainMvp.Presenter {
        return MainPresenter(view)
    }

}
</code>```

And finally, ActivityScope:

```<code>@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope
</code>```

Does anyone know what might be wrong? I have used the same exact Architectural pattern in java several times before, and I have never ran into this error before.

Also, when I comment out everything inside of InjectionModule, everything works

答:
I think you have to add AndroidSupportInjectionModule::class in your AppComponent:

```<code>@Singleton
@Component(modules = arrayOf(AppModule::class,
AndroidSupportInjectionModule::class, InjectionModule::class))
interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(app: KotlinApplication): Builder

        fun build(): AppComponent
    }

    fun inject(app: KotlinApplication)

}
</code>```

If it still does not help try referring to this github repo : Kotlin MVP Chat. Checkout the di folder which contains all dependency injection code in kotlin.

ContentLicense: CC BY-SA 3.0

Title: Dagger with Mvp on Kotlin - Android

Body:
I am an Android developer that is just getting into Kotlin, and I have been trying to setup an Mvp Dagger application in Kotlin, but I cannot figure out what is going on.  I continue to get this error:

Error:dagger.internal.codegen.ComponentProcessor was unable to process this interface
because not all of its dependencies could be resolved.
Check for compilation errors or a circular dependency with generated code.

Here is my code:

KotlinApplication:

class KotlinApplication: MultiDexApplication(), HasActivityInjector {

    @Inject lateinit var injector: DispatchingAndroidInjector<Activity>

    override fun onCreate() {
        super.onCreate()
        inject()
    }

    override fun activityInjector(): AndroidInjector<Activity> {
        return injector
    }

    fun inject() {
        DaggerAppComponent.builder().application(this).build().inject(this);
    }

}

AppComponent:

@Singleton
@Component(modules = arrayOf(AppModule::class, InjectionModule::class))
interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(app: KotlinApplication): Builder

        fun build(): AppComponent
    }

    fun inject(app: KotlinApplication)

}

AppModule:

@Module
class AppModule {
    @Singleton
    @Provides
    fun provideAppContext(app: KotlinApplication): Context {
        return app
    }

    @Singleton
    @Provides
    fun provideApplication(app: KotlinApplication): Application {
        return app
    }
}

InjectionModule:

@Module
abstract class InjectionModule {

    @ActivityScope
    @ContributesAndroidInjector(modules = arrayOf(MainModule::class))
    internal abstract fun bindMainActivity(): MainActivity

}

MainActivity:

class MainActivity : AppCompatActivity(), MainMvp.View {

    @Inject lateinit var presenter: MainMvp.Presenter

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

MainMvp:

interface MainMvp {
    interface View {

    }

    interface Presenter {

    }
}

MainPresenter:

class MainPresenter(view: MainMvp.View): MainMvp.Presenter {

    var view: MainMvp.View

    init {
        this.view = view
    }

}

MainBindModule:

@Module
interface MainBindModule {
    @ActivityScope
    @Binds
    fun bindView(activity: MainActivity): MainMvp.View
}

MainModule:

@Module(includes = arrayOf(MainBindModule::class))
class MainModule {

    @ActivityScope
    @Provides
    fun providePresenter(view: MainMvp.View): MainMvp.Presenter {
        return MainPresenter(view)
    }

}

And finally, ActivityScope:

@Qualifier
@Retention(AnnotationRetention.RUNTIME)
annotation class ActivityScope

Does anyone know what might be wrong? I have used the same exact Architectural pattern in java several times before, and I have never ran into this error before.

Also, when I comment out everything inside of InjectionModule, everything works

Body:
I think you have to add AndroidSupportInjectionModule::class in your AppComponent:

@Singleton
@Component(modules = arrayOf(AppModule::class,
AndroidSupportInjectionModule::class, InjectionModule::class))
interface AppComponent {

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(app: KotlinApplication): Builder

        fun build(): AppComponent
    }

    fun inject(app: KotlinApplication)

}

If it still does not help try referring to this github repo : Kotlin MVP Chat. Checkout the di folder which contains all dependency injection code in kotlin.


问:
Addition for BigDecimal
I want to do some simple sums with some currency values expressed in BigDecimal type.

```<code>BigDecimal test = new BigDecimal(0);
System.out.println(test);
test.add(new BigDecimal(30));
System.out.println(test);
test.add(new BigDecimal(45));
System.out.println(test);
</code>```

Obviously I do not understand well the BigDecimal arithmetics, see output behind.

```<code>Test
0
0
0
</code>```

Can anyone help me out?

答:
You can also do it like this:

```<code>BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);
</code>```

Prints:

A+B+C= 60000000000

Title: Addition for BigDecimal

Body:
I want to do some simple sums with some currency values expressed in BigDecimal type.

BigDecimal test = new BigDecimal(0);
System.out.println(test);
test.add(new BigDecimal(30));
System.out.println(test);
test.add(new BigDecimal(45));
System.out.println(test);

Obviously I do not understand well the BigDecimal arithmetics, see output behind.

Test
0
0
0

Can anyone help me out?

Body:
You can also do it like this:

BigDecimal A = new BigDecimal("10000000000");
BigDecimal B = new BigDecimal("20000000000");
BigDecimal C = new BigDecimal("30000000000");
BigDecimal resultSum = (A).add(B).add(C);
System.out.println("A+B+C= " + resultSum);

Prints:

A+B+C= 60000000000


问:
Child Components are not being re-rendered
I'm new to React. As a learning exercise I'm building an chess application

I want to change the DOM of child based on state in parent. Currently there is no change in child components on change of state in parent.

Parent Component

```<code>class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                board_position = { 'One' : ''}
            }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })

        //this.forceUpdate(); // Just trying different methods to make it work
    }

    render(){
        return(
            <div onClick={(e) => this.handleClick(e) }>
                <Piece {...this.state.game.board_position} />
            </div>
        )
    }
}
</code>```

Child Component

```<code>Class Piece extends Component{

    constructor(){
        super(props);
        this.state = {
            clr : ''
        }
    }

    componentWillMount(){
        let c;

        // some computations that change value of c based on props
        if( typeof ( this.props.game.one) == number ){
            c = 'Red'
        } else {
            c = 'Blue'
        }

        this.setState({
            clr : c
        })

    }

    render(){
        return(
            <span>{this.state.clr}</span>
        )
    }
}
</code>```

On call of handle click method, there is a change in state of the game. However, subsequent changes in Child are not seen.

Can anyone please help me out? Where am I going wrong?

I'm not sure how to implement ref as suggested over here. However, I don't think that is a good solution. Probably I'm having some conceptual misunderstanding.

PS: Please ignore any syntax error. This code is a strip down of real code.
If you want to take a look at full code - go over here

答:
it's a pretty basic react process:

```<code>class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                 board_position = { 'One' : ''}
             }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })
    }

    render(){
        return(
        <div onClick={this.handleClick}>
            <Piece board_position={this.state.game.board_position} />
        </div>
        )
    }
}
</code>```

Child: //can be a function instead of a class

```<code>const Piece = ({board_position}) =>{
  const {board_position} = this.props;
  let clt = board_position;
  //do some stuff

  return(
    <span>{board_position}</span>
  );
};
</code>```

if you want to do more calculations you can use componentWillReceiveProps(newProps)

Body:
I'm new to React. As a learning exercise I'm building an chess application

I want to change the DOM of child based on state in parent. Currently there is no change in child components on change of state in parent.

Parent Component

class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                board_position = { 'One' : ''}
            }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })

        //this.forceUpdate(); // Just trying different methods to make it work
    }

    render(){
        return(

 this.handleClick(e) }>
                <Piece {...this.state.game.board_position} />

        )
    }
}

Child Component

Class Piece extends Component{

    constructor(){
        super(props);
        this.state = {
            clr : ''
        }
    }

    componentWillMount(){
        let c;

        // some computations that change value of c based on props
        if( typeof ( this.props.game.one) == number ){
            c = 'Red'
        } else {
            c = 'Blue'
        }

        this.setState({
            clr : c
        })

    }

    render(){
        return(
            {this.state.clr}
        )
    }
}

On call of handle click method, there is a change in state of the game. However, subsequent changes in Child are not seen.

Can anyone please help me out? Where am I going wrong?

I'm not sure how to implement ref as suggested over here. However, I don't think that is a good solution. Probably I'm having some conceptual misunderstanding.

PS: Please ignore any syntax error. This code is a strip down of real code.
If you want to take a look at full code - go over here

Body:
it's a pretty basic react process:

class Game extends Component{
    constructor(){
        super();
        this.state = {
            game :{
                 board_position = { 'One' : ''}
             }
        }

        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e){
        let p = this.state.game.board_position;

        // some computations on p
        p = { board_position : { 'One' : Math.random() } }

        this.setState({
            game : p
        })
    }

    render(){
        return(
        <div onClick={this.handleClick}>
            <Piece board_position={this.state.game.board_position} />
        </div>
        )
    }
}

Child: //can be a function instead of a class

const Piece = ({board_position}) =>{
  const {board_position} = this.props;
  let clt = board_position;
  //do some stuff

  return(
    <span>{board_position}</span>
  );
};

if you want to do more calculations you can use componentWillReceiveProps(newProps)


问:
Could not fetch URL
This is not a duplicate. I've read every response there is online.

Any time I try to connect to a website through the terminal I get an error. Many solutions say to try installing certifi first and then attempting, but I can't do that either because then I'd have to connect to https://pypi.python.org/simple/certifi/. I've also tried --trusted-hostbut I still receive an error.

Here is the error if I try to run the Install Certificates.command in the Python 3.6 folder:

```<code>/Applications/Python\ 3.6/Install\ Certificates.command ; exit;
 -- pip install --upgrade certifi
Collecting certifi
  Could not fetch URL https://pypi.python.org/simple/certifi/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping
  Could not find a version that satisfies the requirement certifi (from versions: )
No matching distribution found for certifi
Traceback (most recent call last):
  File "<stdin>", line 44, in <module>
  File "<stdin>", line 25, in main
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 291, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6', '-E', '-s', '-m', 'pip', 'install', '--upgrade', 'certifi']' returned non-zero exit status 1.
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]
</code>```

I also get the SSL error if I try to use url lib to connect in a python doc and then attempt to run the python doc in the terminal. Let me also mention this is a brand new issue. I ran the same script yesterday and it worked fine.

Versions:

```<code>Python 3.6
numpy==1.13.3
ortools==6.6.4656
pandas==0.21.0
protobuf==3.5.0.post1
python-dateutil==2.6.1
pytz==2017.3
six==1.11.0
OpenSSH_7.4p1, LibreSSL 2.5.0
</code>```

答:
Add Below lines in your script and execute the script. Might be it will solve your issue.</p>

```<code>import ssl
ssl._create_default_https_context = ssl._create_unverified_context
</code>```

Title: Could not fetch URL

Body:
This is not a duplicate. I've read every response there is online.

Any time I try to connect to a website through the terminal I get an error. Many solutions say to try installing certifi first and then attempting, but I can't do that either because then I'd have to connect to https://pypi.python.org/simple/certifi/. I've also tried --trusted-hostbut I still receive an error.

Here is the error if I try to run the Install Certificates.command in the Python 3.6 folder:

/Applications/Python\ 3.6/Install\ Certificates.command ; exit;
 -- pip install --upgrade certifi
Collecting certifi
  Could not fetch URL https://pypi.python.org/simple/certifi/: There was a problem confirming the ssl certificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) - skipping
  Could not find a version that satisfies the requirement certifi (from versions: )
No matching distribution found for certifi
Traceback (most recent call last):
  File "<stdin>", line 44, in <module>
  File "<stdin>", line 25, in main
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/subprocess.py", line 291, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command '['/Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6', '-E', '-s', '-m', 'pip', 'install', '--upgrade', 'certifi']' returned non-zero exit status 1.
logout
Saving session...
...copying shared history...
...saving history...truncating history files...
...completed.

[Process completed]

I also get the SSL error if I try to use url lib to connect in a python doc and then attempt to run the python doc in the terminal. Let me also mention this is a brand new issue. I ran the same script yesterday and it worked fine.

Versions:

Python 3.6
numpy==1.13.3
ortools==6.6.4656
pandas==0.21.0
protobuf==3.5.0.post1
python-dateutil==2.6.1
pytz==2017.3
six==1.11.0
OpenSSH_7.4p1, LibreSSL 2.5.0

Body:
Add Below lines in your script and execute the script. Might be it will solve your issue.

import ssl
ssl._create_default_https_context = ssl._create_unverified_context


问:
FloatingActionButton hide on list scroll
Im using the FloatingActionButton from the android.support.design.widget package:

```<code><android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="20dp"
    android:layout_marginEnd="16dp"
    android:clickable="true"
    android:backgroundTint="@color/primaryColor"
    android:src="@drawable/ic_search_white_24dp"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:backgroundTint="@color/primaryColorDark"
    app:rippleColor="@color/accentColor" />
</code>```

Is it possible to configure that button to hide with an animation when the listview is scrolling down and to show it again when listview is scrolling up to the top?

答:
Here I am adding extra padding for last view item to avoid overlapping list item with floating action button

I used this in a RecyclerView.Adapter's onBindViewHolder method to set the bottom margin of the last item in the list to 72dp so that it will scroll up above the floating action button.

This does not require a dummy entry in the list.

```<code>@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // other binding code goes here.

    if (position + 1 == getItemCount()) {
        // set bottom margin to 72dp.
        setBottomMargin(holder.itemView, (int) (72 * Resources.getSystem().getDisplayMetrics().density));
    } else {
        // reset bottom margin back to zero. (your value may be different)
        setBottomMargin(holder.itemView, 0);
    }
}

public static void setBottomMargin(View view, int bottomMargin) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        params.setMargins(params.leftMargin, params.topMargin, params.rightMargin, bottomMargin);
        view.requestLayout();
    }
}
</code>```

Body:
Im using the FloatingActionButton from the android.support.design.widget package:

<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="20dp"
    android:layout_marginEnd="16dp"
    android:clickable="true"
    android:backgroundTint="@color/primaryColor"
    android:src="@drawable/ic_search_white_24dp"
    app:borderWidth="0dp"
    app:elevation="6dp"
    app:backgroundTint="@color/primaryColorDark"
    app:rippleColor="@color/accentColor" />

Is it possible to configure that button to hide with an animation when the listview is scrolling down and to show it again when listview is scrolling up to the top?

Body:
Here I am adding extra padding for last view item to avoid overlapping list item with floating action button

I used this in a RecyclerView.Adapter's onBindViewHolder method to set the bottom margin of the last item in the list to 72dp so that it will scroll up above the floating action button.

This does not require a dummy entry in the list.

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // other binding code goes here.

    if (position + 1 == getItemCount()) {
        // set bottom margin to 72dp.
        setBottomMargin(holder.itemView, (int) (72 * Resources.getSystem().getDisplayMetrics().density));
    } else {
        // reset bottom margin back to zero. (your value may be different)
        setBottomMargin(holder.itemView, 0);
    }
}

public static void setBottomMargin(View view, int bottomMargin) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        params.setMargins(params.leftMargin, params.topMargin, params.rightMargin, bottomMargin);
        view.requestLayout();
    }
}


问:
Interacting with actors in scala swing applications
I'm writing a small application in scala. The application processes simple log files. Because the processing takes some time, I've decided to let my application core extend Actor.

```<code>class Application extends Actor {
  def react() {
    loop {
      react {
        case Process(file) => // do something interesting with file...
      }
    }
  }
}
</code>```

The processing of a log file is triggered by clicking a button in the gui. The gui uses scala swing.

```<code>object Gui extends SimpleSwingApplication {
  val application = new Application().start()

  def top = new MainFrame {
    val startButton = new Button

    reactions += {
      case ButtonClicked(`startButton`) => application ! Process(file)
    }
  }
}
</code>```

Now, the application core needs to notify the gui about the current progress.

```<code>  sender ! Progress(value) // whenever progress is made
</code>```

I've solved this by creating a separate actor inside the gui. The actor is executed inside the edt thread. It listens to messages from the application core and updates the gui.

```<code>  object Gui extends SimpleSwingApplication {
    val actor = new Actor {
      override val scheduler = new SchedulerAdapter {
        def execute(fun: => Unit) { Swing.onEDT(fun) }
      }
      start()

      def act() {
        loop {
          react {
            case ForwardToApplication(message) => application ! message
            case Progress(value) => progressBar.value = value
          }
        }
      }
    }
  }
</code>```

Since the application core needs to know about the sender of the message, I also use this actor to forward messages from the gui to the application core, making my actor the new sender.

```<code>  reactions += {
    case ButtonClicked(`startButton`) => actor ! ForwardToApplication(Process(file))
  }
</code>```

This code works just fine. My question: Is there a simpler way to do this? It whould be nice to simple use the reactions mechanism for my application messages:

```<code>  reactions += {
    case Progress(value) => progressBar.value = value
  }
</code>```

Any ideas how to achieve this?

答:
I have extended on gerferras idea of making my application a swing.Publisher. The following class acts as intermediator between a swing.Reactor and an Actor.

```<code>import actors.Actor
import swing.Publisher
import swing.event.Event
import swing.Swing.onEDT

case class Send(event: Any)(implicit intermediator: Intermediator) {
  intermediator ! this
}
case class Receive(event: Any) extends Event

case class Intermediator(application: Actor) extends Actor with Publisher {
  start()

  def act() {
    loop {
      react {
        case Send(evt) => application ! evt
        case evt => onEDT(publish(Receive(evt)))
      }
    }
  }
}
</code>```

Now my reactions can include both swing events and application events.

```<code>implicit val intermediator = Intermediator(application)
listenTo(intermediator, button)

reactions += {
  case ButtonClicked(`button`) => Send(Process(file))
  case Receive(Progress(value)) => progressBar.value = value
}
</code>```

Note how the case class Send provides some syntactic sugar to easily create events and pass them to the intermediator.

ContentLicense: CC BY-SA 2.5

Body:
I'm writing a small application in scala. The application processes simple log files. Because the processing takes some time, I've decided to let my application core extend Actor.

class Application extends Actor {
  def react() {
    loop {
      react {
        case Process(file) => // do something interesting with file...
      }
    }
  }
}

The processing of a log file is triggered by clicking a button in the gui. The gui uses scala swing.

object Gui extends SimpleSwingApplication {
  val application = new Application().start()

  def top = new MainFrame {
    val startButton = new Button

    reactions += {
      case ButtonClicked(`startButton`) => application ! Process(file)
    }
  }
}

Now, the application core needs to notify the gui about the current progress.

  sender ! Progress(value) // whenever progress is made

I've solved this by creating a separate actor inside the gui. The actor is executed inside the edt thread. It listens to messages from the application core and updates the gui.

  object Gui extends SimpleSwingApplication {
    val actor = new Actor {
      override val scheduler = new SchedulerAdapter {
        def execute(fun: => Unit) { Swing.onEDT(fun) }
      }
      start()

      def act() {
        loop {
          react {
            case ForwardToApplication(message) => application ! message
            case Progress(value) => progressBar.value = value
          }
        }
      }
    }
  }

Since the application core needs to know about the sender of the message, I also use this actor to forward messages from the gui to the application core, making my actor the new sender.

  reactions += {
    case ButtonClicked(`startButton`) => actor ! ForwardToApplication(Process(file))
  }

This code works just fine. My question: Is there a simpler way to do this? It whould be nice to simple use the reactions mechanism for my application messages:

  reactions += {
    case Progress(value) => progressBar.value = value
  }

Any ideas how to achieve this?

Body:
I have extended on gerferras idea of making my application a swing.Publisher. The following class acts as intermediator between a swing.Reactor and an Actor.

import actors.Actor
import swing.Publisher
import swing.event.Event
import swing.Swing.onEDT

case class Send(event: Any)(implicit intermediator: Intermediator) {
  intermediator ! this
}
case class Receive(event: Any) extends Event

case class Intermediator(application: Actor) extends Actor with Publisher {
  start()

  def act() {
    loop {
      react {
        case Send(evt) => application ! evt
        case evt => onEDT(publish(Receive(evt)))
      }
    }
  }
}

Now my reactions can include both swing events and application events.

implicit val intermediator = Intermediator(application)
listenTo(intermediator, button)

reactions += {
  case ButtonClicked(`button`) => Send(Process(file))
  case Receive(Progress(value)) => progressBar.value = value
}

Note how the case class Send provides some syntactic sugar to easily create events and pass them to the intermediator.


问:
Codename One - scanning barcodes checking for new line/ENTER character
in Android I can easily detect the ENTER character using the setOnEditorActionListener method so that when a barcode is scanned into a textfield I know when the whole barcode has been read.

[Here is the Android code as requested:]

```<code>scanEditText.setOnEditorActionListener(new TextView.OnEditorActionListener()
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            if ( (actionId == EditorInfo.IME_ACTION_DONE) || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN )))
            {
                System.out.println("   *** ENTER!");
                return true;
            }
            else
                return false;
        }
    });
</code>```

I have been trying to replicate this in Codename One but with no luck. I have tried

setDoneListener

addDataChangedListener

ActionEvent on the text field and text area

overriding the keyPressed and keyReleased methods

but with no joy. If I set a textField with setSingleLineTextArea(false) I can see the barcode characters appear in the box followed by what I am assuming is a
 new line character as the next scan appears on a new line. None of the methods listed seem to catch this event. If I change the focus to another box the ActionEvent is triggered but I don't want to have to move the focus each time.

[Here is the Codenameone code]

```<code>gui_searchTextField.setSingleLineTextArea(false);
gui_searchTextField.setDoneListener(new ActionListener()
{
     public void actionPerformed(ActionEvent evt)
     {
        Dialog.show("KB", "doneListener " +
        gui_searchTextField.getText().trim(), "OK", null);
     }
});
gui_searchTextField.addDataChangedListener((evt1, evt2) ->
{
  System.out.println("DataChanged " + gui_searchTextField.getText());
});
</code>```

So, how do I catch the end of the barcode like I can easily in the Android SDK?

答:
Text input is very much a special case for us in all OS's so the keys go directly into the native OS text editing and don't "travel" through Codename One API's. However, DataChangeListener should be invoked for every key input so I'm not sure how this is happening exactly.

I did notice you are using System.out instead of Log.p so you might miss the output from the device related to the changes. Also I would recommend overriding the key pressed/released events and not starting the text editing. Then adding the key value to the text field instead of letting the native input handle it e.g.:

```<code>class MyForm extends Form {
    public void keyReleased(int key) {
        if(isCrLf(key)) {
            // do this...
        } else {
            myTextField.setText(myTextField.getText() + ((char)key));
        }
    }
}
</code>```

Body:
in Android I can easily detect the ENTER character using the setOnEditorActionListener method so that when a barcode is scanned into a textfield I know when the whole barcode has been read.

[Here is the Android code as requested:]

scanEditText.setOnEditorActionListener(new TextView.OnEditorActionListener()
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
        {
            if ( (actionId == EditorInfo.IME_ACTION_DONE) || ((event.getKeyCode() == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN )))
            {
                System.out.println("   *** ENTER!");
                return true;
            }
            else
                return false;
        }
    });

I have been trying to replicate this in Codename One but with no luck. I have tried

setDoneListener

addDataChangedListener

ActionEvent on the text field and text area

overriding the keyPressed and keyReleased methods

but with no joy. If I set a textField with setSingleLineTextArea(false) I can see the barcode characters appear in the box followed by what I am assuming is a
 new line character as the next scan appears on a new line. None of the methods listed seem to catch this event. If I change the focus to another box the ActionEvent is triggered but I don't want to have to move the focus each time.

[Here is the Codenameone code]

gui_searchTextField.setSingleLineTextArea(false);
gui_searchTextField.setDoneListener(new ActionListener()
{
     public void actionPerformed(ActionEvent evt)
     {
        Dialog.show("KB", "doneListener " +
        gui_searchTextField.getText().trim(), "OK", null);
     }
});
gui_searchTextField.addDataChangedListener((evt1, evt2) ->
{
  System.out.println("DataChanged " + gui_searchTextField.getText());
});

So, how do I catch the end of the barcode like I can easily in the Android SDK?

Body:
Text input is very much a special case for us in all OS's so the keys go directly into the native OS text editing and don't "travel" through Codename One API's. However, DataChangeListener should be invoked for every key input so I'm not sure how this is happening exactly.

I did notice you are using System.out instead of Log.p so you might miss the output from the device related to the changes. Also I would recommend overriding the key pressed/released events and not starting the text editing. Then adding the key value to the text field instead of letting the native input handle it e.g.:

class MyForm extends Form {
    public void keyReleased(int key) {
        if(isCrLf(key)) {
            // do this...
        } else {
            myTextField.setText(myTextField.getText() + ((char)key));
        }
    }
}


问:
what should I add on this script to make the transition fast?
```<code>var i =0; 0 <= i; i++)
function f() {
    $('#clickbtn').click()
    i++;
    if (i < 2100) {
        setTimeout( f, 2500);
    }
}
f();
</code>```

it works fine but I can notice a quick pause before the next click. what should I add to make the click automatically pressed upon loading of the button.

thanks in advance guys

答:
No clear idea what you're trying to do. Click a button a whole bunch? 2099 times maybe?

This might be what you're trying to do, if you're even trying to click a button a bunch.

```<code>var timer = setInterval(function(){
    for (i=0;i<2100;i++){
       $('#clickbtn').click()
    }
    clearTimeout(timer)
    location.reload();
},3000);
</code>```

This will SMASH button clicks, reload the page, and do it all again.

Body:
var i =0; 0 <= i; i++)
function f() {
    $('#clickbtn').click()
    i++;
    if (i < 2100) {
        setTimeout( f, 2500);
    }
}
f();

it works fine but I can notice a quick pause before the next click. what should I add to make the click automatically pressed upon loading of the button.

thanks in advance guys

Body:
No clear idea what you're trying to do. Click a button a whole bunch? 2099 times maybe?

This might be what you're trying to do, if you're even trying to click a button a bunch.

var timer = setInterval(function(){
    for (i=0;i<2100;i++){
       $('#clickbtn').click()
    }
    clearTimeout(timer)
    location.reload();
},3000);

This will SMASH button clicks, reload the page, and do it all again.


问:
setMovementMethod doesn't work in android textview
I have a textview whose text is coming from database. This text can be normal text or it can be a link or both. For this, I am parsing text in html using Html.fromHtml(myText). So that link can be detected and display as clickable. This is working fine. It displays clickable string for links and non-clickable for normal text. But when I click that text, it doesn't work and nothing happens. This is what I am getting from server as text :

```<code>Dear user:

Your review titled <a href="http://example.com/review/someText-1069459" target="blank">Normal verified negative 1 desktop</a> on the product <a href="http://example.com/product-reviews/text-925766045"  target="blank">Clickable Text</a> has been resolved.

To check corporate response  <a target="blank" href="http://example.com/interact.php?add=http://example.com/blog/ejhhspsqmn/Please-talk-about-your-companys-products-and-services-onlyPlease-present-your-post-in-an-objectiv&session_id=Se9qExA6JSY%3d">Click here</a>

Have a great day!

Regards,
Head - Member Support
</code>```

To make clickable text, I use setMovementMethod like below :

```<code>textView.setText(Html.fromHtml(myText));
textView.setMovementMethod(LinkMovementMethod.getInstance());
</code>```

But its not working. Is there anything that I am missing to add in code ? Also I am using  android:autoLink="web" in xml.

答:
You can either user LinkMoveMethod interface or Linkify

Example :----

```<code>TextViewObject.setText(Html.fromHtml("YOur Text "));
TextViewObj.setMovementMethod(LinkMovementMethod.getInstance());
</code>```

OR

```<code>Linkify.addLinks(new SpannableString(Html.fromHtml("Your Text"));
</code>```

Body:
I have a textview whose text is coming from database. This text can be normal text or it can be a link or both. For this, I am parsing text in html using Html.fromHtml(myText). So that link can be detected and display as clickable. This is working fine. It displays clickable string for links and non-clickable for normal text. But when I click that text, it doesn't work and nothing happens. This is what I am getting from server as text :

Dear user:

Your review titled Normal verified negative 1 desktop on the product Clickable Text has been resolved.

To check corporate response  Click here

Have a great day!

Regards,
Head - Member Support

To make clickable text, I use setMovementMethod like below :

textView.setText(Html.fromHtml(myText));
textView.setMovementMethod(LinkMovementMethod.getInstance());

But its not working. Is there anything that I am missing to add in code ? Also I am using  android:autoLink="web" in xml.

Body:
You can either user LinkMoveMethod interface or Linkify

Example :----

TextViewObject.setText(Html.fromHtml("YOur Text "));
TextViewObj.setMovementMethod(LinkMovementMethod.getInstance());

OR

Linkify.addLinks(new SpannableString(Html.fromHtml("Your Text"));


问:
Can't append the array value returned from asp.net webservice in javascript
I am calling a webservice from ajax call. The Webservice is returning all the values fine. Since one of the properties is of datetime i am using this Js function to parse the date.

function ToJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
  // return (dt.getFullYear() + "/" + (dt.getMonth() + 1) +"/" + dt.getDate());
}
```

<p><strong>Here i am calling the webservice</strong> </p>

<pre class="lang-js prettyprint-override"><code>$(document).ready(function() {

  $('#ShowInGridButton').on('click',
    function() {
      var accountNumberId = $('#DepositAccountNumberIdHiddenField').val();
      var fromDate = $("input[name*='FromDateControl']").val();
      var toDate = $("input[name*='ToDateControl']").val();
      var url = "/WebMethods/Deposit.asmx/GetDepositAccountStatement";
      var d = {
        accountNumberId: accountNumberId,
        fromDate: fromDate,
        toDate: toDate
      };
      var jqXhr = ajaxPost(url, d);
      jqXhr.done(function(data) {
        console.log(data);
        if (data) {
          var div = $('#CfDataTable').empty();
          div.append(
            $("<tr class='success'><th>Tran Date</th><th>Value Date</th><th>Statement Reference</th><th>Check No.</th><th>Collector</th><th>Debit</th><th>Credit</th><th>Balance</th></tr>"));

          $(data.d).each(function(index, item) {

            div.append(
              $("<tr>")
              .append($("<td>").html(ToJavaScriptDate(item.TranDate)))
              .append($("<td>").html(ToJavaScriptDate(item.ValueDate)))
              // .append($("<td>").html(item.TranDate))
              // .append($("<td>").html(item.ValueDate))
              .append($("<td>").html(item.StatementReference))
              .append($("<td>").html(item.CheckNumber))
              .append($("<td>").html(item.Collector))
              .append($("<td>").html(item.Debit))
              .append($("<td>").html(item.Credit))
              .append($("<td>").html(item.Balance)));
          });
        }
      }).fail(function() {
        console.log('Data Retrieve failed.');
      });
    });
});
</code>```

XML output

<ArrayOfDepositAccountStatementView xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://Everest.Net.Web.WebMethods/">
  <DepositAccountStatementView>
    <TranId>13018256</TranId>
    <TranDate>2016-01-14T00:00:00</TranDate>
    <ValueDate>2016-01-14T00:00:00</ValueDate>
    <Collector>Office</Collector>
    <Debit xsi:nil="true" />
    <Credit>11000</Credit>
    <Balance>11000</Balance>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>23601</TranId>
    <TranDate>2016-02-04T00:00:00</TranDate>
    <ValueDate>2016-02-04T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>12000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>69273</TranId>
    <TranDate>2016-03-01T00:00:00</TranDate>
    <ValueDate>2016-03-01T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>13000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>118061</TranId>
    <TranDate>2016-04-01T00:00:00</TranDate>
    <ValueDate>2016-04-01T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>14000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>180233</TranId>
    <TranDate>2016-05-10T00:00:00</TranDate>
    <ValueDate>2016-05-10T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>15000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>230251</TranId>
    <TranDate>2016-06-08T00:00:00</TranDate>
    <ValueDate>2016-06-08T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>16000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId xsi:nil="true" />
    <TranDate xsi:nil="true" />
    <ValueDate xsi:nil="true" />
    <StatementReference>Total</StatementReference>
    <Debit>0</Debit>
    <Credit>16000</Credit>
    <Balance xsi:nil="true" />
  </DepositAccountStatementView>
</ArrayOfDepositAccountStatementView>
```

Everything is working fine. But when one of the row has null values for TranDate
and ValueDate null, I can't see any data in my appended div.

If I don't use the above JS dateparser and simply append like item.TranDate I get all the rows with tranDate as TranDate: "/Date(1460398500000)/"

What is wrong here?

I tried JSON.stringyfy(item.TranDate) but reached nowhere.

In my console I can see the data as

{__type: "Everest.Net.Common.Deposit.Views.DepositAccountStatementView", TranId: null, TranDate: null, ValueDate: null, StatementReference: "Total"

but this does not get appended in the div.

答:
Solved this..problem was with my ToJavaScriptDate function.I had to check a null value before calling the function.

function ToJavaScriptDate(value) {
     if(value !== null
        && value !== undefined
)
     {
                var pattern = /Date\(([^)]+)\)/;
                var results = pattern.exec(value);
                var dt = new Date(parseFloat(results[1]));
                return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
                // return (dt.getFullYear() + "/" + (dt.getMonth() + 1) +"/" + dt.getDate());
     }
     else
     {
          return '';
     }
}```

Body:
I am calling a webservice from ajax call. The Webservice is returning all the values fine. Since one of the properties is of datetime i am using this Js function to parse the date.

function ToJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
  // return (dt.getFullYear() + "/" + (dt.getMonth() + 1) +"/" + dt.getDate());
}

Here i am calling the webservice

$(document).ready(function() {

  $('#ShowInGridButton').on('click',
    function() {
      var accountNumberId = $('#DepositAccountNumberIdHiddenField').val();
      var fromDate = $("input[name*='FromDateControl']").val();
      var toDate = $("input[name*='ToDateControl']").val();
      var url = "/WebMethods/Deposit.asmx/GetDepositAccountStatement";
      var d = {
        accountNumberId: accountNumberId,
        fromDate: fromDate,
        toDate: toDate
      };
      var jqXhr = ajaxPost(url, d);
      jqXhr.done(function(data) {
        console.log(data);
        if (data) {
          var div = $('#CfDataTable').empty();
          div.append(
            $("
Tran Date	Value Date	Statement Reference	Check No.	Collector	Debit	Credit	Balance
"));

          $(data.d).each(function(index, item) {

            div.append(
              $("
")
              .append($("").html(ToJavaScriptDate(item.TranDate)))
              .append($("").html(ToJavaScriptDate(item.ValueDate)))
              // .append($("").html(item.TranDate))
              // .append($("").html(item.ValueDate))
              .append($("").html(item.StatementReference))
              .append($("").html(item.CheckNumber))
              .append($("").html(item.Collector))
              .append($("").html(item.Debit))
              .append($("").html(item.Credit))
              .append($("").html(item.Balance)));
          });
        }
      }).fail(function() {
        console.log('Data Retrieve failed.');
      });
    });
});

XML output

<ArrayOfDepositAccountStatementView xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://Everest.Net.Web.WebMethods/">
  <DepositAccountStatementView>
    <TranId>13018256</TranId>
    <TranDate>2016-01-14T00:00:00</TranDate>
    <ValueDate>2016-01-14T00:00:00</ValueDate>
    <Collector>Office</Collector>
    <Debit xsi:nil="true" />
    <Credit>11000</Credit>
    <Balance>11000</Balance>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>23601</TranId>
    <TranDate>2016-02-04T00:00:00</TranDate>
    <ValueDate>2016-02-04T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>12000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>69273</TranId>
    <TranDate>2016-03-01T00:00:00</TranDate>
    <ValueDate>2016-03-01T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>13000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>118061</TranId>
    <TranDate>2016-04-01T00:00:00</TranDate>
    <ValueDate>2016-04-01T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>14000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>180233</TranId>
    <TranDate>2016-05-10T00:00:00</TranDate>
    <ValueDate>2016-05-10T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>15000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId>230251</TranId>
    <TranDate>2016-06-08T00:00:00</TranDate>
    <ValueDate>2016-06-08T00:00:00</ValueDate>
    <StatementReference>Collected by Krishna Pokhrel</StatementReference>
    <Collector>Krishna Pokhrel</Collector>
    <Debit>0</Debit>
    <Credit>1000</Credit>
    <Balance>16000</Balance>
    <CheckNumber/>
  </DepositAccountStatementView>
  <DepositAccountStatementView>
    <TranId xsi:nil="true" />
    <TranDate xsi:nil="true" />
    <ValueDate xsi:nil="true" />
    <StatementReference>Total</StatementReference>
    <Debit>0</Debit>
    <Credit>16000</Credit>
    <Balance xsi:nil="true" />
  </DepositAccountStatementView>
</ArrayOfDepositAccountStatementView>

Everything is working fine. But when one of the row has null values for TranDate
and ValueDate null, I can't see any data in my appended div.

If I don't use the above JS dateparser and simply append like item.TranDate I get all the rows with tranDate as TranDate: "/Date(1460398500000)/"

What is wrong here?

I tried JSON.stringyfy(item.TranDate) but reached nowhere.

In my console I can see the data as

{__type: "Everest.Net.Common.Deposit.Views.DepositAccountStatementView", TranId: null, TranDate: null, ValueDate: null, StatementReference: "Total"

but this does not get appended in the div.


问:
JavaFX Could not get function pointer for JLI_Launch
I'm trying to build a native launcher for a JavaFX app on OSX using the standard JavaFX packaging tools. Nothing happens when I launch the app by double clicking / selecting it from the spotlight / etc...

When I go into the application bundle from the terminal and launch from Contents/MacOS/APP_NAME I see an error like:

```<code>2014-08-21 13:29:22.488 APP_NAME[4479:507] Could not get function pointer for JLI_Launch.: (
    0   CoreFoundation        0x00007fff8c25b25c __exceptionPreprocess + 172
    1   libobjc.A.dylib       0x00007fff84ebde75 objc_exception_throw + 43
    2   CoreFoundation        0x00007fff8c25b10c +[NSException raise:format:] + 204
    3   APP_NAME              0x0000000107f5bde1 launch + 593
    4   APP_NAME              0x0000000107f5b366 main + 70
    5   APP_NAME              0x0000000107f5b314 start + 52
    6   ???                   0x0000000000000001 0x0 + 1
)
</code>```

Environment Info:

```<code>$> java -version
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)

$> sw_vers
ProductName:    Mac OS X
ProductVersion: 10.9.4
BuildVersion:   13E28
</code>```

Any ideas on what could be causing the issue?

答:
I use MacOS Sierra 10.12.6 and i get "Could not get function pointer for JLI_Launch" error

I use CS6 Illustrator and had to install JAVA 6 (https://support.apple.com/kb/DL1572?locale=es_MX) because Illustrator crashes with new JAVA version.

But having older version of JAVA caused jdownloader crash so i downloaded again jdownloader from this link http://jdownloader.org/download/index and choose "Version 10.6 or lower"   from this link: (spanish)

Descargar Installer MacOS Version 10.6 or lower  (http://mega.nz/#!vd1yxZCS!n-W5tr_1LSlQiIaEaQFodPKzi938EwDLjsaiFsoproQ)

Now i have both java versions, older for ILLUSTRATOR and newest to jdownloader and other software

It helped me to solve this problem, hope it works to others

Body:
I'm trying to build a native launcher for a JavaFX app on OSX using the standard JavaFX packaging tools. Nothing happens when I launch the app by double clicking / selecting it from the spotlight / etc...

When I go into the application bundle from the terminal and launch from Contents/MacOS/APP_NAME I see an error like:

2014-08-21 13:29:22.488 APP_NAME[4479:507] Could not get function pointer for JLI_Launch.: (
    0   CoreFoundation        0x00007fff8c25b25c __exceptionPreprocess + 172
    1   libobjc.A.dylib       0x00007fff84ebde75 objc_exception_throw + 43
    2   CoreFoundation        0x00007fff8c25b10c +[NSException raise:format:] + 204
    3   APP_NAME              0x0000000107f5bde1 launch + 593
    4   APP_NAME              0x0000000107f5b366 main + 70
    5   APP_NAME              0x0000000107f5b314 start + 52
    6   ???                   0x0000000000000001 0x0 + 1
)

Environment Info:

$> java -version
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)

$> sw_vers
ProductName:    Mac OS X
ProductVersion: 10.9.4
BuildVersion:   13E28

Any ideas on what could be causing the issue?


问:
GridView with Pager TopAndBottom
I have extended the standard GridView control in ASP.NET. Basically it is just the same, but paging and sorting is done using callbacks.

I have successfully created my own PagerTemplate, but it only works when PagerSettings.Position is set to Top. I want to have the pager at both the top and the bottom.

I get an HttpException saying: The table must contain row sections in order of header, body, then footer.

Anyone know what this could be?

I already tried calling the MakeAccessible() method, but that doesn't help.

Code:

```<code>private int _IdColumnIndex = -1;

public override object DataSource
{
  get
  {
    return HttpContext.Current.Session[this.ClientID + "_DataSource"];
  }
  set
  {
    if (!value.GetType().Equals(typeof(DataView)))
      throw new ArgumentException("Only System.Data.DataView is accepted as a DataSource for DataGridView!");

    HttpContext.Current.Session[this.ClientID + "_DataSource"] = value;
  }
}

/// <summary>
/// Sets the default settings.
/// </summary>
private void SetDefaultSettings()
{
  base.AllowPaging = true;
  base.AllowSorting = true;
  base.ShowHeader = true;
  base.ShowFooter = true;
  base.PagerTemplate = new GridPagerTemplate(PAGER_ID, this);
  base.PagerSettings.Position = PagerPosition.TopAndBottom;
  base.PageSize = 10;

  AddSelectionCheckbox();
}

//private void MakeAccessible()
//{
//  if (this.Rows.Count > 0)
//  {
//    //This replaces <td> with <th> and adds the scope attribute
//    this.UseAccessibleHeader = true;

//    //This will add the <thead> and <tbody> elements
//    this.HeaderRow.TableSection = TableRowSection.TableHeader;

//    //This adds the <tfoot> element. Remove if you don't have a footer row
//    this.FooterRow.TableSection = TableRowSection.TableFooter;
//  }
//}

private void AddSelectionCheckbox()
{
  TemplateField tf = new TemplateField();
  tf.HeaderText = "";
  tf.ItemTemplate = new CheckboxTemplate(ROW_CHECKBOX_ID);

  base.Columns.Add(tf);
}

protected override void OnInit(EventArgs e)
{
  SetDefaultSettings();

  base.DataBound += new EventHandler(DataGridView_DataBound);
  base.RowDataBound += new GridViewRowEventHandler(DataGridView_RowDataBound);

  base.OnInit(e);
}

protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);
  //this.PaintRows();
  //this.FormatCells();

  // Get JavaScript for this DataGridView, and include it on the page.
  string scriptUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Yakinix.UI.Controls.DataGridView.js");
  Page.ClientScript.RegisterClientScriptInclude("DataGridView", scriptUrl);

  string js = "function DGV_MakeCallback(argument)" +
              "{" +
                  "__theFormPostData = '';" +
                  "__theFormPostCollection = new Array();" +
                  "WebForm_InitCallback();" +
                  GetCallbackEventReference("DGV_Callback") +
              ";}";

  Page.ClientScript.RegisterClientScriptBlock(typeof(DataGridView), typeof(DataGridView).FullName + "DGV_MakeCallback", js, true);

  if (this.HeaderRow != null)
    this.HeaderRow.TableSection = TableRowSection.TableHeader;
}

private string GetCallbackEventReference(string func)
{
  string callbackEventReference = Page.ClientScript.GetCallbackEventReference(this, "argument", func, "'" + ClientID + "'", false);

  return callbackEventReference;
}

public override void RenderBeginTag(HtmlTextWriter writer)
{
  writer.RenderBeginTag(HtmlTextWriterTag.Div); // <div>
  base.RenderBeginTag(writer);
}

public override void RenderEndTag(HtmlTextWriter writer)
{
  base.RenderEndTag(writer);
  writer.RenderEndTag(); // </div>
}

/// <summary>
/// Renders the gridview control and strips whitespace. It also
/// applies the right formatting.
/// </summary>
public string RenderHtml()
{
  using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
  {
    //this.PaintRows();
    //this.FormatCells();

    if (this.HeaderRow != null)
      this.HeaderRow.TableSection = TableRowSection.TableHeader;

    this.UseAccessibleHeader = true;
    this.RenderControl(new HtmlTextWriter(sw));
    string html = sw.ToString();

    return html;
  }
}

// TODO: Style all rows for the column matching current SortExpression.
protected void DataGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
  //DataGridView gridView = (DataGridView)sender;

  //if (gridView.SortExpression.Length > 0)
  //{
  //  int cellIndex = -1;

  //  //  find the column index for the corresponding sort expression
  //  foreach (DataControlField field in gridView.Columns)
  //  {
  //    if (field.SortExpression == gridView.SortExpression)
  //    {
  //      cellIndex = gridView.Columns.IndexOf(field);
  //      break;
  //    }
  //  }

  //  if (cellIndex > -1)
  //  {
  //    if (e.Row.RowType == DataControlRowType.Header)
  //    {
  //      //  this is a header row,
  //      //  set the sort style
  //      e.Row.Cells[cellIndex].CssClass += (gridView.SortDirection == SortDirection.Ascending ? " sortascheader" : " sortdescheader");
  //    }
  //    else if (e.Row.RowType == DataControlRowType.DataRow)
  //    {
  //      //  this is a data row
  //      e.Row.Cells[cellIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");
  //    }
  //  }
  //}

  RenderDetailsRow(e);
}

/// <summary>
/// Renders the details row, which is hidden when rendered. Clicking a details link, displays the row and more detailed data is shown, and is editable.
/// </summary>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
private void RenderDetailsRow(GridViewRowEventArgs e)
{
  // Only add a details row to DataRows
  if (false && e.Row.RowType == DataControlRowType.DataRow)
  {
    Table table = e.Row.Parent as Table;

    if (table != null)
    {
      GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
      row.Style[HtmlTextWriterStyle.Display] = "none";

      TableCell rowCell = new TableCell();
      rowCell.ColumnSpan = this.Columns.Count;
      rowCell.Height = new Unit(100);

      row.Cells.Add(rowCell);
      table.Rows.Add(row);

      HtmlAnchor htmlAhref = new HtmlAnchor();
      htmlAhref.HRef = "javascript:void(0);";
      htmlAhref.Attributes.Add("onclick", "ToggleElement('" + row.ClientID + "');");
      htmlAhref.InnerText = "Test";

      e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(htmlAhref);
    }
  }
}

protected void DataGridView_DataBound(object sender, EventArgs e)
{
  FillPagerDetails(base.TopPagerRow);
  FillPagerDetails(base.BottomPagerRow);
}

private void FillPagerDetails(GridViewRow pagerRow)
{
  if (pagerRow != null)
  {
    // Retrieve the DropDownList and Label controls from the row.
    DropDownList pageList = pagerRow.Cells[0].FindControl(PAGER_ID) as DropDownList;

    if (pageList != null)
    {
      pageList.Attributes.Add("onchange", "DataGridViewPage(this.value, '" + ClientID + "');");

      // Add the number of pages to the ListBox
      for (int i = 0; i < base.PageCount; i++)
      {
        int pageNumber = i + 1;

        // Create a ListItem that represents a page
        ListItem item = new ListItem(String.Format("{0}", pageNumber), i.ToString());

        // If the page is already selected, make sure the
        // ListBox select the selected page
        if (i == base.PageIndex)
          item.Selected = true;

        // Add the ListItem object to the Items collection of the DropDownList.
        pageList.Items.Add(item);
      }
    }
  }
}

protected override void InitializeRow(GridViewRow row, DataControlField[] fields)
{
  base.InitializeRow(row, fields);

  if (row.RowType == DataControlRowType.Header)
  {
    for (int i = 0; i < row.Cells.Count; i++)
    {
      row.Cells[i].Controls.Clear();

      if (row.Cells[i].Text.Equals("CHKCOL", StringComparison.Ordinal))
      {
        CheckBox chkSelectAll = new CheckBox();
        chkSelectAll.ID = "chkSelectAllRows";
        row.Cells[i].Controls.Add(chkSelectAll);
      }
      else
      {
        row.Cells[i].Text = String.Format(CultureInfo.InvariantCulture, "<a href=\"javaScript:DataGridViewSort('{0}', '{2}');void(0)\" title=\"{1}\">{1}</a>", fields[i].SortExpression, fields[i].HeaderText, this.ClientID);
      }
    }
    //if (ViewState["SortExpression"] != null)
    //{
    //  int index;
    //  index = 0;// GetHeaderCellIndex(ViewState["SortExpression"].ToString());
    //  if (index != -1)
    //  {
    //    //Literal literal;
    //    //if ((SortDirection)ViewState["SortDirection"] == SortDirection.Ascending)
    //    //{
    //    //  if (string.IsNullOrEmpty(SortAscendingImageUrl))
    //    //  {
    //    //    literal = new Literal();
    //    //    literal.Text = "↑";
    //    //    row.Cells[index].Controls.Add(literal);
    //    //  }
    //    //  else
    //    //  {
    //    //    sortImage.ImageUrl = SortAscendingImageUrl;
    //    //    row.Cells[index].Controls.Add(sortImage);
    //    //  }
    //    //}
    //    //else
    //    //{
    //    //  if (string.IsNullOrEmpty(SortDescendingImageUrl))
    //    //  {
    //    //    literal = new Literal();
    //    //    literal.Text = "↓";
    //    //    row.Cells[index].Controls.Add(literal);
    //    //  }
    //    //  else
    //    //  {
    //    //    sortImage.ImageUrl = SortDescendingImageUrl;
    //    //    row.Cells[index].Controls.Add(sortImage);
    //    //  }
    //    //}
    //  }
    //}
  }
  else if (row.RowType == DataControlRowType.DataRow)
  {
    for (int i = 0; i < row.Cells.Count; i++)
    {
      if (fields[i].HeaderText.Equals("id", StringComparison.InvariantCultureIgnoreCase))
      {
        _IdColumnIndex = i;
        break;
      }
    }
  }
}

protected override void OnRowCreated(GridViewRowEventArgs e)
{
  base.OnRowCreated(e);

  if (e.Row.RowType == DataControlRowType.Header)
  {
    //HtmlImage img = new HtmlImage();
    //img.ID = "lbCheckAll";
    //img.Src = "/img/btn_slct_all.gif";
    //img.Alt = "Select all";
    //img.Attributes.Add("onclick", "SelectAllRows('" + this.ClientID + "',true);return false;");
    //e.Row.Cells[0].Controls.Add(img);
  }
  else if (e.Row.RowType == DataControlRowType.DataRow)
  {
    //AddCheckbox(e);
  }
  else if (e.Row.RowType == DataControlRowType.Footer)
  {
    //e.Row.Cells[0].Text = "sdsds";
  }
}

protected override void OnRowDataBound(GridViewRowEventArgs e)
{
  base.OnRowDataBound(e);

  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    //AddCheckbox(e);

    if (_IdColumnIndex != -1)
      e.Row.Cells[_IdColumnIndex].Text = "<a href=\"Details.aspx?id=" + e.Row.Cells[_IdColumnIndex].Text + "\">Edit</a>";
  }
}

public override void Sort(string sortExpression, SortDirection sortDirection)
{
  DataView dv = this.DataSource as DataView;

  if (dv != null)
  {
    dv.Sort = sortExpression + " " + (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
  }
}

#region ICallbackEventHandler Members

private string callbackArg = String.Empty;

string ICallbackEventHandler.GetCallbackResult()
{
  // Save state with PageStatePersister and place it to Page.ClientState
  System.Reflection.MethodInfo mi = typeof(Page).GetMethod("SaveAllState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  mi.Invoke(this.Page, null);

  // Get serialized viewstate from Page's ClientState
  System.Reflection.PropertyInfo stateProp = typeof(Page).GetProperty("ClientState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  string state = stateProp.GetValue(this.Page, null).ToString();

  return callbackArg + "¤#¤" + state;
}

void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
  try
  {
    // Load XML from client
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(eventArgument.Replace("&", "&"));
    string pagerId = String.Empty;

    if (doc.DocumentElement.Name == "callback")
    {
      string gridId = doc.DocumentElement["arguments"]["gridId"].InnerText;

      switch (doc.DocumentElement["action"].InnerText)
      {
        case "sort":
          string sortExpression = doc.DocumentElement["arguments"]["sortExpression"].InnerText;
          Sort(sortExpression.Split(' ')[0].Trim(), sortExpression.Split(' ')[1].Trim().Equals("ASC") ? SortDirection.Ascending : SortDirection.Descending);
          break;

        case "page":
          string pageIndex = doc.DocumentElement["arguments"]["pageIndex"].InnerText;
          this.PageIndex = Convert.ToInt32(pageIndex);
          pagerId = base.BottomPagerRow.Cells[0].FindControl(PAGER_ID).ClientID;
          break;

        case "search":
          break;
      }

      this.DataBind();
      callbackArg = String.Format("{0}¤|¤{1}¤|¤{2}", gridId, this.RenderHtml(), pagerId);
    }

    doc = null;
  }
  catch (Exception ex)
  {
    callbackArg = String.Format(AJAX_ERROR_FORMAT, ex.Message + "\n\n" + ex.StackTrace);
  }
  finally
  {
    if (callbackArg.Equals(string.Empty))
    {
      callbackArg = String.Format(AJAX_ERROR_FORMAT, "An AJAX Error occurred!");
    }
  }
}

#endregion
</code>```

答:
Giving it a quick look over, you want to make sure that your header and footer pagers are correctly set to TableRowSection.TableHeader or TableRowSection.TableFooter.

You might be trying to draw your Bottom Pager as a thead and not a tfoot.

The error i believe is being thrown by the WebControls.Table

OwnerDisplayName: MartinHN

Title: GridView with Pager TopAndBottom

Body:
I have extended the standard GridView control in ASP.NET. Basically it is just the same, but paging and sorting is done using callbacks.

I have successfully created my own PagerTemplate, but it only works when PagerSettings.Position is set to Top. I want to have the pager at both the top and the bottom.

I get an HttpException saying: The table must contain row sections in order of header, body, then footer.

Anyone know what this could be?

I already tried calling the MakeAccessible() method, but that doesn't help.

Code:

private int _IdColumnIndex = -1;

public override object DataSource
{
  get
  {
    return HttpContext.Current.Session[this.ClientID + "_DataSource"];
  }
  set
  {
    if (!value.GetType().Equals(typeof(DataView)))
      throw new ArgumentException("Only System.Data.DataView is accepted as a DataSource for DataGridView!");

    HttpContext.Current.Session[this.ClientID + "_DataSource"] = value;
  }
}

///
/// Sets the default settings.
///
private void SetDefaultSettings()
{
  base.AllowPaging = true;
  base.AllowSorting = true;
  base.ShowHeader = true;
  base.ShowFooter = true;
  base.PagerTemplate = new GridPagerTemplate(PAGER_ID, this);
  base.PagerSettings.Position = PagerPosition.TopAndBottom;
  base.PageSize = 10;

  AddSelectionCheckbox();
}

//private void MakeAccessible()
//{
//  if (this.Rows.Count > 0)
//  {
//    //This replaces  with  and adds the scope attribute
//    this.UseAccessibleHeader = true;

//    //This will add the
 and
 elements
//    this.HeaderRow.TableSection = TableRowSection.TableHeader;

//    //This adds the
 element. Remove if you don't have a footer row
//    this.FooterRow.TableSection = TableRowSection.TableFooter;
//  }
//}

private void AddSelectionCheckbox()
{
  TemplateField tf = new TemplateField();
  tf.HeaderText = "";
  tf.ItemTemplate = new CheckboxTemplate(ROW_CHECKBOX_ID);

  base.Columns.Add(tf);
}

protected override void OnInit(EventArgs e)
{
  SetDefaultSettings();

  base.DataBound += new EventHandler(DataGridView_DataBound);
  base.RowDataBound += new GridViewRowEventHandler(DataGridView_RowDataBound);

  base.OnInit(e);
}

protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);
  //this.PaintRows();
  //this.FormatCells();

  // Get JavaScript for this DataGridView, and include it on the page.
  string scriptUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Yakinix.UI.Controls.DataGridView.js");
  Page.ClientScript.RegisterClientScriptInclude("DataGridView", scriptUrl);

  string js = "function DGV_MakeCallback(argument)" +
              "{" +
                  "__theFormPostData = '';" +
                  "__theFormPostCollection = new Array();" +
                  "WebForm_InitCallback();" +
                  GetCallbackEventReference("DGV_Callback") +
              ";}";

  Page.ClientScript.RegisterClientScriptBlock(typeof(DataGridView), typeof(DataGridView).FullName + "DGV_MakeCallback", js, true);

  if (this.HeaderRow != null)
    this.HeaderRow.TableSection = TableRowSection.TableHeader;
}

private string GetCallbackEventReference(string func)
{
  string callbackEventReference = Page.ClientScript.GetCallbackEventReference(this, "argument", func, "'" + ClientID + "'", false);

  return callbackEventReference;
}

public override void RenderBeginTag(HtmlTextWriter writer)
{
  writer.RenderBeginTag(HtmlTextWriterTag.Div); //

  base.RenderBeginTag(writer);
}

public override void RenderEndTag(HtmlTextWriter writer)
{
  base.RenderEndTag(writer);
  writer.RenderEndTag(); //

}

///
/// Renders the gridview control and strips whitespace. It also
/// applies the right formatting.
///
public string RenderHtml()
{
  using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
  {
    //this.PaintRows();
    //this.FormatCells();

    if (this.HeaderRow != null)
      this.HeaderRow.TableSection = TableRowSection.TableHeader;

    this.UseAccessibleHeader = true;
    this.RenderControl(new HtmlTextWriter(sw));
    string html = sw.ToString();

    return html;
  }
}

// TODO: Style all rows for the column matching current SortExpression.
protected void DataGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
  //DataGridView gridView = (DataGridView)sender;

  //if (gridView.SortExpression.Length > 0)
  //{
  //  int cellIndex = -1;

  //  //  find the column index for the corresponding sort expression
  //  foreach (DataControlField field in gridView.Columns)
  //  {
  //    if (field.SortExpression == gridView.SortExpression)
  //    {
  //      cellIndex = gridView.Columns.IndexOf(field);
  //      break;
  //    }
  //  }

  //  if (cellIndex > -1)
  //  {
  //    if (e.Row.RowType == DataControlRowType.Header)
  //    {
  //      //  this is a header row,
  //      //  set the sort style
  //      e.Row.Cells[cellIndex].CssClass += (gridView.SortDirection == SortDirection.Ascending ? " sortascheader" : " sortdescheader");
  //    }
  //    else if (e.Row.RowType == DataControlRowType.DataRow)
  //    {
  //      //  this is a data row
  //      e.Row.Cells[cellIndex].CssClass += (e.Row.RowIndex % 2 == 0 ? " sortaltrow" : "sortrow");
  //    }
  //  }
  //}

  RenderDetailsRow(e);
}

///
/// Renders the details row, which is hidden when rendered. Clicking a details link, displays the row and more detailed data is shown, and is editable.
///
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
private void RenderDetailsRow(GridViewRowEventArgs e)
{
  // Only add a details row to DataRows
  if (false && e.Row.RowType == DataControlRowType.DataRow)
  {
    Table table = e.Row.Parent as Table;

    if (table != null)
    {
      GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.DataRow, DataControlRowState.Normal);
      row.Style[HtmlTextWriterStyle.Display] = "none";

      TableCell rowCell = new TableCell();
      rowCell.ColumnSpan = this.Columns.Count;
      rowCell.Height = new Unit(100);

      row.Cells.Add(rowCell);
      table.Rows.Add(row);

      HtmlAnchor htmlAhref = new HtmlAnchor();
      htmlAhref.HRef = "javascript:void(0);";
      htmlAhref.Attributes.Add("onclick", "ToggleElement('" + row.ClientID + "');");
      htmlAhref.InnerText = "Test";

      e.Row.Cells[e.Row.Cells.Count - 1].Controls.Add(htmlAhref);
    }
  }
}

protected void DataGridView_DataBound(object sender, EventArgs e)
{
  FillPagerDetails(base.TopPagerRow);
  FillPagerDetails(base.BottomPagerRow);
}

private void FillPagerDetails(GridViewRow pagerRow)
{
  if (pagerRow != null)
  {
    // Retrieve the DropDownList and Label controls from the row.
    DropDownList pageList = pagerRow.Cells[0].FindControl(PAGER_ID) as DropDownList;

    if (pageList != null)
    {
      pageList.Attributes.Add("onchange", "DataGridViewPage(this.value, '" + ClientID + "');");

      // Add the number of pages to the ListBox
      for (int i = 0; i < base.PageCount; i++)
      {
        int pageNumber = i + 1;

        // Create a ListItem that represents a page
        ListItem item = new ListItem(String.Format("{0}", pageNumber), i.ToString());

        // If the page is already selected, make sure the
        // ListBox select the selected page
        if (i == base.PageIndex)
          item.Selected = true;

        // Add the ListItem object to the Items collection of the DropDownList.
        pageList.Items.Add(item);
      }
    }
  }
}

protected override void InitializeRow(GridViewRow row, DataControlField[] fields)
{
  base.InitializeRow(row, fields);

  if (row.RowType == DataControlRowType.Header)
  {
    for (int i = 0; i < row.Cells.Count; i++)
    {
      row.Cells[i].Controls.Clear();

      if (row.Cells[i].Text.Equals("CHKCOL", StringComparison.Ordinal))
      {
        CheckBox chkSelectAll = new CheckBox();
        chkSelectAll.ID = "chkSelectAllRows";
        row.Cells[i].Controls.Add(chkSelectAll);
      }
      else
      {
        row.Cells[i].Text = String.Format(CultureInfo.InvariantCulture, "{1}", fields[i].SortExpression, fields[i].HeaderText, this.ClientID);
      }
    }
    //if (ViewState["SortExpression"] != null)
    //{
    //  int index;
    //  index = 0;// GetHeaderCellIndex(ViewState["SortExpression"].ToString());
    //  if (index != -1)
    //  {
    //    //Literal literal;
    //    //if ((SortDirection)ViewState["SortDirection"] == SortDirection.Ascending)
    //    //{
    //    //  if (string.IsNullOrEmpty(SortAscendingImageUrl))
    //    //  {
    //    //    literal = new Literal();
    //    //    literal.Text = "↑";
    //    //    row.Cells[index].Controls.Add(literal);
    //    //  }
    //    //  else
    //    //  {
    //    //    sortImage.ImageUrl = SortAscendingImageUrl;
    //    //    row.Cells[index].Controls.Add(sortImage);
    //    //  }
    //    //}
    //    //else
    //    //{
    //    //  if (string.IsNullOrEmpty(SortDescendingImageUrl))
    //    //  {
    //    //    literal = new Literal();
    //    //    literal.Text = "↓";
    //    //    row.Cells[index].Controls.Add(literal);
    //    //  }
    //    //  else
    //    //  {
    //    //    sortImage.ImageUrl = SortDescendingImageUrl;
    //    //    row.Cells[index].Controls.Add(sortImage);
    //    //  }
    //    //}
    //  }
    //}
  }
  else if (row.RowType == DataControlRowType.DataRow)
  {
    for (int i = 0; i < row.Cells.Count; i++)
    {
      if (fields[i].HeaderText.Equals("id", StringComparison.InvariantCultureIgnoreCase))
      {
        _IdColumnIndex = i;
        break;
      }
    }
  }
}

protected override void OnRowCreated(GridViewRowEventArgs e)
{
  base.OnRowCreated(e);

  if (e.Row.RowType == DataControlRowType.Header)
  {
    //HtmlImage img = new HtmlImage();
    //img.ID = "lbCheckAll";
    //img.Src = "/img/btn_slct_all.gif";
    //img.Alt = "Select all";
    //img.Attributes.Add("onclick", "SelectAllRows('" + this.ClientID + "',true);return false;");
    //e.Row.Cells[0].Controls.Add(img);
  }
  else if (e.Row.RowType == DataControlRowType.DataRow)
  {
    //AddCheckbox(e);
  }
  else if (e.Row.RowType == DataControlRowType.Footer)
  {
    //e.Row.Cells[0].Text = "sdsds";
  }
}

protected override void OnRowDataBound(GridViewRowEventArgs e)
{
  base.OnRowDataBound(e);

  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    //AddCheckbox(e);

    if (_IdColumnIndex != -1)
      e.Row.Cells[_IdColumnIndex].Text = "Edit";
  }
}

public override void Sort(string sortExpression, SortDirection sortDirection)
{
  DataView dv = this.DataSource as DataView;

  if (dv != null)
  {
    dv.Sort = sortExpression + " " + (sortDirection == SortDirection.Ascending ? "ASC" : "DESC");
  }
}

#region ICallbackEventHandler Members

private string callbackArg = String.Empty;

string ICallbackEventHandler.GetCallbackResult()
{
  // Save state with PageStatePersister and place it to Page.ClientState
  System.Reflection.MethodInfo mi = typeof(Page).GetMethod("SaveAllState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  mi.Invoke(this.Page, null);

  // Get serialized viewstate from Page's ClientState
  System.Reflection.PropertyInfo stateProp = typeof(Page).GetProperty("ClientState", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
  string state = stateProp.GetValue(this.Page, null).ToString();

  return callbackArg + "¤#¤" + state;
}

void ICallbackEventHandler.RaiseCallbackEvent(string eventArgument)
{
  try
  {
    // Load XML from client
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(eventArgument.Replace("&", "&"));
    string pagerId = String.Empty;

    if (doc.DocumentElement.Name == "callback")
    {
      string gridId = doc.DocumentElement["arguments"]["gridId"].InnerText;

      switch (doc.DocumentElement["action"].InnerText)
      {
        case "sort":
          string sortExpression = doc.DocumentElement["arguments"]["sortExpression"].InnerText;
          Sort(sortExpression.Split(' ')[0].Trim(), sortExpression.Split(' ')[1].Trim().Equals("ASC") ? SortDirection.Ascending : SortDirection.Descending);
          break;

        case "page":
          string pageIndex = doc.DocumentElement["arguments"]["pageIndex"].InnerText;
          this.PageIndex = Convert.ToInt32(pageIndex);
          pagerId = base.BottomPagerRow.Cells[0].FindControl(PAGER_ID).ClientID;
          break;

        case "search":
          break;
      }

      this.DataBind();
      callbackArg = String.Format("{0}¤|¤{1}¤|¤{2}", gridId, this.RenderHtml(), pagerId);
    }

    doc = null;
  }
  catch (Exception ex)
  {
    callbackArg = String.Format(AJAX_ERROR_FORMAT, ex.Message + "\n\n" + ex.StackTrace);
  }
  finally
  {
    if (callbackArg.Equals(string.Empty))
    {
      callbackArg = String.Format(AJAX_ERROR_FORMAT, "An AJAX Error occurred!");
    }
  }
}

#endregion

OwnerDisplayName: Glennular


问:
How to get the parent control of WindowsFormsHost?
In my application, add my control(WF) in WindowsFormsHost and add this host in Window(WPF).

```<code>WindowsFormsHost host = new WindowsFormsHost();
host.Child = grid; //this is instance of WF control
testwindow.testSurface.Children.Add(host); // add in Window(WPF)
</code>```

Query:
Now i need to get the Handle value of "testWindow" from "grid" (in WF project not WPF) to capture image of testWindow.

I have tried "grid.Parent as WinFormsAdapter", but it is internal class. I found the below articles but it all shows in WPF project.

https://social.msdn.microsoft.com/Forums/vstudio/en-US/469f21db-c9cb-4e9c-a29a-b90722032cd1/how-to-find-the-winform-controls-parent-windowsformshost?forum=wpf

Please anyone suggest me how to achieve this?

Thanks,

答:
Try this to get the WindowsFormsHost from the grid. Once you have that, you can try working your way up to get the parent of WindowsFormsHost.

```<code>Control parent = grid.Parent;
Reflection.Assembly adapterAssembly = GetType(WindowsFormsHost).Assembly;
Type adapterType = adapterAssembly.GetType("System.Windows.Forms.Integration.WinFormsAdapter");
object adapterParent = adapterType.InvokeMember("_host", BindingFlags.NonPublic |BindingFlags.GetField | BindingFlags.Instance, null, adapter, new object[] {});
WindowsFormsHost winHost = adapterParent as WindowsFormsHost;
</code>```

Please note the above code is not tested but it is meant to help and hopefully guide you towards the end goal.

Body:
In my application, add my control(WF) in WindowsFormsHost and add this host in Window(WPF).

WindowsFormsHost host = new WindowsFormsHost();
host.Child = grid; //this is instance of WF control
testwindow.testSurface.Children.Add(host); // add in Window(WPF)

Query:
Now i need to get the Handle value of "testWindow" from "grid" (in WF project not WPF) to capture image of testWindow.

I have tried "grid.Parent as WinFormsAdapter", but it is internal class. I found the below articles but it all shows in WPF project.

https://social.msdn.microsoft.com/Forums/vstudio/en-US/469f21db-c9cb-4e9c-a29a-b90722032cd1/how-to-find-the-winform-controls-parent-windowsformshost?forum=wpf

Please anyone suggest me how to achieve this?

Thanks,

Body:
Try this to get the WindowsFormsHost from the grid. Once you have that, you can try working your way up to get the parent of WindowsFormsHost.

Control parent = grid.Parent;
Reflection.Assembly adapterAssembly = GetType(WindowsFormsHost).Assembly;
Type adapterType = adapterAssembly.GetType("System.Windows.Forms.Integration.WinFormsAdapter");
object adapterParent = adapterType.InvokeMember("_host", BindingFlags.NonPublic |BindingFlags.GetField | BindingFlags.Instance, null, adapter, new object[] {});
WindowsFormsHost winHost = adapterParent as WindowsFormsHost;

Please note the above code is not tested but it is meant to help and hopefully guide you towards the end goal.


问:
Generate PTS/SCR value for MJPEG uvc payload header
We are working on one UVC driver to stream mjpeg to host applications. We are using simple two bytes uvc frame header without any pts/scr value added to it. code works fine with all the linux based uvc host applications. but for windows based uvc host application lot of frame drops are happening.

I was wondering if anyone has seen this kind of behavior earlier. I am suspecting PTS/SCR value missing in header for frame synchronization.

If that is the case can anyone please give me one simple example how to calculate pts/scr value in host clock frequency units.

any kind of help appreciated.

答:
I found the root cause for an issue.

Issue was i wasn't making the requested usb length to 0 when i dont have any data to send to the host. That was creating bug in the flow.

Now it works fine in linux as well as in the windows without any glitches.

Thanks


问:
NSString Manipulation
I would like to manipulate the NSString like as

(0) Likes (1). (see. (2))

(0) =  Raman

(1) =  You

(2) = ThisGift

to

Raman Likes You. (see. ThisGift)

I dont know what approch can solve this problem.

Thanks in Advance,
Regards

Venkat.

答:
-[NSString stringByReplacingOccurrencesOfString:withString:].

You use it like this:

```<code>NSString * source = @"(0) Likes (1). (see. (2))";
source = [source stringByReplacingOccurrencesOfString:@"(0)" withString:@"Raman"];
NSLog(@"%@", source);  //logs "Raman Likes (1). (see. (2))"
</code>```

Title: NSString Manipulation

Body:
-[NSString stringByReplacingOccurrencesOfString:withString:].

You use it like this:

NSString * source = @"(0) Likes (1). (see. (2))";
source = [source stringByReplacingOccurrencesOfString:@"(0)" withString:@"Raman"];
NSLog(@"%@", source);  //logs "Raman Likes (1). (see. (2))"