问:
Same action for button and an nav item
I'm having 3 item and 3 buttons. For the buttons I have created a call to action functions and that intent is working fine. I would like add the same action to my nav items. How can I do that?

To be very clear. I need to show same activity when I click the button and the nav item. I'm new to Android. So I don't know even this is possible or not. Or I'm using the proper way to do this.

These are the intents I'm using for the buttons:

```<code>public void exploreActivity(View view){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }
</code>```

These are my menu items

```<code><?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@id/explore"
        android:icon="@drawable/ic_menu_exp"
        android:title="@string/Explore" />
    <item
        android:id="@id/menuPack"
        android:icon="@drawable/ic_menu_pack"
        android:title="@string/packages" />
    <item android:id="@id/dealsMenu"
        android:icon="@drawable/ic_menu_deals"
        android:title="@string/deals" />
    </menu>
</code>```

These are the three buttons I'm having now

```<code><Button
                android:id="@+id/explore"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/explorebutton"
                android:onClick="exploreActivity"
                android:text="@string/Explore"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/packages"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="24dp"
                android:layout_marginStart="24dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/packagebutton"
                android:onClick="packagesActivity"
                android:text="@string/packages"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toStartOf="@+id/deals"
                app:layout_constraintStart_toEndOf="@+id/explore"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/deals"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/dealsbutton"
                android:onClick="dealsActivity"
                android:text="@string/deals"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />
</code>```

I have made the changes on my HomeActivity.Java

```<code>package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    NavigationView mNavigationView;
    private int dotscount;
    private ImageView[] dots;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mtoggle;

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

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mNavigationView.setNavigationItemSelectedListener(this);

        mDrawerLayout.addDrawerListener(mtoggle);
        mtoggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewPager);

        sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
        viewPager.setAdapter(viewPagerAdapter);

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

        dotscount = viewPagerAdapter.getCount();
        dots = new ImageView[dotscount];

        for (int i = 0; i < dotscount; i++){
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.incative_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            params.setMargins(8, 0, 8,0);

            sliderDotspanel.addView(dots[i], params);
        }
        dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < dotscount; i++){
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.incative_dot));
                }
                dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mtoggle.onOptionsItemSelected(item)){
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class MyTimerTask extends TimerTask{

        @Override
        public void run() {

            HomeActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (viewPager.getCurrentItem() == 0){
                        viewPager.setCurrentItem(1);
                    }else if (viewPager.getCurrentItem() == 1){
                        viewPager.setCurrentItem(2);
                    }else{
                        viewPager.setCurrentItem(0);
                    }

                }
            });

        }
    }

    public void myMethod(){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }
    public void exploreActivity(View view){
        myMethod();
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.explore) {
            Log.d("Explore","Clicked");
            myMethod();
        }
        return false;
    }
   }
</code>```

But I got the following error

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.windows81.travelspoc, PID: 3485
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.windows81.travelspoc/com.example.windows81.travelspoc.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2625)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691)
                      at android.app.ActivityThread.access$1000(ActivityThread.java:188)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526)
                      at android.os.Handler.dispatchMessage(Handler.java:111)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5790)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at com.example.windows81.travelspoc.HomeActivity.onCreate(HomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6275)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2578)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691)
                      at android.app.ActivityThread.access$1000(ActivityThread.java:188)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526)
                      at android.os.Handler.dispatchMessage(Handler.java:111)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5790)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
</code>```

答:
Try this

Create method like this

```<code>public void myMethod(){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }
</code>```

than call your method in Button like this

```<code>public void exploreActivity(View view){
        myMethod()
    }
</code>```

now Implement NavigationView.OnNavigationItemSelectedListener the listener in your Activity:

```<code>public class YourActivity extends AppCompatActivity implements
              NavigationView.OnNavigationItemSelectedListene
</code>```

than set

```<code>     NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
   `mNavigationView.setNavigationItemSelectedListener(this);`
</code>```

Override the method

```<code>public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.explore) {
            Log.d("Explore","Clicked");
             myMethod()
        }
}
</code>```

Title: Same action for button and an nav item

Body:
I'm having 3 item and 3 buttons. For the buttons I have created a call to action functions and that intent is working fine. I would like add the same action to my nav items. How can I do that?

To be very clear. I need to show same activity when I click the button and the nav item. I'm new to Android. So I don't know even this is possible or not. Or I'm using the proper way to do this.

These are the intents I'm using for the buttons:

public void exploreActivity(View view){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }

These are my menu items

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@id/explore"
        android:icon="@drawable/ic_menu_exp"
        android:title="@string/Explore" />
    <item
        android:id="@id/menuPack"
        android:icon="@drawable/ic_menu_pack"
        android:title="@string/packages" />
    <item android:id="@id/dealsMenu"
        android:icon="@drawable/ic_menu_deals"
        android:title="@string/deals" />
    </menu>

These are the three buttons I'm having now

<Button
                android:id="@+id/explore"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/explorebutton"
                android:onClick="exploreActivity"
                android:text="@string/Explore"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/packages"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="24dp"
                android:layout_marginStart="24dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/packagebutton"
                android:onClick="packagesActivity"
                android:text="@string/packages"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toStartOf="@+id/deals"
                app:layout_constraintStart_toEndOf="@+id/explore"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/deals"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/dealsbutton"
                android:onClick="dealsActivity"
                android:text="@string/deals"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

I have made the changes on my HomeActivity.Java

package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    NavigationView mNavigationView;
    private int dotscount;
    private ImageView[] dots;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mtoggle;

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

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mNavigationView.setNavigationItemSelectedListener(this);

        mDrawerLayout.addDrawerListener(mtoggle);
        mtoggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewPager);

        sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
        viewPager.setAdapter(viewPagerAdapter);

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

        dotscount = viewPagerAdapter.getCount();
        dots = new ImageView[dotscount];

        for (int i = 0; i < dotscount; i++){
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.incative_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            params.setMargins(8, 0, 8,0);

            sliderDotspanel.addView(dots[i], params);
        }
        dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < dotscount; i++){
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.incative_dot));
                }
                dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mtoggle.onOptionsItemSelected(item)){
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class MyTimerTask extends TimerTask{

        @Override
        public void run() {

            HomeActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (viewPager.getCurrentItem() == 0){
                        viewPager.setCurrentItem(1);
                    }else if (viewPager.getCurrentItem() == 1){
                        viewPager.setCurrentItem(2);
                    }else{
                        viewPager.setCurrentItem(0);
                    }

                }
            });

        }
    }

    public void myMethod(){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }
    public void exploreActivity(View view){
        myMethod();
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.explore) {
            Log.d("Explore","Clicked");
            myMethod();
        }
        return false;
    }
   }

But I got the following error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.windows81.travelspoc, PID: 3485
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.windows81.travelspoc/com.example.windows81.travelspoc.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2625)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691)
                      at android.app.ActivityThread.access$1000(ActivityThread.java:188)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526)
                      at android.os.Handler.dispatchMessage(Handler.java:111)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5790)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at com.example.windows81.travelspoc.HomeActivity.onCreate(HomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6275)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2578)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691)
                      at android.app.ActivityThread.access$1000(ActivityThread.java:188)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526)
                      at android.os.Handler.dispatchMessage(Handler.java:111)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5790)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)

Body:
Try this

Create method like this

public void myMethod(){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }

than call your method in Button like this

public void exploreActivity(View view){
        myMethod()
    }

now Implement NavigationView.OnNavigationItemSelectedListener the listener in your Activity:

public class YourActivity extends AppCompatActivity implements
              NavigationView.OnNavigationItemSelectedListene

than set

     NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
   `mNavigationView.setNavigationItemSelectedListener(this);`

Override the method

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.explore) {
            Log.d("Explore","Clicked");
             myMethod()
        }
}


来源: stackexchange

问:
I have array of pointers of methods my class, but I cannot call my method. Code are below
```<code>#include <iostream>
#include <stdio.h>
#include <stdint.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class FooBar{
public:
        typedef void(FooBar::*OnDio)(void);

    void OnDio0Irq( void ){
        printf("dio0\n");
    };
    void OnDio1Irq( void ){
        printf("dio1\n");
    };
    FooBar(){
        OnDio  dioArray[] = {&OnDio0Irq, &OnDio1Irq};

    };

    OnDio  *dioArray[2];
