问:
Bluetooth enable intent in fragment
I've been searching everywhere and I can't find the answer. I'm simply trying to enable bluetooth in my fragment. I added the following to lines to my OnResume() callback:

```<code>        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
    }
</code>```

for some reason, the output just keeps saying, Activity.onPostResume() called over and over again and it actually locks out my UI. I was wondering if there's a solution?

Edit: AutoConnectFragment:

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

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private Toolbar mToolbar;
    private CollapsingToolbarLayout collapsingToolbar;
    private ImageView mBackArrow;
    private Button mStartTiming;
    private RecyclerView mLaserRecyclerView;
    private LaserAdapter mAdapter;
    private String mCurrentEvent;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private AutoConnectBLE mScanner;
    private static boolean mIsLasersConnected;
    private Drill mCurrentDrill;
    private AutoConnectEventSelected mCallback;
    private static final int REQUEST_ENABLE_BT = 3;
    private static final int REQUEST_CODE_LOCATION = 42;
    private boolean permissionChecked = false;

    // Container Activity must implement this interface
    public interface AutoConnectEventSelected {
        public void onAutoConnectEventSelected(String event);
    }

    // private nested custom view holder class
    public class LaserHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private TextView mLaserName;
        private Module mModule;
        private ImageView mConnectIcon;
        private ProgressBar mProgressBar;

        public LaserHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item_laser, parent, false));
            itemView.setOnClickListener(this);

            // grab the font
            Typeface mont_reg = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");

            // grab the user name and change the font
            mLaserName = (TextView) itemView.findViewById(R.id.laser_name);
            mLaserName.setTypeface(mont_reg);

            // grab the progress bar
            mProgressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);

            //grab the connect icon
            mConnectIcon = (ImageView) itemView.findViewById(R.id.connect_icon);
        }

        public void bind(Module module) {

            // set the text view to the module name
            mModule = module;
            mLaserName.setText(module.getName());
        }

        // if the user clicks on the connect laser
        @Override
        public void onClick(View v) {
            if (mModule.getName().equals("RFID")) {
                mProgressBar.setVisibility(View.VISIBLE);
                mConnectIcon.setVisibility(View.GONE);
//                mScanner.scanRFID(mCurrentDrill, mModule.getName(), v, getContext(), mAdapter,getAdapterPosition());
            } else {
                mProgressBar.setVisibility(View.VISIBLE);
                mConnectIcon.setVisibility(View.GONE);
                mScanner.scanLaser(v,mCurrentDrill, mModule.getName(),mAdapter,getAdapterPosition());
            }

            mAdapter.setCurrentPosition(getAdapterPosition());

        }
    }

    public class LaserAdapter extends RecyclerView.Adapter<LaserHolder> {
        private List<Module> mModules;
        private String mCurrentMAC;
        private int mCurrentPosition;

        public LaserAdapter(List<Module> modules) {
            mModules = modules;
        }

        @Override
        public LaserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new LaserHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(LaserHolder holder, int position) {
            Module module = mModules.get(position);
            /* if a laser is already connected and
            the user tries to connect the same laser to another position,
            unconnect the previous connection
             */
            if (!TextUtils.isEmpty(module.getMACaddress())){
                if ( module.getMACaddress().equals(mCurrentMAC) && position != mCurrentPosition){
                    holder.mConnectIcon.setImageResource(R.drawable.ic_flash);
                    module.setMACaddress(null);
                }
            }

            checkAllLasersConnected(mModules);

            holder.bind(module);
        }

        @Override
        public int getItemCount() {
            return mModules.size();
        }

        public String getCurrentMAC() {
            return mCurrentMAC;
        }

        public void setCurrentMAC(String currentMAC) {
            mCurrentMAC = currentMAC;
        }

        public int getCurrentPosition() {
            return mCurrentPosition;
        }

        public void setCurrentPosition(int currentPosition) {
            mCurrentPosition = currentPosition;
        }

        public void checkAllLasersConnected(List<Module> modules){

            int numLasersConnected = 0;
            // checking to see if all of the lasers are connected
            for (int i = 0; i < modules.size(); i++) {
                System.out.println("Name: " + modules.get(i).getName() + " MAC :" + modules.get(i).getMACaddress());
                if (modules.get(i).getMACaddress() == null) {
                    numLasersConnected++;
                }
            }

            // if all of the lasers are connected, enabled the start timing button
            if (numLasersConnected == 0) {
                mStartTiming.setEnabled(true);
            } else {
                mStartTiming.setEnabled(false);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        // inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_autoconnect, container, false);

        // grab the recyclerview and set its layout manager
        mLaserRecyclerView = (RecyclerView) view.findViewById(R.id.list_recycler_view);
        mLaserRecyclerView.setLayoutManager((new LinearLayoutManager(getActivity())));

        // update the UI ( recycler view )
        updateUI(savedInstanceState);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // grab the views
        collapsingToolbar = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        mBackArrow = (ImageView) view.findViewById(R.id.back_arrow);
        mStartTiming = (Button) view.findViewById(R.id.start_timing_button);

        // disable the startTiming button until all of the lasers are connected
        mStartTiming.setEnabled(false);

        //Set toolbar title
        collapsingToolbar.setTitle(getArguments().getString("Event") + " Connect");
        // setting the text alignment
        collapsingToolbar.setExpandedTitleColor(Color.WHITE);
        collapsingToolbar.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
        collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
        collapsingToolbar.setExpandedTitleGravity(Gravity.CENTER_HORIZONTAL);

        // set the font
        Typeface mont_bold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Bold.ttf");
        Typeface mont_regular = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");
        collapsingToolbar.setExpandedTitleTypeface(mont_bold);
        collapsingToolbar.setCollapsedTitleTypeface(mont_regular);

        // set background color to dark grey
        mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));

        // set up bluetooth
        mScanner = new AutoConnectBLE(getContext());

        // collapsing tool bar effect ( explained in main activtiy)
        AppBarLayout mAppBarLayout = (AppBarLayout) view.findViewById(R.id.app_bar_layout);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                //measuring for alpha
                int toolBarHeight = mToolbar.getMeasuredHeight();
                int appBarHeight = appBarLayout.getMeasuredHeight();
                Float f = ((((float) appBarHeight - toolBarHeight) + i) / ((float) appBarHeight - toolBarHeight)) * 255;
                if (Math.round(f) == 0) {
                    mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));
                } else {
                    mToolbar.getBackground().setAlpha(0);
                }

            }
        });

        // if user clicks on the back arrow, go back to testing page
        mBackArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment frag = new TestingFragment();
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, frag, frag.getTag());
                ft.addToBackStack(null);
                ft.commit();
            }
        });

        // if the user clicks on the start timing, goto the timing page
        mStartTiming.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.onAutoConnectEventSelected(getArguments().getString("Event"));
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("ON RESUME CALLED");

        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            System.out.println("INTENT CALLED");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            getActivity().startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
//
//        if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
//            Toast.makeText(getActivity(), "No LE Support, Please install this app on another phone", Toast.LENGTH_SHORT).show();
//            return;
//        }

    }

    private void updateUI(Bundle savedInstanceState) {

        List<Module> modules = null;
        // check to see which event the user chose and grab the laser array list
        switch (getArguments().getString("Event")) {
            case "Dash":
                Dash dash = Dash.getInstance();
                modules = dash.getModules();
                mCurrentDrill = dash;
                break;
            case "ProAgility":
                ProAgility pa = ProAgility.getInstance();
                modules = pa.getModules();
                mCurrentDrill = pa;
                break;
            case "DashSplit":
                DashSplit ds = DashSplit.getInstance();
                modules = ds.getModules();
                mCurrentDrill = ds;
                break;
            case "Flying40":
                Flying40 f = Flying40.getInstance();
                modules = f.getModules();
                mCurrentDrill = f;
                break;
            case "Lap":
                Lap l = Lap.getInstance();
                modules = l.getModules();
                mCurrentDrill = l;
                break;
        }

        mAdapter = new LaserAdapter(modules);
        mLaserRecyclerView.setAdapter(mAdapter);

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        Activity a;

        if (context instanceof Activity){

            a = (Activity) context;
            // This makes sure that the container activity has implemented
            // the callback interface. If not, it throws an exception
            try {
                mCallback = (AutoConnectEventSelected) a;
            } catch (ClassCastException e) {
                throw new ClassCastException(a.toString()
                        + " must implement OnHeadlineSelectedListener");
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            System.out.println(requestCode);
            if (resultCode == Activity.RESULT_CANCELED) {
                //Bluetooth not enabled.
                getActivity().finish();
                return;
            } else {
                return;

            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}
</code>```

BLE auto connect Scanner class:

```<code>public class AutoConnectBLE {

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothLeScanner mBluetoothLEScanner;
    private ScanSettings mSettings;
    private Context mContext;
    private long mStartScanTimeStamp;
    private long connectTimeStamp = 0L;

    private class laserCallBack extends ScanCallback {

        private Drill drill;
        private AutoConnectFragment.LaserAdapter mAdapter;
        private int position;
        private boolean isConnected = false;
        private long scanTimeStamp = 0L;
        private long mElapsedTimeScanning;
        private String mHex;
        private long mLaserTime;
        private String mBeefMessage;
        private String name;
        private ImageView mConnectIcon;
        private ProgressBar mProgressBar;

        public laserCallBack(View view, Drill drill,String name, AutoConnectFragment.LaserAdapter mAdapter, int position) {
            super();
            this.drill = drill;
            this.mAdapter = mAdapter;
            this.position = position;
            this.name = name;

            // grab views
            mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
            mConnectIcon = (ImageView) view.findViewById(R.id.connect_icon);

        }

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            // grab a timestamp of when the scan starts
            scanTimeStamp = SystemClock.uptimeMillis();

            // if its been 3 seconds, without scanning then stop
            mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
            // if the elapsed time is 3 seconds, then stop the scan
            if (mElapsedTimeScanning >= 3) {

                if (mConnectIcon.getVisibility() != View.VISIBLE) {

                    // if nothing was found, stop the circular progress bar and place the lightning bolt
                    mProgressBar.setVisibility(View.GONE);
                    mConnectIcon.setImageResource(R.drawable.ic_flash);
                    mConnectIcon.setVisibility(View.VISIBLE);
                    // clear out laser
                    ArrayList<Module> m = drill.getModules();
                    m.get(position).setMACaddress(null);

                }

                mAdapter.notifyDataSetChanged();
                isConnected = false;
                mBluetoothLEScanner.stopScan(this);
            } else {
                // grabbing important data from byte record
                mHex = ConversionHelper
                        .bytesToHex(result.getScanRecord().getBytes());
                mLaserTime = ConversionHelper.
                        hex2decimal(mHex.substring(24, 32));
                mBeefMessage = mHex.substring(32, 36);

            /* if there is no connection yet, and the beef message is preset,
            and the laser time < 3 seconds,
            and its atleast 3 seconds since another laser has advertised,
            accept this new scan record as a potential new laser
            */
                System.out.println("CONNECTION DELAY:" + (scanTimeStamp - connectTimeStamp));
                if (!isConnected
                        && ConversionHelper.hex2decimal(mBeefMessage) == 48879
                        && mLaserTime < 3000
                        && scanTimeStamp - connectTimeStamp > 3000) {
                    // set isConnected to true
                    isConnected = true;

                    // grab second timestamp - used so that people can't connect the same MAC for 2 lasers
                    connectTimeStamp = SystemClock.uptimeMillis();
                    System.out.println("CONNECT TIME STAMP" + connectTimeStamp);
                    // set the MAC address of the laser
                    drill.setMAC(name, result.getDevice().getAddress());
                    mAdapter.setCurrentMAC(result.getDevice().getAddress());
                    mAdapter.notifyDataSetChanged();

                    // check to see if this laser is connected to another position

                    // if the device finds a viable laser, replace the circular progress bar with a checkmark
                    mProgressBar.setVisibility(View.GONE);
                    mConnectIcon.setImageResource(R.drawable.ic_connected);
                    mConnectIcon.setVisibility(View.VISIBLE);

                    // notify the user that the start laser has been connected
                    Toast message = Toast.makeText(mContext, name + " Connected!", Toast.LENGTH_SHORT);
                    message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                    message.show();

                    isConnected = false;
                    mBluetoothLEScanner.stopScan(this);

                }

            }
        }

    }

    public AutoConnectBLE(Context context) {

        // grab context
        mContext = context;

        // grab BLE scanner
        mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        mBluetoothLEScanner = mBluetoothAdapter.getBluetoothLeScanner();

        // set settings to LOW LATENCY
        mSettings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();

    }

    public void scanLaser(View view,Drill drill ,String name, final AutoConnectFragment.LaserAdapter mAdapter, int position) {

        mStartScanTimeStamp = SystemClock.uptimeMillis();
        mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings,new laserCallBack(view, drill, name, mAdapter, position));

    }

//    public void scanRFID(final Drill drill, final String name, final View v, final Context context, final AutoConnectFragment.LaserAdapter mAdapter, final int position) {
//
//        final ScanCallback RFIDCallBack = new ScanCallback() {
//            @Override
//            public void onScanResult(int callbackType, ScanResult result) {
//                super.onScanResult(callbackType, result);
//
//                // grab a timestamp
//                scanTimeStamp = SystemClock.uptimeMillis();
//
//
//                String hex = ConversionHelper
//                        .bytesToHex(result.getScanRecord().getBytes());
//                String RFIDBeefMessage = hex.substring(36, 40);
//                System.out.println(hex);
//
//                // if its been 3 seconds, without connecting then stop
//                mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
//                if (mElapsedTimeScanning == 3) {
//                    ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
//                    if (mConnectIcon.getVisibility() != View.VISIBLE) {
//
//                        // if nothing was found, stop the circular progress bar and place the lightning bolt
//                        ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
//                        mProgressBar.setVisibility(View.GONE);
//                        mConnectIcon.setImageResource(R.drawable.ic_flash);
//                        mConnectIcon.setVisibility(View.VISIBLE);
//
//                    }
//                    System.out.println("STOPPED SCANNING");
//                    mBluetoothLEScanner.stopScan(this);
//                    isConnected = false;
//                }
//
//                // RFID
//                if (!isConnected && RFIDBeefMessage.equals("BEEF")) {
//                    isConnected = true;
//                    mBluetoothLEScanner.stopScan(this);
//
//                    // set the MAC address of the laser
//                    String MACAddress = result.getDevice().getAddress();
//                    drill.setMAC(name, MACAddress);
//                    // notify the user that the start laser has been connected
//
//                    // if the device finds a viable laser, replace the circular progress bar with a checkmark
//                    ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
//                    ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
//                    mProgressBar.setVisibility(View.GONE);
//                    mConnectIcon.setImageResource(R.drawable.ic_connected);
//                    mConnectIcon.setVisibility(View.VISIBLE);
//                    Toast message = Toast.makeText(context, name + " Connected!", Toast.LENGTH_SHORT);
//                    message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
//                    message.show();
//
//                }
//
//            }
//
//        };
//        mStartScanTimeStamp = SystemClock.uptimeMillis();
//        mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings, RFIDCallBack);
//
//
//    }

}
</code>```

答:
Just add a manifest permission for Bluetooth access.

```<code>    <uses-permission android:name="android.permission.BLUETOOTH"/>
</code>```

and add this snippet in your fragment, for run time permission allowance.

```<code>  if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH)
            != PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(((Activity)getContext()),
                new String[]{Manifest.permission.BLUETOOTH}, REQUEST_CODE);
    }