private:

};

int main(int argc, char* argv[]){
        typedef void(FooBar::*OnDio)(void);
        void (FooBar::*foo)(void);
    OnDio *myPtr;
    FooBar *fb = new FooBar();

    myPtr = *(&fb->dioArray[0]);
    foo = (OnDio &)(myPtr[0]);
    (foo)();//me need call fb->dioArray[0]()
    (*myPtr)(); // ?
 }
</code>```

How can I call a function from an array?
In my code i have error:

[Error] must use '.' or '->' to call pointer-to-member function in 'foo
(...)', e.g. '(... ->* foo) (...)'

[Error] must use '.' or '->' to call pointer-to-member function in
'* myPtr (...)', e.g. '(... ->* * myPtr) (...)'

答:
To call a pointer to member function (ptmf), you need an instance and the ptmf, together.

OnDio is already typedef'ed to be a pointer type, so you may not want OnDio pointers.

Also, you initialize a local temporary in the constructor, not the dioArray of "this" instance.

This answer is also helpful: C++: Array of member function pointers to different functions

Here is your code, corrected to call dio0 through a pointer to member function.

```<code>#include <iostream>
#include <stdio.h>
#include <stdint.h>

class FooBar {
public:
    typedef void(FooBar::*OnDio)(void);

    void OnDio0Irq(void) {
        printf("dio0\n");
    };
    void OnDio1Irq(void) {
        printf("dio1\n");
    };
    FooBar() {
        // declaring a local OnDio array just masks the actual member and then it gets tossed
        // need to initialize this instance, not some local temporary
        dioArray[0] = &FooBar::OnDio0Irq;
        dioArray[1] = &FooBar::OnDio1Irq;
    };

    OnDio dioArray[2];
private:

};

int main(int argc, char* argv[]) {
    // need instance
    FooBar fb;
    // need pointer to member function
    FooBar::OnDio func = fb.dioArray[0];
    // call pointer to member function using instance
    (fb.*func)();
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
#include <iostream>
#include <stdio.h>
#include <stdint.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

class FooBar{
public:
        typedef void(FooBar::*OnDio)(void);

    void OnDio0Irq( void ){
        printf("dio0\n");
    };
    void OnDio1Irq( void ){
        printf("dio1\n");
    };
    FooBar(){
        OnDio  dioArray[] = {&OnDio0Irq, &OnDio1Irq};

    };

    OnDio  *dioArray[2];
private:

};

int main(int argc, char* argv[]){
        typedef void(FooBar::*OnDio)(void);
        void (FooBar::*foo)(void);
    OnDio *myPtr;
    FooBar *fb = new FooBar();

    myPtr = *(&fb->dioArray[0]);
    foo = (OnDio &)(myPtr[0]);
    (foo)();//me need call fb->dioArray[0]()
    (*myPtr)(); // ?
 }

How can I call a function from an array?
In my code i have error:

[Error] must use '.' or '->' to call pointer-to-member function in 'foo
(...)', e.g. '(... ->* foo) (...)'

[Error] must use '.' or '->' to call pointer-to-member function in
'* myPtr (...)', e.g. '(... ->* * myPtr) (...)'

Body:
To call a pointer to member function (ptmf), you need an instance and the ptmf, together.

OnDio is already typedef'ed to be a pointer type, so you may not want OnDio pointers.

Also, you initialize a local temporary in the constructor, not the dioArray of "this" instance.

This answer is also helpful: C++: Array of member function pointers to different functions

Here is your code, corrected to call dio0 through a pointer to member function.

#include <iostream>
#include <stdio.h>
#include <stdint.h>

class FooBar {
public:
    typedef void(FooBar::*OnDio)(void);

    void OnDio0Irq(void) {
        printf("dio0\n");
    };
    void OnDio1Irq(void) {
        printf("dio1\n");
    };
    FooBar() {
        // declaring a local OnDio array just masks the actual member and then it gets tossed
        // need to initialize this instance, not some local temporary
        dioArray[0] = &FooBar::OnDio0Irq;
        dioArray[1] = &FooBar::OnDio1Irq;
    };

    OnDio dioArray[2];
private:

};

int main(int argc, char* argv[]) {
    // need instance
    FooBar fb;
    // need pointer to member function
    FooBar::OnDio func = fb.dioArray[0];
    // call pointer to member function using instance
    (fb.*func)();
}


问:
Testing filters with IDependencyScope in Web API
I have WebApi simple NUnit Test

```<code>[Test]
public async Task Test()
{
    var attribute = new TestAuthenticationAttribute {ApiVersions = new[] {"v1"}};
    System.Web.Http.Controllers.HttpActionContext context = CreateExecutingContext();

    var executedContext = new HttpAuthenticationContext(context, null);

    const string reasonPhrase = "ReasonPhrase";
    const string messagePhrase = "MessagePhrase";

    executedContext.ErrorResult = new AuthenticationFailureResult(reasonPhrase, messagePhrase, executedContext.Request);

    await attribute.AuthenticateAsync(executedContext, CancellationToken.None);

    var errorResult = await executedContext.ErrorResult.ExecuteAsync(new CancellationToken());

    Assert.AreEqual(HttpStatusCode.Unauthorized, errorResult.StatusCode);
}

private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
{
    return new System.Web.Http.Controllers.HttpActionContext { ControllerContext = new HttpControllerContext {Request = new HttpRequestMessage()
    {
         RequestUri = new Uri("http://TestApi/api/v1/Test")
    }}};
}
</code>```

and in TestAuthenticationAttribute I have

```<code>if (context.Request.GetDependencyScope().GetService(typeof(IExternalService)) is IExternalService externalService)
            Do some actions;
</code>```

How to set/resolve IExternalService dependency in test? Do I need e.g. UnityContainer or I can do it without container?

答:
I added HttpConfiguration to my HttpActionContext and now Context.Request.GetDependencyScope() doesn't throw System.NullReferenceException. Of cource ontext.Request.GetDependencyScope().GetService(typeof(IExternalService)) is null, but now It's ok for my tests.

```<code>private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
{
    var config = new HttpConfiguration();

    var httpActionContext =  new System.Web.Http.Controllers.HttpActionContext
    {
        ControllerContext = new HttpControllerContext
        {
            Request = new HttpRequestMessage()
            {
                RequestUri = new Uri("http://TestApi/api/v1/Test"),
            },

            Configuration = config
        }
    };

    httpActionContext.ControllerContext.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

    return httpActionContext;

}
</code>```

If I want to resolve dependency, I will can add DependencyResolver to my config or Mocking framework

Body:
I have WebApi simple NUnit Test

[Test]
public async Task Test()
{
    var attribute = new TestAuthenticationAttribute {ApiVersions = new[] {"v1"}};
    System.Web.Http.Controllers.HttpActionContext context = CreateExecutingContext();

    var executedContext = new HttpAuthenticationContext(context, null);

    const string reasonPhrase = "ReasonPhrase";
    const string messagePhrase = "MessagePhrase";

    executedContext.ErrorResult = new AuthenticationFailureResult(reasonPhrase, messagePhrase, executedContext.Request);

    await attribute.AuthenticateAsync(executedContext, CancellationToken.None);

    var errorResult = await executedContext.ErrorResult.ExecuteAsync(new CancellationToken());

    Assert.AreEqual(HttpStatusCode.Unauthorized, errorResult.StatusCode);
}

private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
{
    return new System.Web.Http.Controllers.HttpActionContext { ControllerContext = new HttpControllerContext {Request = new HttpRequestMessage()
    {
         RequestUri = new Uri("http://TestApi/api/v1/Test")
    }}};
}

and in TestAuthenticationAttribute I have

if (context.Request.GetDependencyScope().GetService(typeof(IExternalService)) is IExternalService externalService)
            Do some actions;

How to set/resolve IExternalService dependency in test? Do I need e.g. UnityContainer or I can do it without container?

Body:
I added HttpConfiguration to my HttpActionContext and now Context.Request.GetDependencyScope() doesn't throw System.NullReferenceException. Of cource ontext.Request.GetDependencyScope().GetService(typeof(IExternalService)) is null, but now It's ok for my tests.

private System.Web.Http.Controllers.HttpActionContext CreateExecutingContext()
{
    var config = new HttpConfiguration();

    var httpActionContext =  new System.Web.Http.Controllers.HttpActionContext
    {
        ControllerContext = new HttpControllerContext
        {
            Request = new HttpRequestMessage()
            {
                RequestUri = new Uri("http://TestApi/api/v1/Test"),
            },

            Configuration = config
        }
    };

    httpActionContext.ControllerContext.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

    return httpActionContext;

}

If I want to resolve dependency, I will can add DependencyResolver to my config or Mocking framework


问:
AngularJS template parse error when using pipe
I am trying to sanitize text thats coming from db i dont control and show it as html. My broken code looks as follows.

```<code> <li *ngFor="let comm of commList|async;">
    <div class="notifBody">
      <span>
        <div [innerHTML]={{comm.text|safe : 'html'}}> </div>
      </span>
    </div>
 </li>
</code>```

The error i am getting is as follows

```<code>compiler.es5.js:1694 Uncaught Error: Template parse errors:
Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("
      <hr>
      <span>
        <div [innerHTML]={{comm.text|safe : 'html'}}>[ERROR ->]</div>
      </span>
    </div>
</code>```

I am guessing i am missing something in my syntax but not sure what.

If i remove the safe pipe as follows it works fine and renders the text as html....(not sanitized).

```<code>    <div class="notifBody">
      <span>
        <div [innerHTML]=comm.text></div>
      </span>
    </div>
</code>```

The following pipe test also works as expected but the text wont be rendered as html.

```<code><div class="notifBody">
  <span>
    {{comm.text|safe : 'html'}}
  </span>
</div>
</code>```

The Safe pipe just sanitizes the passed string using Sanitizer from angular core as follows.

```<code> import { Pipe, Sanitizer, SecurityContext } from '@angular/core';
 ...
 public transform(value: string, type: string): string {
    switch (type) {
        case 'html':
            return this.sanitizer.sanitize(SecurityContext.HTML, value);
    ...}}
</code>```

Thanks!

答:
Either you can use :

```<code>[innerHTML]="comm.text|safe : 'html'"
</code>```

or

```<code>innerHTML="{{comm.text|safe : 'html'}}"
</code>```

But you have mixed both syntax [innerHTML]={{comm.text|safe : 'html'}}

You can read more about it here : https://angular.io/guide/template-syntax#interpolation----

Body:
I am trying to sanitize text thats coming from db i dont control and show it as html. My broken code looks as follows.

The error i am getting is as follows

compiler.es5.js:1694 Uncaught Error: Template parse errors:
Unexpected closing tag "div". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags ("

[ERROR ->]

I am guessing i am missing something in my syntax but not sure what.

If i remove the safe pipe as follows it works fine and renders the text as html....(not sanitized).

The following pipe test also works as expected but the text wont be rendered as html.

    {{comm.text|safe : 'html'}}

The Safe pipe just sanitizes the passed string using Sanitizer from angular core as follows.

 import { Pipe, Sanitizer, SecurityContext } from '@angular/core';
 ...
 public transform(value: string, type: string): string {
    switch (type) {
        case 'html':
            return this.sanitizer.sanitize(SecurityContext.HTML, value);
    ...}}

Thanks!

Body:
Either you can use :

[innerHTML]="comm.text|safe : 'html'"

or

innerHTML="{{comm.text|safe : 'html'}}"

But you have mixed both syntax [innerHTML]={{comm.text|safe : 'html'}}

You can read more about it here : https://angular.io/guide/template-syntax#interpolation----


问:
Fastest way to retreive bitArray part
The title says all. My current version is:

```<code>Public Function GetBitArrayPart(ByVal BitArray As BitArray, _
                                ByVal IndexStart As Integer, _
                                ByVal IndexEnd As Integer) As BitArray

    If IndexStart < 0 OrElse IndexEnd > BitArray.Length - 1 OrElse IndexEnd < IndexStart Then
        Return New BitArray(0)
    End If

    Dim i As Integer
    Dim outputBA As New BitArray(IndexEnd - IndexStart + 1)

    For i = 0 To outputBA.Length - 1
        outputBA(i) = BitArray(IndexStart + i)
    Next

    Return outputBA

End Function
</code>```

I must specify that the sizes of lookup bitAarrays are big. I dont understand why using the System.String to store the same amount of information to retreive a part of that string is faster than using BitArray. For that reason I started to analize the performance of my functions.

答:
I'm not sure it's going to be faster, but here is an implementation based on copy to an array and create a new BitArray from it:</p>

```<code>Public Function GetBitArrayPart(ByVal BitArray As BitArray, _
                        ByVal IndexStart As Integer, _
                        ByVal IndexEnd As Integer) As BitArray

    If IndexStart < 0 OrElse IndexEnd > BitArray.Length - 1 OrElse IndexEnd < IndexStart Then
        Return New BitArray(0)
    End If

    Dim arr as Boolean()
    BitArray.CopyTo(arr, 0)
    Return new BitArray(arr.Skip(IndexStart).Take(IndexEnd - IndexStart).ToArray())

End Function
</code>```

Title: Fastest way to retreive bitArray part

Body:
The title says all. My current version is:

Public Function GetBitArrayPart(ByVal BitArray As BitArray, _
                                ByVal IndexStart As Integer, _
                                ByVal IndexEnd As Integer) As BitArray

    If IndexStart < 0 OrElse IndexEnd > BitArray.Length - 1 OrElse IndexEnd < IndexStart Then
        Return New BitArray(0)
    End If

    Dim i As Integer
    Dim outputBA As New BitArray(IndexEnd - IndexStart + 1)

    For i = 0 To outputBA.Length - 1
        outputBA(i) = BitArray(IndexStart + i)
    Next

    Return outputBA

End Function

I must specify that the sizes of lookup bitAarrays are big. I dont understand why using the System.String to store the same amount of information to retreive a part of that string is faster than using BitArray. For that reason I started to analize the performance of my functions.

Body:
I'm not sure it's going to be faster, but here is an implementation based on copy to an array and create a new BitArray from it:

Public Function GetBitArrayPart(ByVal BitArray As BitArray, _
                        ByVal IndexStart As Integer, _
                        ByVal IndexEnd As Integer) As BitArray

    If IndexStart < 0 OrElse IndexEnd > BitArray.Length - 1 OrElse IndexEnd < IndexStart Then
        Return New BitArray(0)
    End If

    Dim arr as Boolean()
    BitArray.CopyTo(arr, 0)
    Return new BitArray(arr.Skip(IndexStart).Take(IndexEnd - IndexStart).ToArray())

End Function


问:
Monitoring Apache Tomcat applications in production environment
How do you ensure that your applications in production are up and running?
How do you alert your team of developers if something goes wrong?

I'm asking this because I'm writing a bash script to check for this issue, I'd like to know if there is a smarter or more complete way to achieve this.
The idea behind is this command: wget -q -O - APPLICATION_URL_HERE | grep 'ERROR 404, I still have to check all kinds of HTTP errors, but you can get the point of what I mean.
If an application is recognized to not be running a mail is sent to the list of the team it belongs to.

All my applications are running on Apache Tomcat.

答:
We are running a couple of background applications and services. They all contain a small class that is triggered by a TCP/IP connection to send status information to a webservice that prints out the info on an ASP page. The page is refeshed every 5 minutes by a meta tag.

I just need to open the page in my browser and check from time to time if any of the components is offline (very easy to spot because they turn red).

The whole system is very lightweight and easy to include in any project. It was written by one of my colleagues, and works quite well. We could also enhance it to send us emails if a connection is lost for more than x minutes, but so far there has been no need for that.

OwnerDisplayName: Montecristo

LastEditorDisplayName: Patrick Cuff

OwnerDisplayName: Treb

ContentLicense: CC BY-SA 2.5


问:
how to run gulp tasks in order?
I am trying to concat all the css files into one released css file by running task:

```<code>gulp.task('task one', () => {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));
});
</code>```

After that, because the font path in the output css file is not correct, so I need to modify the path.

```<code>gulp.task('task two', () => {
    var urlAdjuster = require('gulp-css-url-adjuster');

    //change font path for released css files
    gulp.src([releasePath + "/*.css"])
        .pipe(urlAdjuster({
            replace: ['../../fonts', '../fonts'],
        }))
        .pipe(gulp.dest(releasePath + "/"));
);
</code>```

In order to make it happen, I need to run these two tasks separately one by one.
How can I run these two tasks in order and put them into one task.

I have tried:
series = require('gulp-series'); ----not working

```<code>gulp.task('task two', ['task one'], function () {
    // Gulp. src (...
});
</code>```

-----not working

---update--------------------------------------------------------
I used return but it is now working. The actual codes are:

```<code>function procHTMLForRelease(stream, file) {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));

}

function processRelease() {

    // Grab all html files in the folder.
    // Loop over them, process them, then spit em out.
    gulp.src([paths.Source + "/*.html"])
        .pipe(foreach(procHTMLForRelease))
        .pipe(gulp.dest(paths.Release));

    // Process image files
    gulp.src([paths.Source + "images/*.*"])
        .pipe(gulp.dest(paths.Release + "images/"));

    // Copy font files
    gulp.src([paths.html + "fonts/*.*", paths.html + "fonts/*/*.*"])
        .pipe(gulp.dest(paths.release + "/fonts/"));

}

gulp.task('task one', () => { return processRelease();
});
</code>```

答:
For anyone has the same problem and looking for a solution:
Here is what I do to fix it:
https://www.npmjs.com/package/run-sequence

For example:

```<code>// This will run in this order:
// * build-clean
// * build-scripts and build-styles in parallel
// * build-html
// * Finally call the callback function
gulp.task('build', function(callback) {
  runSequence('build-clean',
              ['build-scripts', 'build-styles'],
              'build-html',
              callback);
});
</code>```

Title: how to run gulp tasks in order?

Body:
I am trying to concat all the css files into one released css file by running task:

gulp.task('task one', () => {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));
});