</code>```

The snippet automatically launch an alert for Bluetooth access.

Title: Bluetooth enable intent in fragment

Body:
I've been searching everywhere and I can't find the answer. I'm simply trying to enable bluetooth in my fragment. I added the following to lines to my OnResume() callback:

        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
    }

for some reason, the output just keeps saying, Activity.onPostResume() called over and over again and it actually locks out my UI. I was wondering if there's a solution?

Edit: AutoConnectFragment:

public class AutoConnectFragment extends Fragment {

    private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
    private Toolbar mToolbar;
    private CollapsingToolbarLayout collapsingToolbar;
    private ImageView mBackArrow;
    private Button mStartTiming;
    private RecyclerView mLaserRecyclerView;
    private LaserAdapter mAdapter;
    private String mCurrentEvent;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothLeScanner mBluetoothLeScanner;
    private AutoConnectBLE mScanner;
    private static boolean mIsLasersConnected;
    private Drill mCurrentDrill;
    private AutoConnectEventSelected mCallback;
    private static final int REQUEST_ENABLE_BT = 3;
    private static final int REQUEST_CODE_LOCATION = 42;
    private boolean permissionChecked = false;

    // Container Activity must implement this interface
    public interface AutoConnectEventSelected {
        public void onAutoConnectEventSelected(String event);
    }

    // private nested custom view holder class
    public class LaserHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private TextView mLaserName;
        private Module mModule;
        private ImageView mConnectIcon;
        private ProgressBar mProgressBar;

        public LaserHolder(LayoutInflater inflater, ViewGroup parent) {
            super(inflater.inflate(R.layout.list_item_laser, parent, false));
            itemView.setOnClickListener(this);

            // grab the font
            Typeface mont_reg = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");

            // grab the user name and change the font
            mLaserName = (TextView) itemView.findViewById(R.id.laser_name);
            mLaserName.setTypeface(mont_reg);

            // grab the progress bar
            mProgressBar = (ProgressBar) itemView.findViewById(R.id.progress_bar);

            //grab the connect icon
            mConnectIcon = (ImageView) itemView.findViewById(R.id.connect_icon);
        }

        public void bind(Module module) {

            // set the text view to the module name
            mModule = module;
            mLaserName.setText(module.getName());
        }

        // if the user clicks on the connect laser
        @Override
        public void onClick(View v) {
            if (mModule.getName().equals("RFID")) {
                mProgressBar.setVisibility(View.VISIBLE);
                mConnectIcon.setVisibility(View.GONE);
//                mScanner.scanRFID(mCurrentDrill, mModule.getName(), v, getContext(), mAdapter,getAdapterPosition());
            } else {
                mProgressBar.setVisibility(View.VISIBLE);
                mConnectIcon.setVisibility(View.GONE);
                mScanner.scanLaser(v,mCurrentDrill, mModule.getName(),mAdapter,getAdapterPosition());
            }

            mAdapter.setCurrentPosition(getAdapterPosition());

        }
    }

    public class LaserAdapter extends RecyclerView.Adapter<LaserHolder> {
        private List<Module> mModules;
        private String mCurrentMAC;
        private int mCurrentPosition;

        public LaserAdapter(List<Module> modules) {
            mModules = modules;
        }

        @Override
        public LaserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
            return new LaserHolder(layoutInflater, parent);
        }

        @Override
        public void onBindViewHolder(LaserHolder holder, int position) {
            Module module = mModules.get(position);
            /* if a laser is already connected and
            the user tries to connect the same laser to another position,
            unconnect the previous connection
             */
            if (!TextUtils.isEmpty(module.getMACaddress())){
                if ( module.getMACaddress().equals(mCurrentMAC) && position != mCurrentPosition){
                    holder.mConnectIcon.setImageResource(R.drawable.ic_flash);
                    module.setMACaddress(null);
                }
            }

            checkAllLasersConnected(mModules);

            holder.bind(module);
        }

        @Override
        public int getItemCount() {
            return mModules.size();
        }

        public String getCurrentMAC() {
            return mCurrentMAC;
        }

        public void setCurrentMAC(String currentMAC) {
            mCurrentMAC = currentMAC;
        }

        public int getCurrentPosition() {
            return mCurrentPosition;
        }

        public void setCurrentPosition(int currentPosition) {
            mCurrentPosition = currentPosition;
        }

        public void checkAllLasersConnected(List<Module> modules){

            int numLasersConnected = 0;
            // checking to see if all of the lasers are connected
            for (int i = 0; i < modules.size(); i++) {
                System.out.println("Name: " + modules.get(i).getName() + " MAC :" + modules.get(i).getMACaddress());
                if (modules.get(i).getMACaddress() == null) {
                    numLasersConnected++;
                }
            }

            // if all of the lasers are connected, enabled the start timing button
            if (numLasersConnected == 0) {
                mStartTiming.setEnabled(true);
            } else {
                mStartTiming.setEnabled(false);
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        // inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_autoconnect, container, false);

        // grab the recyclerview and set its layout manager
        mLaserRecyclerView = (RecyclerView) view.findViewById(R.id.list_recycler_view);
        mLaserRecyclerView.setLayoutManager((new LinearLayoutManager(getActivity())));

        // update the UI ( recycler view )
        updateUI(savedInstanceState);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // grab the views
        collapsingToolbar = (CollapsingToolbarLayout) view.findViewById(R.id.collapsing_toolbar);
        mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
        mBackArrow = (ImageView) view.findViewById(R.id.back_arrow);
        mStartTiming = (Button) view.findViewById(R.id.start_timing_button);

        // disable the startTiming button until all of the lasers are connected
        mStartTiming.setEnabled(false);

        //Set toolbar title
        collapsingToolbar.setTitle(getArguments().getString("Event") + " Connect");
        // setting the text alignment
        collapsingToolbar.setExpandedTitleColor(Color.WHITE);
        collapsingToolbar.setCollapsedTitleGravity(Gravity.CENTER_HORIZONTAL);
        collapsingToolbar.setCollapsedTitleTextColor(Color.WHITE);
        collapsingToolbar.setExpandedTitleGravity(Gravity.CENTER_HORIZONTAL);

        // set the font
        Typeface mont_bold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Bold.ttf");
        Typeface mont_regular = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Montserrat-Regular.ttf");
        collapsingToolbar.setExpandedTitleTypeface(mont_bold);
        collapsingToolbar.setCollapsedTitleTypeface(mont_regular);

        // set background color to dark grey
        mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));

        // set up bluetooth
        mScanner = new AutoConnectBLE(getContext());

        // collapsing tool bar effect ( explained in main activtiy)
        AppBarLayout mAppBarLayout = (AppBarLayout) view.findViewById(R.id.app_bar_layout);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int i) {
                //measuring for alpha
                int toolBarHeight = mToolbar.getMeasuredHeight();
                int appBarHeight = appBarLayout.getMeasuredHeight();
                Float f = ((((float) appBarHeight - toolBarHeight) + i) / ((float) appBarHeight - toolBarHeight)) * 255;
                if (Math.round(f) == 0) {
                    mToolbar.setBackgroundColor(getResources().getColor(R.color.darkGrey));
                } else {
                    mToolbar.getBackground().setAlpha(0);
                }

            }
        });

        // if user clicks on the back arrow, go back to testing page
        mBackArrow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Fragment frag = new TestingFragment();
                FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
                ft.replace(R.id.container, frag, frag.getTag());
                ft.addToBackStack(null);
                ft.commit();
            }
        });

        // if the user clicks on the start timing, goto the timing page
        mStartTiming.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCallback.onAutoConnectEventSelected(getArguments().getString("Event"));
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        System.out.println("ON RESUME CALLED");

        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            System.out.println("INTENT CALLED");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            getActivity().startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
//
//        if (!getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
//            Toast.makeText(getActivity(), "No LE Support, Please install this app on another phone", Toast.LENGTH_SHORT).show();
//            return;
//        }

    }

    private void updateUI(Bundle savedInstanceState) {

        List<Module> modules = null;
        // check to see which event the user chose and grab the laser array list
        switch (getArguments().getString("Event")) {
            case "Dash":
                Dash dash = Dash.getInstance();
                modules = dash.getModules();
                mCurrentDrill = dash;
                break;
            case "ProAgility":
                ProAgility pa = ProAgility.getInstance();
                modules = pa.getModules();
                mCurrentDrill = pa;
                break;
            case "DashSplit":
                DashSplit ds = DashSplit.getInstance();
                modules = ds.getModules();
                mCurrentDrill = ds;
                break;
            case "Flying40":
                Flying40 f = Flying40.getInstance();
                modules = f.getModules();
                mCurrentDrill = f;
                break;
            case "Lap":
                Lap l = Lap.getInstance();
                modules = l.getModules();
                mCurrentDrill = l;
                break;
        }

        mAdapter = new LaserAdapter(modules);
        mLaserRecyclerView.setAdapter(mAdapter);

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        Activity a;

        if (context instanceof Activity){

            a = (Activity) context;
            // This makes sure that the container activity has implemented
            // the callback interface. If not, it throws an exception
            try {
                mCallback = (AutoConnectEventSelected) a;
            } catch (ClassCastException e) {
                throw new ClassCastException(a.toString()
                        + " must implement OnHeadlineSelectedListener");
            }
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            System.out.println(requestCode);
            if (resultCode == Activity.RESULT_CANCELED) {
                //Bluetooth not enabled.
                getActivity().finish();
                return;
            } else {
                return;

            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

}

BLE auto connect Scanner class:

public class AutoConnectBLE {

    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothManager mBluetoothManager;
    private BluetoothLeScanner mBluetoothLEScanner;
    private ScanSettings mSettings;
    private Context mContext;
    private long mStartScanTimeStamp;
    private long connectTimeStamp = 0L;

    private class laserCallBack extends ScanCallback {

        private Drill drill;
        private AutoConnectFragment.LaserAdapter mAdapter;
        private int position;
        private boolean isConnected = false;
        private long scanTimeStamp = 0L;
        private long mElapsedTimeScanning;
        private String mHex;
        private long mLaserTime;
        private String mBeefMessage;
        private String name;
        private ImageView mConnectIcon;
        private ProgressBar mProgressBar;

        public laserCallBack(View view, Drill drill,String name, AutoConnectFragment.LaserAdapter mAdapter, int position) {
            super();
            this.drill = drill;
            this.mAdapter = mAdapter;
            this.position = position;
            this.name = name;

            // grab views
            mProgressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
            mConnectIcon = (ImageView) view.findViewById(R.id.connect_icon);

        }

        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);

            // grab a timestamp of when the scan starts
            scanTimeStamp = SystemClock.uptimeMillis();

            // if its been 3 seconds, without scanning then stop
            mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
            // if the elapsed time is 3 seconds, then stop the scan
            if (mElapsedTimeScanning >= 3) {

                if (mConnectIcon.getVisibility() != View.VISIBLE) {

                    // if nothing was found, stop the circular progress bar and place the lightning bolt
                    mProgressBar.setVisibility(View.GONE);
                    mConnectIcon.setImageResource(R.drawable.ic_flash);
                    mConnectIcon.setVisibility(View.VISIBLE);
                    // clear out laser
                    ArrayList<Module> m = drill.getModules();
                    m.get(position).setMACaddress(null);

                }

                mAdapter.notifyDataSetChanged();
                isConnected = false;
                mBluetoothLEScanner.stopScan(this);
            } else {
                // grabbing important data from byte record
                mHex = ConversionHelper
                        .bytesToHex(result.getScanRecord().getBytes());
                mLaserTime = ConversionHelper.
                        hex2decimal(mHex.substring(24, 32));
                mBeefMessage = mHex.substring(32, 36);

            /* if there is no connection yet, and the beef message is preset,
            and the laser time < 3 seconds,
            and its atleast 3 seconds since another laser has advertised,
            accept this new scan record as a potential new laser
            */
                System.out.println("CONNECTION DELAY:" + (scanTimeStamp - connectTimeStamp));
                if (!isConnected
                        && ConversionHelper.hex2decimal(mBeefMessage) == 48879
                        && mLaserTime < 3000
                        && scanTimeStamp - connectTimeStamp > 3000) {
                    // set isConnected to true
                    isConnected = true;

                    // grab second timestamp - used so that people can't connect the same MAC for 2 lasers
                    connectTimeStamp = SystemClock.uptimeMillis();
                    System.out.println("CONNECT TIME STAMP" + connectTimeStamp);
                    // set the MAC address of the laser
                    drill.setMAC(name, result.getDevice().getAddress());
                    mAdapter.setCurrentMAC(result.getDevice().getAddress());
                    mAdapter.notifyDataSetChanged();

                    // check to see if this laser is connected to another position

                    // if the device finds a viable laser, replace the circular progress bar with a checkmark
                    mProgressBar.setVisibility(View.GONE);
                    mConnectIcon.setImageResource(R.drawable.ic_connected);
                    mConnectIcon.setVisibility(View.VISIBLE);

                    // notify the user that the start laser has been connected
                    Toast message = Toast.makeText(mContext, name + " Connected!", Toast.LENGTH_SHORT);
                    message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                    message.show();

                    isConnected = false;
                    mBluetoothLEScanner.stopScan(this);

                }

            }
        }

    }

    public AutoConnectBLE(Context context) {

        // grab context
        mContext = context;

        // grab BLE scanner
        mBluetoothManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        mBluetoothLEScanner = mBluetoothAdapter.getBluetoothLeScanner();

        // set settings to LOW LATENCY
        mSettings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .build();

    }

    public void scanLaser(View view,Drill drill ,String name, final AutoConnectFragment.LaserAdapter mAdapter, int position) {

        mStartScanTimeStamp = SystemClock.uptimeMillis();
        mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings,new laserCallBack(view, drill, name, mAdapter, position));

    }

//    public void scanRFID(final Drill drill, final String name, final View v, final Context context, final AutoConnectFragment.LaserAdapter mAdapter, final int position) {
//
//        final ScanCallback RFIDCallBack = new ScanCallback() {
//            @Override
//            public void onScanResult(int callbackType, ScanResult result) {
//                super.onScanResult(callbackType, result);
//
//                // grab a timestamp
//                scanTimeStamp = SystemClock.uptimeMillis();
//
//
//                String hex = ConversionHelper
//                        .bytesToHex(result.getScanRecord().getBytes());
//                String RFIDBeefMessage = hex.substring(36, 40);
//                System.out.println(hex);
//
//                // if its been 3 seconds, without connecting then stop
//                mElapsedTimeScanning = (scanTimeStamp - mStartScanTimeStamp) / 1000;
//                if (mElapsedTimeScanning == 3) {
//                    ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
//                    if (mConnectIcon.getVisibility() != View.VISIBLE) {
//
//                        // if nothing was found, stop the circular progress bar and place the lightning bolt
//                        ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
//                        mProgressBar.setVisibility(View.GONE);
//                        mConnectIcon.setImageResource(R.drawable.ic_flash);
//                        mConnectIcon.setVisibility(View.VISIBLE);
//
//                    }
//                    System.out.println("STOPPED SCANNING");
//                    mBluetoothLEScanner.stopScan(this);
//                    isConnected = false;
//                }
//
//                // RFID
//                if (!isConnected && RFIDBeefMessage.equals("BEEF")) {
//                    isConnected = true;
//                    mBluetoothLEScanner.stopScan(this);
//
//                    // set the MAC address of the laser
//                    String MACAddress = result.getDevice().getAddress();
//                    drill.setMAC(name, MACAddress);
//                    // notify the user that the start laser has been connected
//
//                    // if the device finds a viable laser, replace the circular progress bar with a checkmark
//                    ImageView mConnectIcon = (ImageView) v.findViewById(R.id.connect_icon);
//                    ProgressBar mProgressBar = (ProgressBar) v.findViewById(R.id.progress_bar);
//                    mProgressBar.setVisibility(View.GONE);
//                    mConnectIcon.setImageResource(R.drawable.ic_connected);
//                    mConnectIcon.setVisibility(View.VISIBLE);
//                    Toast message = Toast.makeText(context, name + " Connected!", Toast.LENGTH_SHORT);
//                    message.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
//                    message.show();
//
//                }
//
//            }
//
//        };
//        mStartScanTimeStamp = SystemClock.uptimeMillis();
//        mBluetoothLEScanner.startScan(new ArrayList<ScanFilter>(), mSettings, RFIDCallBack);
//
//
//    }

}

Body:
Just add a manifest permission for Bluetooth access.

    <uses-permission android:name="android.permission.BLUETOOTH"/>

and add this snippet in your fragment, for run time permission allowance.

  if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.BLUETOOTH)
            != PackageManager.PERMISSION_GRANTED)
    {
        ActivityCompat.requestPermissions(((Activity)getContext()),
                new String[]{Manifest.permission.BLUETOOTH}, REQUEST_CODE);
    }

The snippet automatically launch an alert for Bluetooth access.


来源: stackexchange

问:
gridview with different data sources in vb.net
Is it possible to bind columns of gridview with different data sources ?
I have two different datasources in my web.config file and i want to select data in one gridview with different datasources .

how can i fill my dataset or datatable for the gridview ?

答:
i think from what you asked
the best way is to merge both in one dataset or datatable then fill the gridview with this new combined object

Note: for very high speed use special objects you develop to catch data and return the number of rows so you do not make it very slow using List grow process

Better Example:

```<code>CREATE TABLE [dbo].[NewTable](
    [id]            [smallint] NOT NULL PRIMARY KEY,
    [name]          [nvarchar](50) NOT NULL,
);
CREATE Procedure NewTableGetAll
BEGIN
    SELECT      Count(id) as RowsCount
    FROM        NewTable

    SELECT      *
    FROM        NewTable