After that, because the font path in the output css file is not correct, so I need to modify the path.

gulp.task('task two', () => {
    var urlAdjuster = require('gulp-css-url-adjuster');

    //change font path for released css files
    gulp.src([releasePath + "/*.css"])
        .pipe(urlAdjuster({
            replace: ['../../fonts', '../fonts'],
        }))
        .pipe(gulp.dest(releasePath + "/"));
);

In order to make it happen, I need to run these two tasks separately one by one.
How can I run these two tasks in order and put them into one task.

I have tried:
series = require('gulp-series'); ----not working

gulp.task('task two', ['task one'], function () {
    // Gulp. src (...
});

-----not working

---update--------------------------------------------------------
I used return but it is now working. The actual codes are:

function procHTMLForRelease(stream, file) {
    gulp.src([Dir + "**/*.css"])
        .pipe(concat(outFilename + ".css"))
        .pipe(gulp.dest(destDir));

}

function processRelease() {

    // Grab all html files in the folder.
    // Loop over them, process them, then spit em out.
    gulp.src([paths.Source + "/*.html"])
        .pipe(foreach(procHTMLForRelease))
        .pipe(gulp.dest(paths.Release));

    // Process image files
    gulp.src([paths.Source + "images/*.*"])
        .pipe(gulp.dest(paths.Release + "images/"));

    // Copy font files
    gulp.src([paths.html + "fonts/*.*", paths.html + "fonts/*/*.*"])
        .pipe(gulp.dest(paths.release + "/fonts/"));

}

gulp.task('task one', () => { return processRelease();
});

Body:
For anyone has the same problem and looking for a solution:
Here is what I do to fix it:
https://www.npmjs.com/package/run-sequence

For example:

// This will run in this order:
// * build-clean
// * build-scripts and build-styles in parallel
// * build-html
// * Finally call the callback function
gulp.task('build', function(callback) {
  runSequence('build-clean',
              ['build-scripts', 'build-styles'],
              'build-html',
              callback);
});


问:
Arrange nav tabs to single row in css/html
Im want to arrange all the nav tabs in a single row (in line with hr element).

I dont want any space between hr element and tabs.

After updating margin-top, for Technical Documentation tab, it seems fine, but for 1st tab , Products tab, still gap seems to be there between the hr.

Gap in the 1st tab

I have the below code like:

UPDATED:

```<code><div class="container">
    <ul class="nav nav-tabs search-results-navtab">
        <li class="active search-list-class">
            <a data-toggle="tab" href="#products">Products <br/></a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#multilayer_inductors_series">   Technical
                <br/>Documentation</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#smdpower_inductors_series">Support</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#molding_inductors_series">Component
                <br/>   Selector</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#shieldedsmdpower_inductors_series">Quality</a>
        </li>
    </ul>
    <hr class="search-hr">
</div>
</code>```

The Css is as:

```<code>.search-hr {
    margin-top: 0px;
}

.search-results-navtab {
    padding-left: 0px;
    margin-left: 32px;
    margin-right: 70px;
    margin-bottom: 1px;
    list-style: none;
    border: 0px !important;
    background-color: white;
}

.search-list-class {
    padding-right: 100px;
}
</code>```

答:
Solution #1

Remove the margin-top value from the hr element.

```<code>hr {
    margin-top: 0px;
}
</code>```

This will retain the margin-bottom value which you may need for spacing.

Solution #2

Alternatively, and I would recommend this, remove the hr element and declare border-bottom on a containing parent element of your list items (li), like .nav, then declare a margin-bottom property if you need bottom spacing.

```<code><div class="container">
    <ul class="nav nav-tabs search-results-navtab">
        <li class="active search-list-class">
            <a data-toggle="tab" href="#products">Products <br/></a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#multilayer_inductors_series">   Technical
                <br/>Documentation</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#smdpower_inductors_series">Support</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#molding_inductors_series">Component
                <br/>   Selector</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#shieldedsmdpower_inductors_series">Quality</a>
        </li>
    </ul>
</div>
</code>```

Additional Styles Declared:

```<code>.nav {
    border-bottom: 1px solid #ccc;
    margin-bottom: 10px; /* adjust as per requirement */
}
</code>```

Body:
Im want to arrange all the nav tabs in a single row (in line with hr element).

I dont want any space between hr element and tabs.

After updating margin-top, for Technical Documentation tab, it seems fine, but for 1st tab , Products tab, still gap seems to be there between the hr.

Gap in the 1st tab

I have the below code like:

UPDATED:

            Products

               Technical

Documentation

            Support

            Component

   Selector

            Quality

The Css is as:

.search-hr {
    margin-top: 0px;
}

.search-results-navtab {
    padding-left: 0px;
    margin-left: 32px;
    margin-right: 70px;
    margin-bottom: 1px;
    list-style: none;
    border: 0px !important;
    background-color: white;
}

.search-list-class {
    padding-right: 100px;
}

Body:
Solution #1

Remove the margin-top value from the hr element.

hr {
    margin-top: 0px;
}

This will retain the margin-bottom value which you may need for spacing.

Solution #2

Alternatively, and I would recommend this, remove the hr element and declare border-bottom on a containing parent element of your list items (li), like .nav, then declare a margin-bottom property if you need bottom spacing.

<div class="container">
    <ul class="nav nav-tabs search-results-navtab">
        <li class="active search-list-class">
            <a data-toggle="tab" href="#products">Products <br/></a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#multilayer_inductors_series">&nbsp;&nbsp;&nbsp;Technical
                <br/>Documentation</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#smdpower_inductors_series">Support</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#molding_inductors_series">Component
                <br/>&nbsp;&nbsp;&nbsp;Selector</a>
        </li>
        <li class="search-list-class">
            <a data-toggle="tab" href="#shieldedsmdpower_inductors_series">Quality</a>
        </li>
    </ul>
</div>

Additional Styles Declared:

.nav {
    border-bottom: 1px solid #ccc;
    margin-bottom: 10px; /* adjust as per requirement */
}


问:
PowerShell Issues with getting string from file

Problem

I am working on an automated version control script in powershell and I hit a snag where I am trying pull a line of text from an AssemblyInfo.cs file. However, I can't seem to get it to work as expected despite all my efforts.

After many trial and errors to achieve the results intended, I have come to find the following to get close to what I'm trying to achieve:

```<code># Constants
$Assembly = Get-Item "C:\generalfilepath\*\Assembly.cs"
$regex = '(?<!\/\/ \[assembly: AssemblyVersion\(")(?<=\[assembly: AssemblyVersion\(")[^"]*'

$CurrentVersion = GC $Assembly
$CurrentVersion = $CurrentVersion -match $regex

Write-Host "CurrentVersion = $CurrentVersion
</code>```

I am expecting to see: CurrentVersion = 1.0.0.0 or something similar, but what I get is: CurrentVersion = [assembly: AssemblyVersion("1.0.0.0")]

I have been searching all over for examples on how to properly utilize regex with PowerShell, but I have not really found anything that contains more than the regex itself... As such, I was hoping someone here could assist me in either steering me in the right direction or point out what I am doing wrong.

Question

Despite the use of the regex filter, I'm getting the entire line instead of just the value I want. How do I ensure the variable stores ONLY the target value using the lookbehind and lookahead regex filters?

答:
You can try:

```<code>C:\> ([string] (Get-Content \AssemblyInfo.cs)) -match 'AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\)'
True
</code>```

Afterwards the result shall be store in $Matches[1]

```<code>C:\> $Matches[1]
6.589.0.123
</code>```

Be aware to cast the results of Get-Content to [string] otherwise $Matches will be $null. See this answer for a complete description.

If you want to use a more "greedy" regex like ^\[assembly: AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\) which also includes a check (^\[assembly:) that the string starts with [assembly you've to walk through the [string[]] array Get-Content returns:

```<code>> gc .\AssemblyInfo.cs | % { $_ -match '^\[assembly: AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\)' }

> $Matches[1]
6.589.0.*
</code>```

Hope that helps.

Body:
Problem

I am working on an automated version control script in powershell and I hit a snag where I am trying pull a line of text from an AssemblyInfo.cs file. However, I can't seem to get it to work as expected despite all my efforts.

After many trial and errors to achieve the results intended, I have come to find the following to get close to what I'm trying to achieve:

# Constants
$Assembly = Get-Item "C:\generalfilepath\*\Assembly.cs"
$regex = '(?<!\/\/ \[assembly: AssemblyVersion\(")(?<=\[assembly: AssemblyVersion\(")[^"]*'

$CurrentVersion = GC $Assembly
$CurrentVersion = $CurrentVersion -match $regex

Write-Host "CurrentVersion = $CurrentVersion

I am expecting to see: CurrentVersion = 1.0.0.0 or something similar, but what I get is: CurrentVersion = [assembly: AssemblyVersion("1.0.0.0")]

I have been searching all over for examples on how to properly utilize regex with PowerShell, but I have not really found anything that contains more than the regex itself... As such, I was hoping someone here could assist me in either steering me in the right direction or point out what I am doing wrong.

Question

Despite the use of the regex filter, I'm getting the entire line instead of just the value I want. How do I ensure the variable stores ONLY the target value using the lookbehind and lookahead regex filters?

Body:
You can try:

C:\> ([string] (Get-Content \AssemblyInfo.cs)) -match 'AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\)'
True

Afterwards the result shall be store in $Matches[1]

C:\> $Matches[1]
6.589.0.123

Be aware to cast the results of Get-Content to [string] otherwise $Matches will be $null. See this answer for a complete description.

If you want to use a more "greedy" regex like ^\[assembly: AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\) which also includes a check (^\[assembly:) that the string starts with [assembly you've to walk through the [string[]] array Get-Content returns:

> gc .\AssemblyInfo.cs | % { $_ -match '^\[assembly: AssemblyVersion\("([0-9]+(\.([0-9]+|\*)){1,3}){1}"\)' }

> $Matches[1]
6.589.0.*

Hope that helps.


问:
Efficient way to define new variables by iterating a dictionary (Julia)
Consider a dictionary d in Julia which contains a thousand of keys. Each key is a symbol and each value is an array. I can access to the value associated with the symbol :S1 and assign it to the variable k1 via

k1 = d[:S1]

Now assume I want to define the new variables k2, k3, k4, ..., k10 by repeating the same procedure for the special keys :S1 ... :S10 (not for all the keys in the dictionary). What is the most efficient way to do it? I have the impression this can be solved using metaprogramming but not sure about that.

答:
In case you really want to have k1, k2, ... , k10, ... you could use a little more complicated eval than Lyndon's:

```<code>for (i,j) in enumerate(d)
       @eval $(Symbol("k$i")) = $j.second
end
</code>```

Warning: eval() use global scope so even if you use this inside a function k1...kn will be global variables.

Body:
In case you really want to have k1, k2, ... , k10, ... you could use a little more complicated eval than Lyndon's:

for (i,j) in enumerate(d)
       @eval $(Symbol("k$i")) = $j.second
end

Warning: eval() use global scope so even if you use this inside a function k1...kn will be global variables.


答:
For navigation menu -> Create it using NavigationView

here is proper example link for it -> http://v4all123.blogspot.in/2016/02/navigationview-example-in-android.html

Using this method you can create Nav Menu from Menu option.

Another method is using Recyclerview -> make Recyclerview and Handle all your intent through adapter.(If you have dynamic list or Long list then i would suggest 2nd method.)

Title: Same action for button and an nav item

Body:
I'm having 3 item and 3 buttons. For the buttons I have created a call to action functions and that intent is working fine. I would like add the same action to my nav items. How can I do that?

To be very clear. I need to show same activity when I click the button and the nav item. I'm new to Android. So I don't know even this is possible or not. Or I'm using the proper way to do this.

These are the intents I'm using for the buttons:

public void exploreActivity(View view){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }

These are my menu items

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@id/explore"
        android:icon="@drawable/ic_menu_exp"
        android:title="@string/Explore" />
    <item
        android:id="@id/menuPack"
        android:icon="@drawable/ic_menu_pack"
        android:title="@string/packages" />
    <item android:id="@id/dealsMenu"
        android:icon="@drawable/ic_menu_deals"
        android:title="@string/deals" />
    </menu>

These are the three buttons I'm having now

<Button
                android:id="@+id/explore"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/explorebutton"
                android:onClick="exploreActivity"
                android:text="@string/Explore"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/packages"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="24dp"
                android:layout_marginStart="24dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/packagebutton"
                android:onClick="packagesActivity"
                android:text="@string/packages"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toStartOf="@+id/deals"
                app:layout_constraintStart_toEndOf="@+id/explore"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/deals"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/dealsbutton"
                android:onClick="dealsActivity"
                android:text="@string/deals"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

I have made the changes on my HomeActivity.Java

package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    NavigationView mNavigationView;
    private int dotscount;
    private ImageView[] dots;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mtoggle;

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

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mNavigationView.setNavigationItemSelectedListener(this);

        mDrawerLayout.addDrawerListener(mtoggle);
        mtoggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewPager);

        sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
        viewPager.setAdapter(viewPagerAdapter);

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

        dotscount = viewPagerAdapter.getCount();
        dots = new ImageView[dotscount];

        for (int i = 0; i < dotscount; i++){
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.incative_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            params.setMargins(8, 0, 8,0);

            sliderDotspanel.addView(dots[i], params);
        }
        dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < dotscount; i++){
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.incative_dot));
                }
                dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mtoggle.onOptionsItemSelected(item)){
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class MyTimerTask extends TimerTask{

        @Override
        public void run() {

            HomeActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (viewPager.getCurrentItem() == 0){
                        viewPager.setCurrentItem(1);
                    }else if (viewPager.getCurrentItem() == 1){
                        viewPager.setCurrentItem(2);
                    }else{
                        viewPager.setCurrentItem(0);
                    }

                }
            });

        }
    }

    public void myMethod(){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }
    public void exploreActivity(View view){
        myMethod();
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.explore) {
            Log.d("Explore","Clicked");
            myMethod();
        }
        return false;
    }
   }