END

public class NewTable
{
    private short _id;

    private string _name;

    public short Id
    {
        get { return _id; }
        set { _id = value; }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public void Fill(SqlDataReader reader)
    {
        _id = Convert.ToInt16(reader["id"]);
        _name = Convert.ToString(reader["name"]);
    }
}

Public static class SNewTable{
    Public List<NewTable> GetNewTable(*****************){
        ****************
        ****************
        List<NewTable> myList = null;
        If(reader.Read()){
            myList = new List<NewTable>(Convert.ToInt(reader[“RowsCount”]));
        }

        reader.NextResult();

        while(reader.Read()){
            NewTable obj = new NewTable();
            Obj.Fill(reader);
            myList.Add(obj);
        }

        ****************
        ****************
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i think from what you asked
the best way is to merge both in one dataset or datatable then fill the gridview with this new combined object

Note: for very high speed use special objects you develop to catch data and return the number of rows so you do not make it very slow using List grow process

Better Example:

CREATE TABLE [dbo].[NewTable](
    [id]            [smallint] NOT NULL PRIMARY KEY,
    [name]          [nvarchar](50) NOT NULL,
);
CREATE Procedure NewTableGetAll
BEGIN
    SELECT      Count(id) as RowsCount
    FROM        NewTable

    SELECT      *
    FROM        NewTable
END

public class NewTable
{
    private short _id;

    private string _name;

    public short Id
    {
        get { return _id; }
        set { _id = value; }
    }

    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    public void Fill(SqlDataReader reader)
    {
        _id = Convert.ToInt16(reader["id"]);
        _name = Convert.ToString(reader["name"]);
    }
}

Public static class SNewTable{
    Public List<NewTable> GetNewTable(*****************){
        ****************
        ****************
        List<NewTable> myList = null;
        If(reader.Read()){
            myList = new List<NewTable>(Convert.ToInt(reader[“RowsCount”]));
        }

        reader.NextResult();

        while(reader.Read()){
            NewTable obj = new NewTable();
            Obj.Fill(reader);
            myList.Add(obj);
        }

        ****************
        ****************
    }
}


问:
how to fetch data in view or display it in a page in codeigniter
this is my profile.php code i want to display it in webpage

```<code><!-- Bridegroom Profile Details -->
<div class="w3ls-list">

    <div class="container">

                <h2>Bridegroom Profile Details</h2>

    <div class="col-md-9 profiles-list-agileits">
        <div class="single_w3_profile">
            <div class="agileits_profile_image">
    <?php foreach ($profile_details as $row) { ?>
                                <img src="<?php echo $row['upload'];?>" alt="profile image" />
                                           <?php } ?>

            </div>

            <div class="clearfix"></div>
        </div>

        <div class="profile_w3layouts_details">

            <div class="agileits_aboutme">
                <h4>Profile</h4>
                <h5>Personal Details:</h5>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Profile for : </label>
                    <div class="col-sm-9 w3_details">

                                               <!--Brother-->
                    </div>
                    <div class="clearfix"> </div>
                </div>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Name : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Gender : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Dob : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Religion : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                </div>
                                    <div class="form_but1">
                    <label class="col-sm-3 control-label1" for="Relation">Mobile : </label>
                    <div class="col-sm-9 w3_details">

                    </div>
                    <div class="clearfix"> </div>
                                    </div>

                            </div>

        </div>

    </div>
           </div>

    </div>
</code>```

this is my controller home.php
please help to how to diplay this profile

```<code> public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

     $this->load->view('index',$data);
 }
</code>```

答:
Since you already know to do this

```<code><?php foreach ($profile_details as $row) { ?>
      <img src="<?php echo $row['upload'];?>" alt="profile image" />
<?php } ?>
</code>```

I think what you want to do is like below?

```<code> <div class="form_but1">
    <label class="col-sm-3 control-label1" for="Relation">Name : </label>
                    <div class="col-sm-9 w3_details">
                         <?php echo $row['Name'];?> // or the name of the column
                    </div>
     <div class="clearfix"> </div>
  </div>
</code>```

Added

Put a print_r($data) after your database query and check if you actually getting a result.

```<code>public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

    print_r($data);

     $this->load->view('index',$data);

 }
</code>```

Body:
this is my profile.php code i want to display it in webpage

Bridegroom Profile Details

    <?php foreach ($profile_details as $row) { ?>
                                <img src="<?php echo $row['upload'];?>" alt="profile image" />
                                           <?php } ?>

Profile

Personal Details:

                    Profile for :

                    Name :

                    Gender :

                    Dob :

                    Religion :

                    Mobile :

this is my controller home.php
please help to how to diplay this profile

 public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

     $this->load->view('index',$data);
 }

Body:
Since you already know to do this

<?php foreach ($profile_details as $row) { ?>
      <img src="<?php echo $row['upload'];?>" alt="profile image" />
<?php } ?>

I think what you want to do is like below?

 <div class="form_but1">
    <label class="col-sm-3 control-label1" for="Relation">Name : </label>
                    <div class="col-sm-9 w3_details">
                         <?php echo $row['Name'];?> // or the name of the column
                    </div>
     <div class="clearfix"> </div>
  </div>

Added

Put a print_r($data) after your database query and check if you actually getting a result.

public function profile($param1='')
 {

     //$data['user_detail'] = $this->db->get_where('admin',array('id'=> $this->session->userdata('admin_id')))->result_array();
     $data['page_name']='profile';
     $data['profile_details']=$this->db->get_where('profile',array('id' => $param1))->result_array();

    print_r($data);

     $this->load->view('index',$data);

 }


问:
I don't know why this while loop doesn't stop iterating
It's a challenge on codewars.com, but I can't figure out why this while loop doesn't work

def digital_root(n):
    # Creating variable combine to have the sum
    combine = 0
    # as long as n is more than two numbers.
    while n > 10:
        # converting n to string to iterate
        for i in str(n):
            # getting the sum each element in n
            combine += int(i)
        # reset n to be equal to the combined result
        n = combine
    return combine
```

also, any solutions will be appreciated, here is the link to the challenge
https://www.codewars.com/kata/sum-of-digits-slash-digital-root

答:
interesting;)</p>

```<code>def digital_root(n):
    return n if n < 10 else digital_root(sum(int(i) for i in str(n)))
</code>```

Body:
It's a challenge on codewars.com, but I can't figure out why this while loop doesn't work

def digital_root(n):
    # Creating variable combine to have the sum
    combine = 0
    # as long as n is more than two numbers.
    while n > 10:
        # converting n to string to iterate
        for i in str(n):
            # getting the sum each element in n
            combine += int(i)
        # reset n to be equal to the combined result
        n = combine
    return combine

also, any solutions will be appreciated, here is the link to the challenge
https://www.codewars.com/kata/sum-of-digits-slash-digital-root

Body:
interesting;)

def digital_root(n):
    return n if n < 10 else digital_root(sum(int(i) for i in str(n)))


问:
org.json.JSONException: Unterminated object at character on Android
I parse the JSON String and face the error

org.json.JSONException: Unterminated object at character 25

my JSON is retrieved from Facebook

```<code>{Response:  responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[{"venue":{"id":108242939200809,"zip":"","longitude":11.4,"latitude":62.5833,"street":""},"location":"Røros, Norway","eid":1473462312875161,"pic_big":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yn\/r\/5uwzdFmIMKQ.png","pic_small":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yy\/r\/XcB-JGXohjk.png","description":"Test","name":"Test"},{"venue":{"id":105818232792451,"zip":"","longitude":108.217,"latitude":16.0167,"street":""},"location":"Hòa Vang","eid":1425682134338854,"pic_big":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yn\/r\/5uwzdFmIMKQ.png","pic_small":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yy\/r\/XcB-JGXohjk.png","description":"test","name":"Test"}]}}, error: null, isFromCache:false}
</code>```

My JSON parser is

```<code>public static JSONArray parse(Response response) throws JSONException{
        JSONArray jsonArray=new JSONArray(response.toString());
        return jsonArray;
    }