But I got the following error

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.windows81.travelspoc, PID: 3485
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.windows81.travelspoc/com.example.windows81.travelspoc.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2625)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691)
                      at android.app.ActivityThread.access$1000(ActivityThread.java:188)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526)
                      at android.os.Handler.dispatchMessage(Handler.java:111)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5790)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at com.example.windows81.travelspoc.HomeActivity.onCreate(HomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6275)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2578)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691)
                      at android.app.ActivityThread.access$1000(ActivityThread.java:188)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526)
                      at android.os.Handler.dispatchMessage(Handler.java:111)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5790)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)


问:
Is there big syntax differences between Clojure and Lisp
I want to learn new language and I thought to start with Lisp. I want to know  if I learn Lisp do I also know Clojure ( with minimal effort ), is there big syntax differences between Lisp and Clojure ?</p>

答:
I think it's fair to say that if you learn the principles of LISP you will also know the principles of Clojure and vice-versa. They are all rooted in the same philosophy, emphasising things such as:

Code is data. Macros are just normal functions that manipulate code.

Use of S-expressions to represent data and code.

The concept of a list / sequence as a fundamental structure.

Functional programming with first-class functions.

Apart from that, there are lots of differences in syntax, libraries, runtime environments etc. The difference in my view  is probably about the same as C# vs. C++ - if you know one well, then the core concepts will be familiar but there are still a lot of fundamental differences.