</code>```

Please help me. Thank you very much.

答:
```<code>try {
            JSONObject jsonData = response.getJSONObject();
            JSONArray jsonArray = jsonData.getJSONArray("data");

            Log.e("MainActivity ", "jsondata   -->  " + jsonArray.toString(2));
            Log.e("MainActivity ", "jsonArray.length()->  " + jsonArray.length());

            likesPojos.clear();
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject json = jsonArray.getJSONObject(i);

                Log.e("MainActivity ", "message  -->  " + json.getString("name"));
                Log.e("MainActivity ", "id  -->  " + json.getString("id"));

                LikesPojo likesPojo = new LikesPojo();
                likesPojo.setId(json.getString("id"));
                likesPojo.setName(json.getString("name"));
                likesPojos.add(likesPojo);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
</code>```

Body:
I parse the JSON String and face the error

org.json.JSONException: Unterminated object at character 25

my JSON is retrieved from Facebook

{Response:  responseCode: 200, graphObject: GraphObject{graphObjectClass=GraphObject, state={"data":[{"venue":{"id":108242939200809,"zip":"","longitude":11.4,"latitude":62.5833,"street":""},"location":"Røros, Norway","eid":1473462312875161,"pic_big":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yn\/r\/5uwzdFmIMKQ.png","pic_small":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yy\/r\/XcB-JGXohjk.png","description":"Test","name":"Test"},{"venue":{"id":105818232792451,"zip":"","longitude":108.217,"latitude":16.0167,"street":""},"location":"Hòa Vang","eid":1425682134338854,"pic_big":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yn\/r\/5uwzdFmIMKQ.png","pic_small":"https:\/\/fbcdn-profile-a.akamaihd.net\/static-ak\/rsrc.php\/v2\/yy\/r\/XcB-JGXohjk.png","description":"test","name":"Test"}]}}, error: null, isFromCache:false}

My JSON parser is

public static JSONArray parse(Response response) throws JSONException{
        JSONArray jsonArray=new JSONArray(response.toString());
        return jsonArray;
    }

Please help me. Thank you very much.


问:
angular 2 select set selected item
I have a select in Angular 2

```<code><select [(ngModel)]="selectedItem">
 <option [ngValue]="'<empty>'"></option>
 <option *ngFor="let e of range" [ngValue]="e.value">{{e.display}}</option>
</select>
</code>```

Note that there is an "empty" option at the top. Every time the user selects an option I want to process the selected item and then set the first, empty option as selected. I've tried adding an (change) and ngModelChange handler and can set selectedItem to whatever value I want, but that doesn't change the displayed selected option.

答:
```<code><select [(ngModel)]="selectedItem" (ngModelChange)="processSelectedItem();selectedItem = range[0]">
</code>```

You can also move selectedItem = range[0] into processSelectedItem() { ... }

Title: angular 2 select set selected item

Body:
I have a select in Angular 2

<select [(ngModel)]="selectedItem">
 <option [ngValue]="'<empty>'"></option>
 <option *ngFor="let e of range" [ngValue]="e.value">{{e.display}}</option>
</select>

Note that there is an "empty" option at the top. Every time the user selects an option I want to process the selected item and then set the first, empty option as selected. I've tried adding an (change) and ngModelChange handler and can set selectedItem to whatever value I want, but that doesn't change the displayed selected option.

Body:
<select [(ngModel)]="selectedItem" (ngModelChange)="processSelectedItem();selectedItem = range[0]">

You can also move selectedItem = range[0] into processSelectedItem() { ... }


问:
nonce token after ajax response and hash problems using ajax jquery type json
i have login with my own code at php, now i dont so good at jquery ajax and so on,
my login using ajax jquery type json , i take all vals and post them to server side php which check all details , and response answer via the same jquery ajax .

the problem is i added nonce token that maded in php to the login form and every time after user try to login the nonce change , the problem is only when i refresh the login page the nonce changed to the good nonce else its will keep the same nonce token and will send with the post not the updated one because the ajax didnt refresh the page after login .

So the question is how i trigger the ajax to refresh the nonce token after every response ?
the nonce token is write in php.

and more thing about the hash nonce token , its make that hash string sometime:

asdaskjn34kj+sdf/sd=

now the ajax jquery auto remove the '+' from the hash string so its send wrong token in the POST,
here my hash function :

```<code>public static function RandomBytes($count, $printable=FALSE)
    {
        $bytes = '';

    // supress warnings when open_basedir restricts access to /dev/urand
        if(@is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE)
        {
            $bytes = fread($hRand, $count);
            fclose($hRand);
        }
    if((strlen($bytes) < $count) && function_exists('mcrypt_create_iv'))
    {
        // Use MCRYPT_RAND on Windows hosts with PHP < 5.3.7, otherwise use MCRYPT_DEV_URANDOM
        // (http://bugs.php.net/55169).
        if ((version_compare(PHP_VERSION, '5.3.7', '<') && strncasecmp(PHP_OS, 'WIN', 3) == 0))
          $bytes = mcrypt_create_iv($count, MCRYPT_RAND);
        else
          $bytes = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
    }
    if((strlen($bytes) < $count) && function_exists('openssl_random_pseudo_bytes'))  // OpenSSL slow on Win
    {
        $bytes = openssl_random_pseudo_bytes($count);
    }
    if ((strlen($bytes) < $count) && @class_exists('COM'))
    {
        // Officially deprecated in Windows 7
        // http://msdn.microsoft.com/en-us/library/aa388182%28v=vs.85%29.aspx
        try
        {
            $CAPI_Util = new COM('CAPICOM.Utilities.1');
            if(is_callable(array($CAPI_Util,'GetRandom')))
            {
                $bytes = $CAPI_Util->GetRandom(16,0);
                $bytes = base64_decode($bytes);
            }
        }
        catch (Exception $ex)
        {
        }
    }
        if (strlen($bytes) < $count)
        {
            // This fallback here based on phpass code
            $bytes = '';
            $random_state = microtime();
            if (function_exists('getmypid'))
                $random_state .= getmypid();

            for ($i = 0; $i < $count; $i += 16) {
                $random_state =
                    md5(microtime() . $random_state);
                $bytes .=
                    pack('H*', md5($random_state));
            }
            $bytes = substr($bytes, 0, $count);
        }

        if ($printable)
            return base64_encode($bytes);
        else
            return $bytes;
    }
</code>```

any one know how to change this function to make the strings without '+' in the hashesh?

答: This was really useful as I had encountered the same problem - I had considered an auto page refresh for the login  but this is a real inconvenience to the user - I also added a block so that the ip and/or user are blocked after 5  failed attempts</p>

Body:
i have login with my own code at php, now i dont so good at jquery ajax and so on,
my login using ajax jquery type json , i take all vals and post them to server side php which check all details , and response answer via the same jquery ajax .

the problem is i added nonce token that maded in php to the login form and every time after user try to login the nonce change , the problem is only when i refresh the login page the nonce changed to the good nonce else its will keep the same nonce token and will send with the post not the updated one because the ajax didnt refresh the page after login .

So the question is how i trigger the ajax to refresh the nonce token after every response ?
the nonce token is write in php.

and more thing about the hash nonce token , its make that hash string sometime:

asdaskjn34kj+sdf/sd=

now the ajax jquery auto remove the '+' from the hash string so its send wrong token in the POST,
here my hash function :

public static function RandomBytes($count, $printable=FALSE)
    {
        $bytes = '';

    // supress warnings when open_basedir restricts access to /dev/urand
        if(@is_readable('/dev/urandom') && ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE)
        {
            $bytes = fread($hRand, $count);
            fclose($hRand);
        }
    if((strlen($bytes) < $count) && function_exists('mcrypt_create_iv'))
    {
        // Use MCRYPT_RAND on Windows hosts with PHP < 5.3.7, otherwise use MCRYPT_DEV_URANDOM
        // (http://bugs.php.net/55169).
        if ((version_compare(PHP_VERSION, '5.3.7', '<') && strncasecmp(PHP_OS, 'WIN', 3) == 0))
          $bytes = mcrypt_create_iv($count, MCRYPT_RAND);
        else
          $bytes = mcrypt_create_iv($count, MCRYPT_DEV_URANDOM);
    }
    if((strlen($bytes) < $count) && function_exists('openssl_random_pseudo_bytes'))  // OpenSSL slow on Win
    {
        $bytes = openssl_random_pseudo_bytes($count);
    }
    if ((strlen($bytes) < $count) && @class_exists('COM'))
    {
        // Officially deprecated in Windows 7
        // http://msdn.microsoft.com/en-us/library/aa388182%28v=vs.85%29.aspx
        try
        {
            $CAPI_Util = new COM('CAPICOM.Utilities.1');
            if(is_callable(array($CAPI_Util,'GetRandom')))
            {
                $bytes = $CAPI_Util->GetRandom(16,0);
                $bytes = base64_decode($bytes);
            }
        }
        catch (Exception $ex)
        {
        }
    }
        if (strlen($bytes) < $count)
        {
            // This fallback here based on phpass code
            $bytes = '';
            $random_state = microtime();
            if (function_exists('getmypid'))
                $random_state .= getmypid();

            for ($i = 0; $i < $count; $i += 16) {
                $random_state =
                    md5(microtime() . $random_state);
                $bytes .=
                    pack('H*', md5($random_state));
            }
            $bytes = substr($bytes, 0, $count);
        }

        if ($printable)
            return base64_encode($bytes);
        else
            return $bytes;
    }

any one know how to change this function to make the strings without '+' in the hashesh?


问:
Ranking in PHP and MySQL
```<code>  `id` int(11) NOT NULL,
  `ip` text NOT NULL,
  `song` text NOT NULL,
  `vote` int(11) NOT NULL
</code>```

I have created a voting system and I would like to print the songs with more votes ... how do I do it? Thank you

答:
If I understand correctly your table contains each single vote.
I also assume that song is unique ID of a song.
If that is so you need to sum the values of vote and divide it to the total votes.</p>

```<code>SELECT song, SUM(vote)/COUNT(*) AS rateing FROM your_table_name GROUP BY song ORDER BY rateing DESC;
</code>```

Title: Ranking in PHP and MySQL

Body:
  `id` int(11) NOT NULL,
  `ip` text NOT NULL,
  `song` text NOT NULL,
  `vote` int(11) NOT NULL

I have created a voting system and I would like to print the songs with more votes ... how do I do it? Thank you

Body:
If I understand correctly your table contains each single vote.
I also assume that song is unique ID of a song.
If that is so you need to sum the values of vote and divide it to the total votes.

SELECT song, SUM(vote)/COUNT(*) AS rateing FROM your_table_name GROUP BY song ORDER BY rateing DESC;


问:
Ionic 2: use NativeStorage in the browser
Ionic 2 has a Native Storage component for iOS and Android:
https://ionicframework.com/docs/v2/native/nativestorage/

In the repo's readme (https://github.com/TheCocoaProject/cordova-plugin-nativestorage) is said that there is support for browser environment (it uses the LocalStorage fom the browser).

I tried to use it but when I run my Ionic in browser (ionic serve) the browser outputs something like this:

main.js:224 Native: tried calling NativeStorage.setItem, but Cordova
  is not available. Make sure to include cordova.js or run in a
  device/simulator

In the browser environment the cordova is not injected. This makes senses, as long as the cordova.js only works for integration with the device's API.

Anyone knows if it is possible to use this plugin in the browser?

答:
Ionic / cordova made some changes in the CLI.
The command to run with plugins is now
ionic cordova run browser


问:
How to move app from background to foreground in ionic 2?
Is there any method to move app from background to foreground when a push-notification arrive?

答: you can not do such this by push notification you need something like direct video call or voice call try Voip.  Maybe you find it useful for what you need.


问:
How to add a new table in nopcommerce?
I have a requirement to add a new table in nopCommerce solution.

I am following the article shared at
http://www.lateshtclick.com/blogpost/how-to-add-new-tables-to-nopcommerce
By following the instructions mentioned, I am able to add a new model in Nop.Admin project and it works fine.

But when I tried do the same in Nop.Web project.  I stuck at Step 5.
In Step 5 it says, Open this path ~\Nop.Admin\Infrastructure. Open AutoMapperConfiguration.cs class and write below code for Mapping Model to Entity and Entity to Model.

The problem is, I cannot see any file named AutoMapperConfiguration.cs.
How I can have it? Do I have to create a new file or is there any other class where I can map the model to entity and entity to model.

Any help will be appreciated!

答:
The path for files sometimes changes in each nopCommerce new release. But currently the step 5 you mentioned can be found here. In this case, the file has been renamed to AdminMapperConfiguration.cs

```<code>/src/Presentation/Nop.Web/Areas/Admin/Infrastructure/Mapper
</code>```

Title: How to add a new table in nopcommerce?

Body:
The path for files sometimes changes in each nopCommerce new release. But currently the step 5 you mentioned can be found here. In this case, the file has been renamed to AdminMapperConfiguration.cs

/src/Presentation/Nop.Web/Areas/Admin/Infrastructure/Mapper


问:
Compare two text and find the difference
I am working on AngularJS application i want to compare text and highlight the difference in another div. Below is my code

```<code>$scope.left="one two three";
$scope.right="one two four";

<div>{{diff}}</div>
</code>```

in above context if we compare two scope's left and right we get to know that "three" is extra in $scope.left and "four" is extra in $scope.right . So we need to highlight "three" in red color and "four" in green color so that it will be easy to find the difference.

Is there any plugins or library i can use for this functionality ?

答:
I know a good library jsdiff: https://github.com/kpdecker/jsdiff

A simple example: http://incaseofstairs.com/jsdiff/

Is it what you are looking for?

Body:
I am working on AngularJS application i want to compare text and highlight the difference in another div. Below is my code

$scope.left="one two three";
$scope.right="one two four";

{{diff}}

in above context if we compare two scope's left and right we get to know that "three" is extra in $scope.left and "four" is extra in $scope.right . So we need to highlight "three" in red color and "four" in green color so that it will be easy to find the difference.

Is there any plugins or library i can use for this functionality ?


问:
i can see search icon on my actionbar even though i have not implemented searchquery listener in my fragment android
i can see search icon on my actionbar even though i have not implemented searchquery listener in my fragment android,

Prior to this i have a fragment that holds viewpager in which there are two fragments(FragA and FragB) with list...i have implemented SearchQueryListener and implement OCreateOptionMenu in both FragA and FragB,, on item click of FragA and FragB i want to add another fragment that keeps the detail of item but when i add that new fragment i am able to see the same search icon on topbar..when click on that search icon my app crash because search icon dowsnt belong to this current fragment..
Please help me to resolve how to get this fix.. i want to have Search icon only where i have implemented onCreateOptionMenu method..

Thanks in advance

答:
Use this in your new fragment that you are adding, where "action_search" is the search icon id in menu.xml:</p>

```<code> @Override
 public boolean onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_search).setVisible(false);
    return true;
 }