See this list of ways that Clojure is different from other Lisps


问:
Created SSH user on apache for specific directory, getting packet_write_wait: Connection to <my IP> port 22: Broken pipe error
My directory path is /var/www/my virtual host/public_html
I want to create a new ssh user which will have permission to my virtual host directory.

I have taken below steps.

```<code>groupadd sftpusers
useradd -g sftpusers -d /var/www/my virtual host -s /bin/bash  username
</code>```

Then i edit my sshd file

```<code>vi /etc/ssh/sshd_config
Subsystem sftp internal-sftp
Match group sftpusers
ChrootDirectory %h
ForceCommand internal-sftp

sudo service ssh restart
</code>```

Then i changed user for directory like

```<code>chown -R username:sftpusers /var/www/my virtual host
</code>```

Then i set the password for the user
But when i try to SSH to the server with this user. I get error as 'packet_write_wait: Connection to  port 22: Broken pipe
'
Does anyone have any idea about what am I missing here?

答: It turned out i had wrong permissions to /my virtual host/ dir. I set to username:groupname which should have been root:root. Changed it accordingly. And it worked.

Body:
My directory path is /var/www/my virtual host/public_html
I want to create a new ssh user which will have permission to my virtual host directory.

I have taken below steps.

groupadd sftpusers
useradd -g sftpusers -d /var/www/my virtual host -s /bin/bash  username

Then i edit my sshd file

vi /etc/ssh/sshd_config
Subsystem sftp internal-sftp
Match group sftpusers
ChrootDirectory %h
ForceCommand internal-sftp

sudo service ssh restart

Then i changed user for directory like

chown -R username:sftpusers /var/www/my virtual host

Then i set the password for the user
But when i try to SSH to the server with this user. I get error as 'packet_write_wait: Connection to  port 22: Broken pipe
'
Does anyone have any idea about what am I missing here?


问:
message not received in Bluetooth chat. Is my handler broken?
I am working on the project on the android dev. the website for BluetoothChat and it seems to be sending messages correctly but not receiving them. In the past,
I attempted to create another Bluetooth app and when connecting to a device I was prompted to confirm the connection and presented with a pin code. when working on the current app I am never given a prompt. However, it is not hitting any exceptions and messages seem to be sending. Here is my Thread class for managing a connection:

```<code>inner class ConnectedThread(val socket:BluetoothSocket, val socketType:String) : Thread(){

    val inStream = socket.inputStream
    val outStream = socket.outputStream

    init {
        mState = STATE_CONNECTED
    }

    override fun run() {
        Log.i(TAG, "BEGIN mConnectedThread")
        val buffer = ByteArray(1024)
        var bytes:Int

        while (mState == STATE_CONNECTED){
            try {
                bytes = inStream.read(buffer)

                mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget()
            }catch (ioe:IOException){
                Log.e(TAG, "disconnected", ioe)
                connectionLost()
                break
            }
        }
    }

    fun write(buffer:ByteArray){
        try {
            outStream.writeMessage(buffer, mHandler)
        }catch (ioe:IOException){
            Log.e(TAG, "Exception during write", ioe)
        }
    }

    fun cancel(){
        try {
            socket.close()
        }catch (ioe:IOException){
            Log.e(TAG, "close of connect socket failed", ioe)
        }
    }
}

}
</code>```

and below i it the extension function used to write to the OutputStream:

```<code>fun OutputStream.writeMessage(buffer:ByteArray, handler:Handler? = null){
write(buffer)

handler?.let {
    it.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
            .sendToTarget()
}
}
</code>```

I just am not sure where my mistake is. I was thinking it was a problem with the way that I am sending the message? But when I step through my code with the debugger I really don't see anything out of place. Now I am thinking that the problem is at the end of the receiving device which doesn't seem to receive anything at all. I will post my Handler and broadcastReceiver as well:

```<code>val mHandler = object:Handler(){
    override fun handleMessage(msg: Message?) {
        when(msg!!.what) {
            Constants.MESSAGE_STATE_CHANGE -> {
                when(msg.arg1) {
                    BluetoothChatService.STATE_CONNECTED -> {
                        setStatus(getString(R.string.title_connected_to, mConnectedDeviceName))
                        mConversationArrayAdapter!!.clear()
                    }
                    BluetoothChatService.STATE_CONNECTING -> {
                        setStatus(getString(R.string.title_connecting))
                    }
                    BluetoothChatService.STATE_LISTEN -> {
                    }
                    BluetoothChatService.STATE_NONE -> {
                        setStatus(getString(R.string.title_not_connected))
                    }
                }
            }
            Constants.MESSAGE_WRITE -> {
                val writeBuf = msg.obj as ByteArray
                val writeMessage = String(writeBuf)
                mConversationArrayAdapter!!.add("Me: $writeMessage")
            }
            Constants.MESSAGE_READ -> {
                val readBuf = msg.obj as ByteArray
                val readMessage = String(readBuf, 0, msg.arg1)
                mConversationArrayAdapter!!.add("$mConnectedDeviceName: $readMessage")
            }
            Constants.MESSAGE_DEVICE_NAME -> {
                mConnectedDeviceName = msg.data.getString(Constants.DEVICE_NAME)
                if (activity!=null)Toast.makeText(activity, "Connected to $mConnectedDeviceName", Toast.LENGTH_SHORT).show()
            }
            Constants.MESSAGE_TOAST -> {
                if (activity!=null)Toast.makeText(activity, msg.data.getString(Constants.TOAST), Toast.LENGTH_SHORT).show()
            }
        }
    }
}

val mReceiver:BroadcastReceiver = object:BroadcastReceiver(){
    override fun onReceive(context: Context, intent: Intent) {
         val action = intent.action

        if (BluetoothDevice.ACTION_FOUND.equals(action)){
            val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
            if (device.bondState!=BluetoothDevice.BOND_BONDED){
                mNewDevicesArrayAdapter.add("${device.name} \n ${device.address}")
            }
        }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
            setProgressBarIndeterminateVisibility(false)
            setTitle(R.string.select_device)
            if (mNewDevicesArrayAdapter.count==0){
                val noDevices = resources.getText(R.string.none_found).toString()
                mNewDevicesArrayAdapter.add(noDevices)
            }
        }
    }

}
</code>```

Here is my AcceptThread as well:

```<code>    inner class AcceptThread(val secure:Boolean) : Thread(){
    var mmServerSocket:BluetoothServerSocket? = null
    val mSocketType:String = if (secure) "Secure" else "Insecure"

    init {
        try {
            mmServerSocket = if (secure){
                mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_SECURE)
            } else {
                mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, UUID_INSECURE)
            }
        }catch (ioe:IOException){
            Log.e(TAG, "Socket Type: $mSocketType listen() failed", ioe)
        }
        mState = STATE_LISTEN
    }

    override fun run() {
        Log.d(TAG, "Socket Type: $mSocketType BEGIN $this")
        name = "AcceptThread $mSocketType"

        var socket:BluetoothSocket? = null

        while (mState!=STATE_CONNECTED){
            try {
                socket = mmServerSocket!!.accept()
            }catch (ioe:IOException){
                Log.e(TAG, "Socket Type: $mSocketType accept failed", ioe)
                break
            }
        }

        socket?.let {
            synchronized(this@BluetoothChatService){
                when(mState){
                    STATE_LISTEN -> {}
                    STATE_CONNECTING -> {
                        connected(socket!!, socket!!.remoteDevice, mSocketType)
                    }
                    STATE_NONE -> {}
                    STATE_CONNECTED -> {
                        try {
                        it.close()
                    }catch (ioe:IOException){
                        Log.e(TAG, "Could not close unwanted socket", ioe)
                        }
                    }
                    else->{throw BluetoothChatServiceException("Invalid Service State")}
                }
            }
        }
        Log.i(TAG, "End mAcceptThread, Socket Type: $mSocketType")
    }

    fun cancel(){
        Log.d(TAG, "Socket Type: $mSocketType cancel $this")
        try {
            mmServerSocket!!.close()
        }catch (ioe:IOException){
            Log.e(TAG, "Socket Type: $mSocketType close() of server failed", ioe)
        }
    }

}
</code>```

Please let me know if you're able to spot anything. I would really appreciate the help. Also, I should mention that the original code was in Java. I am writing mine in Kotlin.

答: Turns out the problem was my while loop. The while(mState!=STATE_CONNECTED loop should have enclosed the rest of the run() function body. So the solution was just moving the curly brace. Sometimes it's the little things. But I do appreciate the help with my when expressions.

Body:
I am working on the project on the android dev. the website for BluetoothChat and it seems to be sending messages correctly but not receiving them. In the past,
I attempted to create another Bluetooth app and when connecting to a device I was prompted to confirm the connection and presented with a pin code. when working on the current app I am never given a prompt. However, it is not hitting any exceptions and messages seem to be sending. Here is my Thread class for managing a connection:

inner class ConnectedThread(val socket:BluetoothSocket, val socketType:String) : Thread(){

    val inStream = socket.inputStream
    val outStream = socket.outputStream

    init {
        mState = STATE_CONNECTED
    }

    override fun run() {
        Log.i(TAG, "BEGIN mConnectedThread")
        val buffer = ByteArray(1024)
        var bytes:Int

        while (mState == STATE_CONNECTED){
            try {
                bytes = inStream.read(buffer)

                mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget()
            }catch (ioe:IOException){
                Log.e(TAG, "disconnected", ioe)
                connectionLost()
                break
            }
        }
    }

    fun write(buffer:ByteArray){
        try {
            outStream.writeMessage(buffer, mHandler)
        }catch (ioe:IOException){
            Log.e(TAG, "Exception during write", ioe)
        }
    }

    fun cancel(){
        try {
            socket.close()
        }catch (ioe:IOException){
            Log.e(TAG, "close of connect socket failed", ioe)
        }
    }
}

}

and below i it the extension function used to write to the OutputStream:

fun OutputStream.writeMessage(buffer:ByteArray, handler:Handler? = null){
write(buffer)

handler?.let {
    it.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
            .sendToTarget()
}
}

I just am not sure where my mistake is. I was thinking it was a problem with the way that I am sending the message? But when I step through my code with the debugger I really don't see anything out of place. Now I am thinking that the problem is at the end of the receiving device which doesn't seem to receive anything at all. I will post my Handler and broadcastReceiver as well:

val mHandler = object:Handler(){
    override fun handleMessage(msg: Message?) {
        when(msg!!.what) {
            Constants.MESSAGE_STATE_CHANGE -> {
                when(msg.arg1) {
                    BluetoothChatService.STATE_CONNECTED -> {
                        setStatus(getString(R.string.title_connected_to, mConnectedDeviceName))
                        mConversationArrayAdapter!!.clear()
                    }
                    BluetoothChatService.STATE_CONNECTING -> {
                        setStatus(getString(R.string.title_connecting))
                    }
                    BluetoothChatService.STATE_LISTEN -> {
                    }
                    BluetoothChatService.STATE_NONE -> {
                        setStatus(getString(R.string.title_not_connected))
                    }
                }
            }
            Constants.MESSAGE_WRITE -> {
                val writeBuf = msg.obj as ByteArray
                val writeMessage = String(writeBuf)
                mConversationArrayAdapter!!.add("Me: $writeMessage")
            }
            Constants.MESSAGE_READ -> {
                val readBuf = msg.obj as ByteArray
                val readMessage = String(readBuf, 0, msg.arg1)
                mConversationArrayAdapter!!.add("$mConnectedDeviceName: $readMessage")
            }
            Constants.MESSAGE_DEVICE_NAME -> {
                mConnectedDeviceName = msg.data.getString(Constants.DEVICE_NAME)
                if (activity!=null)Toast.makeText(activity, "Connected to $mConnectedDeviceName", Toast.LENGTH_SHORT).show()
            }
            Constants.MESSAGE_TOAST -> {
                if (activity!=null)Toast.makeText(activity, msg.data.getString(Constants.TOAST), Toast.LENGTH_SHORT).show()
            }
        }
    }
}

val mReceiver:BroadcastReceiver = object:BroadcastReceiver(){
    override fun onReceive(context: Context, intent: Intent) {
         val action = intent.action

        if (BluetoothDevice.ACTION_FOUND.equals(action)){
            val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
            if (device.bondState!=BluetoothDevice.BOND_BONDED){
                mNewDevicesArrayAdapter.add("${device.name} \n ${device.address}")
            }
        }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
            setProgressBarIndeterminateVisibility(false)
            setTitle(R.string.select_device)
            if (mNewDevicesArrayAdapter.count==0){
                val noDevices = resources.getText(R.string.none_found).toString()
                mNewDevicesArrayAdapter.add(noDevices)
            }
        }
    }

}

Here is my AcceptThread as well:

    inner class AcceptThread(val secure:Boolean) : Thread(){
    var mmServerSocket:BluetoothServerSocket? = null
    val mSocketType:String = if (secure) "Secure" else "Insecure"

    init {
        try {
            mmServerSocket = if (secure){
                mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, UUID_SECURE)
            } else {
                mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME_INSECURE, UUID_INSECURE)
            }
        }catch (ioe:IOException){
            Log.e(TAG, "Socket Type: $mSocketType listen() failed", ioe)
        }
        mState = STATE_LISTEN
    }

    override fun run() {
        Log.d(TAG, "Socket Type: $mSocketType BEGIN $this")
        name = "AcceptThread $mSocketType"

        var socket:BluetoothSocket? = null

        while (mState!=STATE_CONNECTED){
            try {
                socket = mmServerSocket!!.accept()
            }catch (ioe:IOException){
                Log.e(TAG, "Socket Type: $mSocketType accept failed", ioe)
                break
            }
        }

        socket?.let {
            synchronized(this@BluetoothChatService){
                when(mState){
                    STATE_LISTEN -> {}
                    STATE_CONNECTING -> {
                        connected(socket!!, socket!!.remoteDevice, mSocketType)
                    }
                    STATE_NONE -> {}
                    STATE_CONNECTED -> {
                        try {
                        it.close()
                    }catch (ioe:IOException){
                        Log.e(TAG, "Could not close unwanted socket", ioe)
                        }
                    }
                    else->{throw BluetoothChatServiceException("Invalid Service State")}
                }
            }
        }
        Log.i(TAG, "End mAcceptThread, Socket Type: $mSocketType")
    }

    fun cancel(){
        Log.d(TAG, "Socket Type: $mSocketType cancel $this")
        try {
            mmServerSocket!!.close()
        }catch (ioe:IOException){
            Log.e(TAG, "Socket Type: $mSocketType close() of server failed", ioe)
        }
    }

}

Please let me know if you're able to spot anything. I would really appreciate the help. Also, I should mention that the original code was in Java. I am writing mine in Kotlin.


问:
Firebase Auth for Twitter with React
I have been working to create an authentication process where users can log-in via Twitter using Firebase's authentication. After logging in, I am trying to store the user's token and secret so that I can perform Twitter actions on behalf of the users. So far, this is what my login looks like:

```<code>export function loginWithTwitter() {
   return auth.signInWithPopup(provider)
}
</code>```

and inside my main file, I have implemented a button that calls a function that in turn calls the function above to authenticate the user. It looks like this:

```<code>login() {
loginWithTwitter()
.then((result) => {
 const user = result.user;
   accessToken = result.credential.accessToken;
   accessTokenSecret = result.credential.secret;
  this.setState({
    user
  });
});
localStorage.setItem(firebaseAuthKey, "1");
}
</code>```

This code properly pulls up the window and authenticates the app with the user but when testing the accessToken and accessTokenSecret values it appears that they are not ever receiving input since printing them out to the console for testing returns values of undefined. Is there anything obvious I am doing wrong that is causing this? Thanks!