</code>```

Body:
Use this in your new fragment that you are adding, where "action_search" is the search icon id in menu.xml:

 @Override
 public boolean onPrepareOptionsMenu(Menu menu) {
    menu.findItem(R.id.action_search).setVisible(false);
    return true;
 }


问:
Synchronized block will lock the whole object or the method alone?
I have multiple methods in a class and most of the methods are having critical sections(shared data). So I made those methods as synchronized. Say thread t1 is running one of the synchronized block . At the same time thread t2 can access the other methods critical section ? </p>

```<code>class Sample{

synchronized public void method1(){

}

synchronized public void method2(){

}

synchronized public void method3(){

}

public void method4(){

}

}
</code>```

答:
synchronized is always locking on an object. In case of a synchronized method, the object is this. So basically these two methods do the same:

```<code>synchronized public void method1() {
  // do something
}
</code>```

and

```<code>public void method1() {
  synchronized(this){
    // do something
  }
}
</code>```

As long as one thread has the lock on the lock object, no other thread can lock this object. So in your example, the synchronized methods (one, two and three) can never be executed at the same time. method4 is not synchronized, so it can access the object anytime.

If you want a more fine-grained locking, because method1and method2 should be exclusive and method3and method4 you could use for example something like this:

```<code>class Sample{
  private final Object lock1 = new Object();
  private final Object lock2 = new Object();

  public void method1(){
    synchronized(lock1) {
      // do something
    }
  }
  public void method2(){
    synchronized(lock1) {
      // do something
    }
  }

  public void method3(){
    synchronized(lock2) {
      // do something
    }
  }
  public void method4(){
    synchronized(lock2) {
      // do something
    }
  }
}
</code>```

You can then even use the synchonized(lock) method to just wrap the statements that need to be synchronized, not the whole method:

```<code>public void method() {
  // some code
  synchronized(lock) {
    // code that must be synchronized
  }
  // some other code
}
</code>```

With this approach you can keep the lock duration to a minimum.

Body:
I have multiple methods in a class and most of the methods are having critical sections(shared data). So I made those methods as synchronized. Say thread t1 is running one of the synchronized block . At the same time thread t2 can access the other methods critical section ?

class Sample{

synchronized public void method1(){

}

synchronized public void method2(){

}

synchronized public void method3(){

}

public void method4(){

}

}

Body:
synchronized is always locking on an object. In case of a synchronized method, the object is this. So basically these two methods do the same:

synchronized public void method1() {
  // do something
}

and

public void method1() {
  synchronized(this){
    // do something
  }
}

As long as one thread has the lock on the lock object, no other thread can lock this object. So in your example, the synchronized methods (one, two and three) can never be executed at the same time. method4 is not synchronized, so it can access the object anytime.

If you want a more fine-grained locking, because method1and method2 should be exclusive and method3and method4 you could use for example something like this:

class Sample{
  private final Object lock1 = new Object();
  private final Object lock2 = new Object();

  public void method1(){
    synchronized(lock1) {
      // do something
    }
  }
  public void method2(){
    synchronized(lock1) {
      // do something
    }
  }

  public void method3(){
    synchronized(lock2) {
      // do something
    }
  }
  public void method4(){
    synchronized(lock2) {
      // do something
    }
  }
}

You can then even use the synchonized(lock) method to just wrap the statements that need to be synchronized, not the whole method:

public void method() {
  // some code
  synchronized(lock) {
    // code that must be synchronized
  }
  // some other code
}

With this approach you can keep the lock duration to a minimum.


问:
Inconsisent gap between number and text
I got strange spacing issues. There is number and each text parallel. And there is different spacing between 1, 4, 7 and 'each' text. How can we fix this issue or it can't be fixed. I have not used any spacing and extra css properties.

@import url('https://fonts.googleapis.com/css?family=Spectral');
@import url('https://fonts.googleapis.com/css?family=Open+Sans|Spectral');

.bigger {
  font-size: 40px;
}

p {
  font-family: 'Open Sans', sans-serif;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>
  <span class="bigger">81</span>
  <small>each</small>
</p> <br>
<p>
  <span class="bigger">84</span>
  <small>each</small>
</p> <br>
<p>
  <span class="bigger">87</span>
  <small>each</small>
</p> <br></code>```

答:
Although using a monospace font is a nice workaround, you could solve this with your original font if it has the correct OpenType features.

The difference in the space that a digit occupies is caused by the width of the digit (as opposed to kerning or letter spacing, as suggested in the other answers). The width is proportional — the 1 is narrower than the 4.

But a font can also offer tabular figures, where each digit is of equal width:

You can enable this in CSS with font-feature-settings: 'tnum';. Or to use other OpenType features and take care of browser inconsistencies, see Utility OpenType.

Title: Inconsisent gap between number and text

Body:
I got strange spacing issues. There is number and each text parallel. And there is different spacing between 1, 4, 7 and 'each' text. How can we fix this issue or it can't be fixed. I have not used any spacing and extra css properties.

@import url('https://fonts.googleapis.com/css?family=Spectral');
@import url('https://fonts.googleapis.com/css?family=Open+Sans|Spectral');

.bigger {
  font-size: 40px;
}

p {
  font-family: 'Open Sans', sans-serif;
}

  81
  each

  84
  each

  87
  each


问:
Generate all possible choices of elements each from a distinct set
Suppose that we have k sets each of which contains q elements. I want to generate all possible sets in which we select exactly 1 element from each set. Assume that the sets are represented as a table where each row is a set and its columns are its elements. Also assume that all elements are indexed row-wise like this

Set 1: 1 2 3

Set 2: 4 5 6

Set 3: 7 8 9

The thing is that k,q may vary so I cannot use nested for loops. I work in C++ and this structure is actually a std::vector of std::vector of int, but I am not asking for code here, just an idea on how to do this.

答:
This does the job?</p>

```<code>std::vector<std::vector<int>> v;
for(auto& r : v)
    for(auto i : r)
        // use i
</code>```

Body:
This does the job?

std::vector<std::vector<int>> v;
for(auto& r : v)
    for(auto i : r)
        // use i


问:
How to correctly swap some characters in string
I have a string that represents a date:

```<code>"12.27.1995"
</code>```

I need to swap the month and the day to get:

```<code>"27.12.1995"
</code>```

I did:

```<code>date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]
</code>```

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

答:
Yes. Perhaps like this:</p>

```<code>date = "12.27.1995"
m, d, y = date.split(".")
date = [d, m, y].join(".")
</code>```

Body:
I have a string that represents a date:

"12.27.1995"

I need to swap the month and the day to get:

"27.12.1995"

I did:

date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

Body:
Yes. Perhaps like this:

date = "12.27.1995"
m, d, y = date.split(".")
date = [d, m, y].join(".")


问:
Why doesn't Mercurial Eclipse auto-add files like Subclipse?
What is the use case for this behavior, which has made my work unavailable from one location to the next on a dozen occasions? Why is hg like this? How am I "not in the know"?</p>

答:
Hg behaves like svn in this case: it only tracks the files that were explicitly added with svn add or hg add command.

But eclipse plugins behave differently. Why - you could ask their authors.

ContentLicense: CC BY-SA 2.5


问:
Angular 2 | How to pass a model data into another model
How to pass a model data into another model

For Example i want to inject the model 2 modelUser to model 1 user..

model1.ts

```<code>export class model1{
  constructor(private user: modelUser;){}
}
</code>```

model2.ts

```<code>export class model2{
   constructor(public modelUser: string){}
}
</code>```

答:
Model1.ts

```<code>import { Model2} from './model2'

export class Model1{
  user: Model2
}
</code>```

Model2.ts

```<code>export class Model2{
   id: Number
   name: String
}
</code>```

you can call model 2 from model 1 with something like this

```<code>export class Model1{
  ...
  someFunction(){
     const userDetail = {
       id: user.id
       name: user.name
     }
  }
}
</code>```

Body:
How to pass a model data into another model

For Example i want to inject the model 2 modelUser to model 1 user..

model1.ts

export class model1{
  constructor(private user: modelUser;){}
}

model2.ts

export class model2{
   constructor(public modelUser: string){}
}

Body:
Model1.ts

import { Model2} from './model2'

export class Model1{
  user: Model2
}

Model2.ts

export class Model2{
   id: Number
   name: String
}

you can call model 2 from model 1 with something like this

export class Model1{
  ...
  someFunction(){
     const userDetail = {
       id: user.id
       name: user.name
     }
  }
}


问:
google Cloud spanner java.lang.IllegalArgumentException: Jetty ALPN/NPN has not been properly configured
I am new to the Google cloud Spanner and to explore it I started with documentation provided by google Here. To explore any database we start with data operations and the same I did, I started with writing data to the spanner using simple java application given here https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/spanner/cloud-client/src/main/java/com/example/spanner/SpannerSample.java.
I have made changes in driver class on respective places shown in following code snippet:

```<code> public static void main(String[] args) throws Exception {
            String path = "File_Path";

            SpannerOptions.Builder options = SpannerOptions.newBuilder().setCredentials(GoogleCredentials.fromStream(new FileInputStream(path)));
            options.setProjectId("Project_id");
            Spanner spanner = (options.build()).getService();
            try {
                DatabaseId db = DatabaseId.of("project_id", "spannerInstance", "Database_name");
                DatabaseClient dbClient = spanner.getDatabaseClient(db);
                run(dbClient);
            } finally {
                spanner.closeAsync().get();
            }
            System.out.println("Closed client");
        }
</code>```