The initial resource I used on how to do authentication is here: https://firebase.google.com/docs/auth/web/twitter-login

EDIT: For further testing, I set the values of accessToken and accessTokenSecret to random integers and added the line of code

```<code>accessToken = 'changed';
</code>```

in the second block of code right below where I set accessTokenSecret = result.credential.secret. When I ran through the program, the console printed out the initial values assigned to the variables, never changing them. It seems to me that for some reason the code in the second block is never run through, but I am still not sure why.

答:
try this way with handling error message

export function loginWithTwitter() {
// make sure your Firebase OAuth redirect URI (e.g. my-app-12345.firebaseapp.com/__/auth/handler) is set as your Callback URL in your app's settings page on your Twitter app's config in firebase console. You have to sign in for API and secret
   return provider;
}
//import the function loginwithTwiter
//bind this if required.
login=()=> {
var provider = loginWithTwitter();
firebase.auth().signInWithPopup(provider).then(function (result){
  var token = result.credential.accessToken;
  var secret = result.credential.secret;
  // The signed-in user info.
  var user = result.user;
  //set this data in your state or anywhere.
  this.setState({ user : user, tok: token })
}).catch(err => {
  console.log(err.message);
});```

Title: Firebase Auth for Twitter with React

Body:
I have been working to create an authentication process where users can log-in via Twitter using Firebase's authentication. After logging in, I am trying to store the user's token and secret so that I can perform Twitter actions on behalf of the users. So far, this is what my login looks like:

export function loginWithTwitter() {
   return auth.signInWithPopup(provider)
}

and inside my main file, I have implemented a button that calls a function that in turn calls the function above to authenticate the user. It looks like this:

login() {
loginWithTwitter()
.then((result) => {
 const user = result.user;
   accessToken = result.credential.accessToken;
   accessTokenSecret = result.credential.secret;
  this.setState({
    user
  });
});
localStorage.setItem(firebaseAuthKey, "1");
}

This code properly pulls up the window and authenticates the app with the user but when testing the accessToken and accessTokenSecret values it appears that they are not ever receiving input since printing them out to the console for testing returns values of undefined. Is there anything obvious I am doing wrong that is causing this? Thanks!

The initial resource I used on how to do authentication is here: https://firebase.google.com/docs/auth/web/twitter-login

EDIT: For further testing, I set the values of accessToken and accessTokenSecret to random integers and added the line of code

accessToken = 'changed';

in the second block of code right below where I set accessTokenSecret = result.credential.secret. When I ran through the program, the console printed out the initial values assigned to the variables, never changing them. It seems to me that for some reason the code in the second block is never run through, but I am still not sure why.


问:
get Value of selected item in FlatList. -- React Native
I have implemented a flat list component by binding an array. when i tap an item . I have to get either item name or Id.</p>

```<code> _renderList = ({ item }) => {
    return (
        <View style={styles.listContainer} onPress={this._selectedItem(item.text)}  >
            <Image style={styles.listImage} source={item.avatar} />
            <Text style={styles.listText} >{item.text}</Text>
            <Text style={styles.listVal} >{item.val}</Text>
            <Image style={styles.listImage}   source={require('../../resources/icons/MyAccount/arrowright.png')} />
        </View>
    );

}

<FlatList data={this.state.data} renderItem={this._renderList} />
</code>```

答:
You can use TouchableOpacity, TouchableHighlitfor, TouchableWithoutFeedback onPress event. View doesn't provide onPress prop.

```<code> _renderList = ({ item }) => {
    return (
     <TouchableWithoutFeedback onPress={(item)=>this._selectedItem(item.text)}>
        <View style={styles.listContainer}>
            <Image style={styles.listImage} source={item.avatar} />
            <Text style={styles.listText} >{item.text}</Text>
            <Text style={styles.listVal} >{item.val}</Text>
            <Image style={styles.listImage}   source={require('../../resources/icons/MyAccount/arrowright.png')} />
        </View>
     </TouchableWithoutFeedback>
    );

}

<FlatList data={this.state.data} renderItem={this._renderList} />
</code>```

Body:
I have implemented a flat list component by binding an array. when i tap an item . I have to get either item name or Id.

 _renderList = ({ item }) => {
    return (
        <View style={styles.listContainer} onPress={this._selectedItem(item.text)}  >
            <Image style={styles.listImage} source={item.avatar} />
            <Text style={styles.listText} >{item.text}</Text>
            <Text style={styles.listVal} >{item.val}</Text>
            <Image style={styles.listImage}   source={require('../../resources/icons/MyAccount/arrowright.png')} />
        </View>
    );

}

<FlatList data={this.state.data} renderItem={this._renderList} />

Body:
You can use TouchableOpacity, TouchableHighlitfor, TouchableWithoutFeedback onPress event. View doesn't provide onPress prop.

 _renderList = ({ item }) => {
    return (
     <TouchableWithoutFeedback onPress={(item)=>this._selectedItem(item.text)}>
        <View style={styles.listContainer}>
            <Image style={styles.listImage} source={item.avatar} />
            <Text style={styles.listText} >{item.text}</Text>
            <Text style={styles.listVal} >{item.val}</Text>
            <Image style={styles.listImage}   source={require('../../resources/icons/MyAccount/arrowright.png')} />
        </View>
     </TouchableWithoutFeedback>
    );

}

<FlatList data={this.state.data} renderItem={this._renderList} />


问:
How to show the inside div(replacable) if I scrolled to the leftmost
Attached is the Plunker Demo.I need to show Div-2 in place of Div-1, after user scrolled the Div-1 to the leftmost..can any one help me out?..

HTML

```<code><div id="div-1" class="scrollable-div">
  <div class="div-inside">Div 1:After scrolling this I should get Div-2 inplace of Div-1</div>
</div>
<div id="div-2" class="scrollable-div">
    <div class="div-inside">Div 2:After scrolling this I should show "End-treatment"</div>
</div>
</code>```

jQuery

```<code>    jQuery(function ($) {
                  $('#div-2').hide();
  $('#div-1').on('scroll', function () {
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) {
      $('#div-2').show();
    } else if($(this).scrollLeft() === 0) {
      $('#other-message').show();
    // Remove this part if you don't want your messages hidden again
    } else {
      $('#end-treatment').hide();
      $('#other-message').hide();
    }
  })
    $('#div-2').on('scroll', function () {
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) {
      $('#end-treatment').show();
    } else if($(this).scrollLeft() === 0) {
      $('#other-message').show();
    // Remove this part if you don't want your messages hidden again
    } else {
      $('#end-treatment').hide();
      $('#other-message').hide();
    }
  })

});
</code>```

答:
Here is the Updated Plunker Demo with answer given in above comment</p>

```<code>jQuery(function ($)
      {
        $('#div-2').hide();

  $('#div-1').on('scroll', function () {
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth)
    {
         $('#div-2').show(1000);
         $('#div-1').hide();
    }
 })
</code>```

Body:
Attached is the Plunker Demo.I need to show Div-2 in place of Div-1, after user scrolled the Div-1 to the leftmost..can any one help me out?..

HTML

Div 1:After scrolling this I should get Div-2 inplace of Div-1

Div 2:After scrolling this I should show "End-treatment"

jQuery

    jQuery(function ($) {
                  $('#div-2').hide();
  $('#div-1').on('scroll', function () {
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) {
      $('#div-2').show();
    } else if($(this).scrollLeft() === 0) {
      $('#other-message').show();
    // Remove this part if you don't want your messages hidden again
    } else {
      $('#end-treatment').hide();
      $('#other-message').hide();
    }
  })
    $('#div-2').on('scroll', function () {
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) {
      $('#end-treatment').show();
    } else if($(this).scrollLeft() === 0) {
      $('#other-message').show();
    // Remove this part if you don't want your messages hidden again
    } else {
      $('#end-treatment').hide();
      $('#other-message').hide();
    }
  })

});

Body:
Here is the Updated Plunker Demo with answer given in above comment

jQuery(function ($)
      {
        $('#div-2').hide();

  $('#div-1').on('scroll', function () {
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth)
    {
         $('#div-2').show(1000);
         $('#div-1').hide();
    }
 })