Now, When I am trying to execute the code I end up with following error:

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Jetty ALPN/NPN has not been properly configured.
    at io.grpc.netty.GrpcSslContexts.selectApplicationProtocolConfig(GrpcSslContexts.java:174)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:151)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:139)
    at io.grpc.netty.GrpcSslContexts.forClient(GrpcSslContexts.java:109)
    at com.google.cloud.spanner.SpannerOptions$NettyRpcChannelFactory.newSslContext(SpannerOptions.java:283)
    at com.google.cloud.spanner.SpannerOptions$NettyRpcChannelFactory.newChannel(SpannerOptions.java:274)
    at com.google.cloud.spanner.SpannerOptions.createChannel(SpannerOptions.java:253)
    at com.google.cloud.spanner.SpannerOptions.createChannels(SpannerOptions.java:240)
    at com.google.cloud.spanner.SpannerOptions.<init>(SpannerOptions.java:89)
    at com.google.cloud.spanner.SpannerOptions.<init>(SpannerOptions.java:43)
    at com.google.cloud.spanner.SpannerOptions$Builder.build(SpannerOptions.java:180)
</code>```

while searching for this issue I have been suggest to add some dependencies like:

```<code>   compile group: 'org.eclipse.jetty.alpn', name: 'alpn-api', version: '1.1.3.v20160715'
   compile group: 'org.mortbay.jetty.alpn', name: 'jetty-alpn-agent', version: '2.0.6'
   compile group: 'io.grpc', name: 'grpc-all', version: '1.2.0'
   compile group: 'io.netty', name: 'netty-all', version: '4.0.29.Final'
   compile group: 'org.eclipse.jetty.orbit', name: 'javax.servlet', version: '3.0.0.v201112011016'
</code>```

but facing same issue, I am also using Bigquery and other GCP's feature one same working environment and they all are working fine except google-Spanner, any suggestion on this is appreciated.
Thanks.

答:
Please read the comments on the question, @Mairbek Khadikov and my discussion on this conclude the actual reason of the issue. As discussed in comment the actual problem was with another dependencies.
By adding

```<code>configurations {
    compile.exclude module: 'netty-all'
}
</code>```

to the build.gradle file this issue has resolved.

Here is the link of github issue I raised regarding to this error. github issue where I posted exact issue eventually which I got to know and the resolution of that by, '@michaelbausor'.

Body:
I am new to the Google cloud Spanner and to explore it I started with documentation provided by google Here. To explore any database we start with data operations and the same I did, I started with writing data to the spanner using simple java application given here https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/spanner/cloud-client/src/main/java/com/example/spanner/SpannerSample.java.
I have made changes in driver class on respective places shown in following code snippet:

 public static void main(String[] args) throws Exception {
            String path = "File_Path";

            SpannerOptions.Builder options = SpannerOptions.newBuilder().setCredentials(GoogleCredentials.fromStream(new FileInputStream(path)));
            options.setProjectId("Project_id");
            Spanner spanner = (options.build()).getService();
            try {
                DatabaseId db = DatabaseId.of("project_id", "spannerInstance", "Database_name");
                DatabaseClient dbClient = spanner.getDatabaseClient(db);
                run(dbClient);
            } finally {
                spanner.closeAsync().get();
            }
            System.out.println("Closed client");
        }

Now, When I am trying to execute the code I end up with following error:

Exception in thread "main" java.lang.IllegalArgumentException: Jetty ALPN/NPN has not been properly configured.
    at io.grpc.netty.GrpcSslContexts.selectApplicationProtocolConfig(GrpcSslContexts.java:174)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:151)
    at io.grpc.netty.GrpcSslContexts.configure(GrpcSslContexts.java:139)
    at io.grpc.netty.GrpcSslContexts.forClient(GrpcSslContexts.java:109)
    at com.google.cloud.spanner.SpannerOptions$NettyRpcChannelFactory.newSslContext(SpannerOptions.java:283)
    at com.google.cloud.spanner.SpannerOptions$NettyRpcChannelFactory.newChannel(SpannerOptions.java:274)
    at com.google.cloud.spanner.SpannerOptions.createChannel(SpannerOptions.java:253)
    at com.google.cloud.spanner.SpannerOptions.createChannels(SpannerOptions.java:240)
    at com.google.cloud.spanner.SpannerOptions.<init>(SpannerOptions.java:89)
    at com.google.cloud.spanner.SpannerOptions.<init>(SpannerOptions.java:43)
    at com.google.cloud.spanner.SpannerOptions$Builder.build(SpannerOptions.java:180)

while searching for this issue I have been suggest to add some dependencies like:

   compile group: 'org.eclipse.jetty.alpn', name: 'alpn-api', version: '1.1.3.v20160715'
   compile group: 'org.mortbay.jetty.alpn', name: 'jetty-alpn-agent', version: '2.0.6'
   compile group: 'io.grpc', name: 'grpc-all', version: '1.2.0'
   compile group: 'io.netty', name: 'netty-all', version: '4.0.29.Final'
   compile group: 'org.eclipse.jetty.orbit', name: 'javax.servlet', version: '3.0.0.v201112011016'

but facing same issue, I am also using Bigquery and other GCP's feature one same working environment and they all are working fine except google-Spanner, any suggestion on this is appreciated.
Thanks.

Body:
Please read the comments on the question, @Mairbek Khadikov and my discussion on this conclude the actual reason of the issue. As discussed in comment the actual problem was with another dependencies.
By adding

configurations {
    compile.exclude module: 'netty-all'
}

to the build.gradle file this issue has resolved.

Here is the link of github issue I raised regarding to this error. github issue where I posted exact issue eventually which I got to know and the resolution of that by, '@michaelbausor'.


问:
Detecting near-by phone numbers
Trying to figure out some sort of method in which it would be possible to detect nearby phone numbers e.g. within a private premises.

My only lead so far is to build a mini mobile base station that would let phones connect to it - even then my theory for this has many holes and blanks.

The above may be completely off or possibly I may be on to something, either way if someone could give me a rough idea of what direction to take it in that would be much appreciated - I do not require any kind of code as I would much rather figure it out myself via a finger pointed in the right direction.

Even if you do not have any solid answers but some tips that could possibly help me piece this together, that'd be great.

答:
After a lot of searching, I came across something called an IMSI-catcher, which is a telephone eavesdropping device used for intercepting mobile phone traffic and tracking location data of mobile phone users. Now, this does not give the MSISDN (the phone number) but does give the unique IMSI number of the user, so maybe that could help.

Ref: https://en.wikipedia.org/wiki/IMSI-catcher

Also, accroding to this article (https://en.wikipedia.org/wiki/Talk%3AIMSI-catcher), it is not possible to get the MSISDN with this method since mobile phones send the IMSI when connecting to towers which internally is converted by the provider to the mobile number (MSISDN).

Title: Detecting near-by phone numbers


问:
How can I Connect orientDB to angularJS web application
I need to connect orientDB with my angularJS login web application.
after log in user allowed to iput some data to web application and those data also need to be stored in the orient DB data base .
So i need to connect database with my angularJS web application and to use database to store and retrieve data, </p>

答:
This is a sample Angular2 service to connect to OrientDB

```<code>import {Injectable} from "@angular/core";
import {Headers, Http} from '@angular/http';

@Injectable()
export class OrientService {

  url = "http://localhost:2480/command/yourDbName/"
  username = "admin";
  password = "admin";

  constructor(private http: Http) {
  }

  command(statement: string, success: (data: any) => void, error: (err: any) => void): void {
    var url = this.url + "sql/-/-1"
    var headers = new Headers();
    headers.append("Authorization", "Basic " + btoa(this.username + ":" +     this.password));

    this.http.post(url,
      JSON.stringify({"command": statement}),
      {headers: headers})
      .toPromise()
      .then(success)
      .catch(error);
  }
}
</code>```

Then you can use it as follows:

```<code> this.orientService.command(
       "SELECT FROM V",
       (res) => {
         let body = res.json();
         ...
       },
       (e) => {
         console.log(e)
       });
</code>```

Here you can find a full example: https://github.com/luigidellaquila/geospatial-demo/tree/geeconprague2016

Consider that you will have to enable cross-site requests in OrientDB https://orientdb.com/docs/2.2/Web-Server.html

Body:
This is a sample Angular2 service to connect to OrientDB

import {Injectable} from "@angular/core";
import {Headers, Http} from '@angular/http';

@Injectable()
export class OrientService {

  url = "http://localhost:2480/command/yourDbName/"
  username = "admin";
  password = "admin";

  constructor(private http: Http) {
  }

  command(statement: string, success: (data: any) => void, error: (err: any) => void): void {
    var url = this.url + "sql/-/-1"
    var headers = new Headers();
    headers.append("Authorization", "Basic " + btoa(this.username + ":" +     this.password));

    this.http.post(url,
      JSON.stringify({"command": statement}),
      {headers: headers})
      .toPromise()
      .then(success)
      .catch(error);
  }
}

Then you can use it as follows:

 this.orientService.command(
       "SELECT FROM V",
       (res) => {
         let body = res.json();
         ...
       },
       (e) => {
         console.log(e)
       });

Here you can find a full example: https://github.com/luigidellaquila/geospatial-demo/tree/geeconprague2016

Consider that you will have to enable cross-site requests in OrientDB https://orientdb.com/docs/2.2/Web-Server.html