问:
Positioning a form label
Creating a form, and would like to position the labels on the top left corner of the input texts. Currently have it working by placing a margin-right on the labels - but I don't think this is the 'best' solution. Any other ways round doing it without having to use a margin/padding?

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ul,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    outline:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

body {
    line-height:1;
}

article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section {
    display:block;
}

nav ul {
    list-style:none;
}

blockquote, q {
    quotes:none;
}

blockquote:before, blockquote:after,
q:before, q:after {
    content:'';
    content:none;
}

a {
    margin:0;
    padding:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

/* change colours to suit your needs */
ins {
    background-color:#ff9;
    color:#000;
    text-decoration:none;
}

/* change colours to suit your needs */
mark {
    background-color:#ff9;
    color:#000;
    font-style:italic;
    font-weight:bold;
}

del {
    text-decoration: line-through;
}

abbr[title], dfn[title] {
    border-bottom:1px dotted;
    cursor:help;
}

table {
    border-collapse:collapse;
    border-spacing:0;
}

/* change border colour to suit your needs */
hr {
    display:block;
    height:1px;
    border:0;
    border-top:1px solid #cccccc;
    margin:1em 0;
    padding:0;
}

input, select {
    vertical-align:middle;
}

*{
    border:none;
}
/* here starts my CSS */
.contact-us{
    background-color:#FFB6C1;
    clear:left;
    text-align:center;
    position:relative;
}

.contact-us form{
    margin-top:20px;
    font-family:'amiri';
    border:none;

}

.contact-us form input{
    margin-bottom:10px;
}

.contact-us h2{
     font-family:'Pacifico',sans-serif;
     font-size:30px;
     text-align:center;
     margin-top:20px;
}

input{
    margin:0 auto;
}
input,label{
    display:block;
}

label{
    margin-right:25%;
}

input[type="text"]{
    width:30%;

}

textarea{
    width:30%;
    height:80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "contact-us">
 <div class = "inner-wrapper">

  <h2> Contact </h2>

  <form>

   <section>

   <label for ="name">Name</label>
    <input type = "text" name = "name"><br>

   <label for ="email">Email</label>
    <input type ="text" name = "email"><br>

   <label for ="message">Message</label>
   <textarea name ="message">Enter text here...</textarea>

   </section>

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

答:
The only reliable and least hacky way I could think of is to use position. I have taken the liberty of modifying the HTML. The form fields moved inside the label. Its still valid HTML. See if it works for you.

label{position:relative; display:inline-block;}
label span{position:absolute; top:0; left:0; font-size:14px; line-height:1;}
input,textarea{padding-top:14px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>

<label><span>Name</span>
<input type="text" name="name">
</label>

<label><span>Email</span>
<input type="text" name="email">
</label>

<label><span>Message</span>
<textarea name ="message">Enter text here...</textarea>
</label>

</form></code>```

Title: Positioning a form label

Body:
Creating a form, and would like to position the labels on the top left corner of the input texts. Currently have it working by placing a margin-right on the labels - but I don't think this is the 'best' solution. Any other ways round doing it without having to use a margin/padding?

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ul,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    outline:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

body {
    line-height:1;
}

article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section {
    display:block;
}

nav ul {
    list-style:none;
}

blockquote, q {
    quotes:none;
}

blockquote:before, blockquote:after,
q:before, q:after {
    content:'';
    content:none;
}

a {
    margin:0;
    padding:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

/* change colours to suit your needs */
ins {
    background-color:#ff9;
    color:#000;
    text-decoration:none;
}

/* change colours to suit your needs */
mark {
    background-color:#ff9;
    color:#000;
    font-style:italic;
    font-weight:bold;
}

del {
    text-decoration: line-through;
}

abbr[title], dfn[title] {
    border-bottom:1px dotted;
    cursor:help;
}

table {
    border-collapse:collapse;
    border-spacing:0;
}

/* change border colour to suit your needs */
hr {
    display:block;
    height:1px;
    border:0;
    border-top:1px solid #cccccc;
    margin:1em 0;
    padding:0;
}

input, select {
    vertical-align:middle;
}

*{
    border:none;
}
/* here starts my CSS */
.contact-us{
    background-color:#FFB6C1;
    clear:left;
    text-align:center;
    position:relative;
}

.contact-us form{
    margin-top:20px;
    font-family:'amiri';
    border:none;

}

.contact-us form input{
    margin-bottom:10px;
}

.contact-us h2{
     font-family:'Pacifico',sans-serif;
     font-size:30px;
     text-align:center;
     margin-top:20px;
}

input{
    margin:0 auto;
}
input,label{
    display:block;
}

label{
    margin-right:25%;
}

input[type="text"]{
    width:30%;

}

textarea{
    width:30%;
    height:80px;
}

 Contact

  <form>

   Name
    <input type = "text" name = "name">

   Email
    <input type ="text" name = "email">

   Message
   <textarea name ="message">Enter text here...</textarea>

  </form>

Body:
The only reliable and least hacky way I could think of is to use position. I have taken the liberty of modifying the HTML. The form fields moved inside the label. Its still valid HTML. See if it works for you.

label{position:relative; display:inline-block;}
label span{position:absolute; top:0; left:0; font-size:14px; line-height:1;}
input,textarea{padding-top:14px;}

<form>

<label><span>Name</span>
<input type="text" name="name">
</label>

<label><span>Email</span>
<input type="text" name="email">
</label>

<label><span>Message</span>
<textarea name ="message">Enter text here...</textarea>
</label>

</form>


来源: stackexchange

问:
UITextView limit characters and display count left
I'm trying limit the characters for a UITextView to 200. It gets the data from Firebase Database (if it's available), if not - the UILabel that represents the characters left should be hidden - hence, if there's data (text in the text field it should present the UILabel with left characters.

I've made sure to conform my UIViewController as a delegate of  UITextViewDelegate and I've also set up IBOutlet weak var descriptionTextView: TextViewX! (TextViewX is a subclass of UITextView) and set the descriptionTextView.delegate = self in the viewDidLoad() method. Once you start typing in the text view, the label count is simply not updated or shown at all.

Also, I'd also would like to change the color of the UILabel from green to red when it detects that there are less than 30 characters left.

Here's the code that I have, but it's not working. The characters left is not shown at at all:

```<code>func textView(_ textView: TextViewX, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
    let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
    let numberOfChars = newText.characters.count
    return numberOfChars < 200
}

func textViewDidChange(textView: TextViewX)
{
    let currentCharacterCount = 200 - textView.text.characters.count

    if currentCharacterCount >= 30 {
        descriptionCharacterCountLabel.text = "\(200 - textView.text.characters.count)"
    }
    else
    {
        descriptionCharacterCountLabel.textColor = UIColor.red
        descriptionCharacterCountLabel.text = "\(200 - textView.text.characters.count)"
    }
}
</code>```

答:
If you look closely at the docs for UITextViewDelegate, you will see that textViewDidChange is defined like this:

```<code>optional func textViewDidChange(_ textView: UITextView)
</code>```

Look at the parameter! It requires a parameter with an external parameter name of _!

Look what you've written:

```<code>func textViewDidChange(textView: TextViewX)
</code>```

Your parameter's external name is textView!

This is why it does not work.

So, just add _ and a space before textView and change the type of the parameter to UITextView.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying limit the characters for a UITextView to 200. It gets the data from Firebase Database (if it's available), if not - the UILabel that represents the characters left should be hidden - hence, if there's data (text in the text field it should present the UILabel with left characters.

I've made sure to conform my UIViewController as a delegate of  UITextViewDelegate and I've also set up IBOutlet weak var descriptionTextView: TextViewX! (TextViewX is a subclass of UITextView) and set the descriptionTextView.delegate = self in the viewDidLoad() method. Once you start typing in the text view, the label count is simply not updated or shown at all.

Also, I'd also would like to change the color of the UILabel from green to red when it detects that there are less than 30 characters left.

Here's the code that I have, but it's not working. The characters left is not shown at at all:

func textView(_ textView: TextViewX, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool
{
    let newText = (textView.text as NSString).replacingCharacters(in: range, with: text)
    let numberOfChars = newText.characters.count
    return numberOfChars < 200
}

func textViewDidChange(textView: TextViewX)
{
    let currentCharacterCount = 200 - textView.text.characters.count

    if currentCharacterCount >= 30 {
        descriptionCharacterCountLabel.text = "\(200 - textView.text.characters.count)"
    }
    else
    {
        descriptionCharacterCountLabel.textColor = UIColor.red
        descriptionCharacterCountLabel.text = "\(200 - textView.text.characters.count)"
    }
}

Body:
If you look closely at the docs for UITextViewDelegate, you will see that textViewDidChange is defined like this:

optional func textViewDidChange(_ textView: UITextView)

Look at the parameter! It requires a parameter with an external parameter name of _!

Look what you've written:

func textViewDidChange(textView: TextViewX)

Your parameter's external name is textView!

This is why it does not work.

So, just add _ and a space before textView and change the type of the parameter to UITextView.


问:
React : Cannot update during an existing state transition error
I have a function which generatesTimelist for me. When it starts rendering the method should be called and the state displayed. It gets displayed, but the console is throwing multiple errors of:

```<code>setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.
</code>```

My code looks like this:

```<code>import React, { Component } from 'react';

export default class Timeline extends Component {
    constructor(props) {
        super();
            this.state = {
                timeList: 'aa'
            };
        }

      generateTimelineArray(start = 1499162400, end = 1499248800, step = 60) {
      let arr =[];
      for(let i = start; i <= end;i+=step) {
        const date = new Date(i);
        const hours = date.getHours();
        const mins = date.getMinutes();
        arr[i] = {
          time: hours + ":" + mins,
          hour: hours,
          minutes: mins
        };
      }
    this.setState({ timeList: 'bb'});
        this.setState({ timeList: 'bb'});

    }

  render() {

{this.generateTimelineArray()}
    return (
      <div className="App" >
       {this.state.timeList}
      </div>
    );
  }
}
</code>```

The generateTimelineArray is looping trough the specified arguments and creating an array. Which i later on want to map into another component, for example purposes i changed it to a string.

What is the cause of the error and how should this be fixed ?

答:
You can't call this.setState within a render cycle, just as the error has told you. Why not instead call the generateTimelineArray in the componentWillReceiveProps lifecycle function provided by React? Or perhaps during the componentWillMount function if you don't see the state of it changing.

This is a better place to 'react' to changes in state and as such build new component state. Ultimately you would end up in a a never ending loop because you would constantly be rendering and resetting the component state

Facebook Documentation on React Lifecycle - componentWillReceiveProps

Body:
I have a function which generatesTimelist for me. When it starts rendering the method should be called and the state displayed. It gets displayed, but the console is throwing multiple errors of:

setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

My code looks like this:

import React, { Component } from 'react';

export default class Timeline extends Component {
    constructor(props) {
        super();
            this.state = {
                timeList: 'aa'
            };
        }

      generateTimelineArray(start = 1499162400, end = 1499248800, step = 60) {
      let arr =[];
      for(let i = start; i <= end;i+=step) {
        const date = new Date(i);
        const hours = date.getHours();
        const mins = date.getMinutes();
        arr[i] = {
          time: hours + ":" + mins,
          hour: hours,
          minutes: mins
        };
      }
    this.setState({ timeList: 'bb'});
        this.setState({ timeList: 'bb'});

    }

  render() {

{this.generateTimelineArray()}
    return (

       {this.state.timeList}

    );
  }
}

The generateTimelineArray is looping trough the specified arguments and creating an array. Which i later on want to map into another component, for example purposes i changed it to a string.

What is the cause of the error and how should this be fixed ?


问:
Test environment for microsoft graph api and Azure v2.0
I am integrating OneNote application using MS graph endpoints. To authenticate the user I am using azure v2.0 endpoint. Does microsoft graph platform, onenote and azure provides test/sandbox environment the same.

Currently I am using endpoints as follows -

Fetch onenote notebooks - https://graph.microsoft.com/v1.0/me/onenote/notebooks

Authenticate user using Azure v2.0 - https://login.microsoftonline.com/common/oauth2/v2.0/authorize
https://login.microsoftonline.com/common/oauth2/v2.0/token

These endpoints works in all environment including dev/prod/test. The kind of application that we register at https://apps.dev.microsoft.com/ does that only matter ?

答:
https://developer.microsoft.com/en-us/graph/graph-explorer

Yes - you can use the graph explorer as your test environment.

https://developer.microsoft.com/en-us/graph/docs/concepts/auth_register_app_v2

Yes - the kind of application you register matters. If this is a new app, I'd recommend using a converged application so your app works for O365 and Microsoft accounts. See link above for full description.


问:
Why are literal HTML strings being appended to the DOM?
When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:

```<code>var banner ={
    'Format': '90x120cm',
    'Value': 35
};
// var premium = { key: values };

function defineProduct(data) {
        var item = $('span.tooltip')[0];
        console.log($('span.tooltip'));
        for(var keys in data){
            console.log(keys);
            item.append('<div class="item"><div class="left">'+keys+':</div><div class="right ">'+data[keys]+'</div></div>');
        }
    }

defineProduct(banner);
</code>```

HTML:

```<code><div class="three-columns">
        <div class="col">
            <div class="image-holder">
                <a href='' id="premium" class="tooltips">
                <img src="" class="premium-img" width="85px" height="79px">
                <p class="description">Cartão <br><span style="color: #ffc600;" class="different">premium</span></p>
                    <span class="tooltip"></span>
                </a>
            </div>
        <!-- Same thing from above different description -->
        <!-- ditto -->
</div>
</code>```

Output:

What have I tried/used:

.get();

.prepend(string);

.html(string);

.text(string); <– I don't know why, but I did

document.createTextNode(string);

set a variable which contains HTML tags strings and set to one of the previous attempts

And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc

答:
You're using ParentNode.append to append a literal DOMString which is appended as a text node instead of jQuery#append here:

```<code>var item = $('span.tooltip')[0];
</code>```

The [0] access the underlying DOM element in the jQuery object. Remove the [0] to use jQuery methods (or eq(0) for the first element in the selection collection as a jQuery object) on it or use Node.appendChild.

Body:
When prepending or appending to an element, it literally puts the text and doesn't compile in HTML:

var banner ={
    'Format': '90x120cm',
    'Value': 35
};
// var premium = { key: values };

function defineProduct(data) {
        var item = $('span.tooltip')[0];
        console.log($('span.tooltip'));
        for(var keys in data){
            console.log(keys);
            item.append('

'+keys+':

'+data[keys]+'

');
        }
    }

defineProduct(banner);

HTML:

Cartão
premium

Output:

What have I tried/used:

.get();

.prepend(string);

.html(string);

.text(string); <– I don't know why, but I did

document.createTextNode(string);

set a variable which contains HTML tags strings and set to one of the previous attempts

And the reason I used .get() is because I have more than one object that are equivalent to the quantity of their elements, in this case, I have 3. So, for every append, I have different information. E.g.: .get(0), .get(1), etc

Body:
You're using ParentNode.append to append a literal DOMString which is appended as a text node instead of jQuery#append here:

var item = $('span.tooltip')[0];

The [0] access the underlying DOM element in the jQuery object. Remove the [0] to use jQuery methods (or eq(0) for the first element in the selection collection as a jQuery object) on it or use Node.appendChild.


问:
SQL Query assistance - Looping through data query
I have two tables. Config and Data. Config table has info to define what I call "Predefined Points". The columns are configId, machineId, iotype, ioid, subfield and predeftype. I have a second table that contains all the data for all the items in the config table linked by configId. Data table contains configId, timestamp, value.

I am trying to return each row from the config table with 2 new columns in the result which would be min timestamp of this particular predefined point and max timestamp of this particular predefined point.

Pseudocode would be

```<code>select a.*, min(b.timestamp), max(b.timestamp) from TrendConfig a join TrendData b on a.configId = b.configId where configId = (select configId from TrendConfig)
</code>```

Where the subquery would return multiple values.

Any idea how to formulate this?

答:
I was able to find an answer using: Why can't you mix Aggregate values and Non-Aggregate values in a single SELECT?

The solution was indeed GROUP BY as CL mentioned above.

select a.*, min(b.timestamp), max(b.timestamp) from TrendConfig a join TrendData b on a.configId = b.configId group by a.configId

Body:
I have two tables. Config and Data. Config table has info to define what I call "Predefined Points". The columns are configId, machineId, iotype, ioid, subfield and predeftype. I have a second table that contains all the data for all the items in the config table linked by configId. Data table contains configId, timestamp, value.

I am trying to return each row from the config table with 2 new columns in the result which would be min timestamp of this particular predefined point and max timestamp of this particular predefined point.

Pseudocode would be

select a.*, min(b.timestamp), max(b.timestamp) from TrendConfig a join TrendData b on a.configId = b.configId where configId = (select configId from TrendConfig)

Where the subquery would return multiple values.

Any idea how to formulate this?


问:
Vue.js 2: Delete property from data object
How can you delete a property/key from a Vue.js data object (i.e. associative array) like this:

```<code>var vm = new Vue({
    data: {
        users: {
            foo : { firstName: ..., lastName: ... },
            bar : { firstName: ..., lastName: ... }
        }
    },
    methods: {
        someFunction : function ()
        {
            // how to remove `users.foo`?
        }
    }
});
</code>```

Googling around, I found these two ways, but both don't work:

delete this.users.foo; is not updating the DOM

this.users.splice('foo', 1); is not working at all (probably only works on arrays, not on objects)

答:
The answer is:

```<code>Vue.delete(users, 'foo');
</code>```

It took me a while to find it, that's why I'm posting it here ;-)

https://github.com/vuejs/vue/issues/3368#issuecomment-236642919

Body:
How can you delete a property/key from a Vue.js data object (i.e. associative array) like this:

var vm = new Vue({
    data: {
        users: {
            foo : { firstName: ..., lastName: ... },
            bar : { firstName: ..., lastName: ... }
        }
    },
    methods: {
        someFunction : function ()
        {
            // how to remove `users.foo`?
        }
    }
});

Googling around, I found these two ways, but both don't work:

delete this.users.foo; is not updating the DOM

this.users.splice('foo', 1); is not working at all (probably only works on arrays, not on objects)

Body:
The answer is:

Vue.delete(users, 'foo');

It took me a while to find it, that's why I'm posting it here ;-)

https://github.com/vuejs/vue/issues/3368#issuecomment-236642919


问:
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>```

答:
Use below code to enable your bluetooth

```<code> BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

      if(!mBluetoothAdapter.isEnabled()){
 AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
        alertBuilder.setCancelable(true);
        alertBuilder.setMessage("Do you want to enable bluetooth");
        alertBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mBluetoothAdapter.enable();
            }
        });
        AlertDialog alert = alertBuilder.create();
        alert.show();
       }
</code>```

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:
Use below code to enable your bluetooth

 BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

      if(!mBluetoothAdapter.isEnabled()){
 AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
        alertBuilder.setCancelable(true);
        alertBuilder.setMessage("Do you want to enable bluetooth");
        alertBuilder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mBluetoothAdapter.enable();
            }
        });
        AlertDialog alert = alertBuilder.create();
        alert.show();
       }


问:
Symfony One-To-Many unidirectional relation without JOIN table
I have the following tables:

```<code>strings
------
"id" int not null primary key

string_texts
------
"id"          int not null primary key
"string_id"   int not null fk(strings.id)
"language_id" int not null fk(languages.id)
"text"        text

"countries"
------
"id"      int not null primary key,
"name_id" int not null fk(strings.id)
</code>```

All localizable text stored in a single table, and every other table connected to that table.

What I dont know is how to write the Country model? This is how I got so far.

```<code>namespace LoginHood\HoodBundle\Entity\Geo;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

class Country
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     */
    protected $id;

    /**
     * @var Collection
     *
     * @ORM\OneToMany(targetEntity="StringText", mappedBy="")
     */
    protected $names;

    /*
    ...
    */

    public function __construct()
    {
        $this->names = new ArrayCollection();
    }
}
</code>```

Because of the structure you can't get the Country or any Entity from the StringText entity. But I don't want to make a join table, because its kind of an overkill, and totally meaningless.

答:
I want to explain to you something you should know.

Let's say that we have table A, table B, and table C.

and then

you want the table A, table B, and table C having relation without JOIN

I will tell you that it is imposible.

WHY ?

Actually, if  table A, table B, and table C have a Relation,

  it means that you are doing JOIN on your table.

Body:
I have the following tables:

strings
------
"id" int not null primary key

string_texts
------
"id"          int not null primary key
"string_id"   int not null fk(strings.id)
"language_id" int not null fk(languages.id)
"text"        text

"countries"
------
"id"      int not null primary key,
"name_id" int not null fk(strings.id)

All localizable text stored in a single table, and every other table connected to that table.

What I dont know is how to write the Country model? This is how I got so far.

namespace LoginHood\HoodBundle\Entity\Geo;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

class Country
{
    /**
     * @var int
     *
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="SEQUENCE")
     */
    protected $id;

    /**
     * @var Collection
     *
     * @ORM\OneToMany(targetEntity="StringText", mappedBy="")
     */
    protected $names;

    /*
    ...
    */

    public function __construct()
    {
        $this->names = new ArrayCollection();
    }
}

Because of the structure you can't get the Country or any Entity from the StringText entity. But I don't want to make a join table, because its kind of an overkill, and totally meaningless.


答:
I'd do this by placing each label along with its respective input field into a div.  Make the label and input field aligned with the left side of the div; all you need to do now is edit the div to move the positioning of the label and input field in unison.

To do this, I created a div class called inputfielddiv (see below).  Just adjust the left-margin of inputfielddiv to adjust the positioning of all of the fields and their respective labels.

Hope this helps!  Let me know if you need further clarification.

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ul,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    outline:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

body {
    line-height:1;
}

article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section {
    display:block;
}

nav ul {
    list-style:none;
}

blockquote, q {
    quotes:none;
}

blockquote:before, blockquote:after,
q:before, q:after {
    content:'';
    content:none;
}

a {
    margin:0;
    padding:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

/* change colours to suit your needs */
ins {
    background-color:#ff9;
    color:#000;
    text-decoration:none;
}

/* change colours to suit your needs */
mark {
    background-color:#ff9;
    color:#000;
    font-style:italic;
    font-weight:bold;
}

del {
    text-decoration: line-through;
}

abbr[title], dfn[title] {
    border-bottom:1px dotted;
    cursor:help;
}

table {
    border-collapse:collapse;
    border-spacing:0;
}

/* change border colour to suit your needs */
hr {
    display:block;
    height:1px;
    border:0;
    border-top:1px solid #cccccc;
    margin:1em 0;
    padding:0;
}

input, select {
    vertical-align:middle;
}

*{
    border:none;
}
/* here starts my CSS */
.contact-us{
    background-color:#FFB6C1;
    clear:left;
    text-align:center;
    position:relative;
}

.contact-us form{
    margin-top:20px;
    font-family:'amiri';
    border:none;

}

.contact-us form input{
    margin-bottom:10px;
}

.contact-us h2{
     font-family:'Pacifico',sans-serif;
     font-size:30px;
     text-align:center;
     margin-top:20px;
}

input,label{
    display:block;
}

input[type="text"]{
    width:30%;

}

textarea{
    width:30%;
    height:80px;
    display:block;
}

.inputfielddiv {
  margin-left: 30%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class = "contact-us">
 <div class = "inner-wrapper">

  <h2> Contact </h2>

  <form>

   <section>
   <div class="inputfielddiv">
   <label align="left" for ="name">Name</label>
    <input align="left" type = "text" name = "name"><br>
      </div>

      <div class="inputfielddiv">
   <label align="left" for ="email">Email</label>
    <input align="left" type ="text" name = "email"><br>
    </div>

      <div class="inputfielddiv">
   <label align="left" for ="message">Message</label>
   <textarea align="left" name ="message">Enter text here...</textarea>
      </div>

   </section>

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

Title: Positioning a form label

Body:
I'd do this by placing each label along with its respective input field into a div.  Make the label and input field aligned with the left side of the div; all you need to do now is edit the div to move the positioning of the label and input field in unison.

To do this, I created a div class called inputfielddiv (see below).  Just adjust the left-margin of inputfielddiv to adjust the positioning of all of the fields and their respective labels.

Hope this helps!  Let me know if you need further clarification.

html, body, div, span, object, iframe,
h1, h2, h3, h4, h5, h6, blockquote, pre,
abbr, address, cite, code,
del, dfn, em, img, ins, kbd, q, samp,
small, strong, sub, sup, var,
b, i,
dl, dt, dd, ul,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, figcaption, figure,
footer, header, hgroup, menu, nav, section, summary,
time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    outline:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

body {
    line-height:1;
}

article,aside,details,figcaption,figure,
footer,header,hgroup,menu,nav,section {
    display:block;
}

nav ul {
    list-style:none;
}

blockquote, q {
    quotes:none;
}

blockquote:before, blockquote:after,
q:before, q:after {
    content:'';
    content:none;
}

a {
    margin:0;
    padding:0;
    font-size:100%;
    vertical-align:baseline;
    background:transparent;
}

/* change colours to suit your needs */
ins {
    background-color:#ff9;
    color:#000;
    text-decoration:none;
}

/* change colours to suit your needs */
mark {
    background-color:#ff9;
    color:#000;
    font-style:italic;
    font-weight:bold;
}

del {
    text-decoration: line-through;
}

abbr[title], dfn[title] {
    border-bottom:1px dotted;
    cursor:help;
}

table {
    border-collapse:collapse;
    border-spacing:0;
}

/* change border colour to suit your needs */
hr {
    display:block;
    height:1px;
    border:0;
    border-top:1px solid #cccccc;
    margin:1em 0;
    padding:0;
}

input, select {
    vertical-align:middle;
}

*{
    border:none;
}
/* here starts my CSS */
.contact-us{
    background-color:#FFB6C1;
    clear:left;
    text-align:center;
    position:relative;
}

.contact-us form{
    margin-top:20px;
    font-family:'amiri';
    border:none;

}

.contact-us form input{
    margin-bottom:10px;
}

.contact-us h2{
     font-family:'Pacifico',sans-serif;
     font-size:30px;
     text-align:center;
     margin-top:20px;
}

input,label{
    display:block;
}

input[type="text"]{
    width:30%;

}

textarea{
    width:30%;
    height:80px;
    display:block;
}

.inputfielddiv {
  margin-left: 30%;
}

<div class = "contact-us">
 <div class = "inner-wrapper">

  <h2> Contact </h2>

  <form>

   <section>
   <div class="inputfielddiv">
   <label align="left" for ="name">Name</label>
    <input align="left" type = "text" name = "name"><br>
      </div>

      <div class="inputfielddiv">
   <label align="left" for ="email">Email</label>
    <input align="left" type ="text" name = "email"><br>
    </div>

      <div class="inputfielddiv">
   <label align="left" for ="message">Message</label>
   <textarea align="left" name ="message">Enter text here...</textarea>
      </div>

   </section>

  </form>
 </div>
</div>


问:
React native inspect element on desktop
Using react native on windows, is there anyway I can inspect elements and their styles in Chrome on my desktop, like you would with a webpage?

I have the dev tools on my device, but would like to use my desktop to debug.

Any ideas?

Thanks

答:
https://github.com/jhen0409/react-native-debugger
I haven't used it. But maybe you can try it.</p>

Title: React native inspect element on desktop


问:
How to randomly choose columns from a text file
I have a text file (tab delimited)

```<code>Name Attribute1 Attribute2 ..........Attribute1000
aaaa   1           100                  0
bbbb   0            20                  50
cccc   10           20                  30
</code>```

I want to randomly choose 25 columns from the Attributes but always keep the first column (Name). How can I do this?

答:
First, craft a sequence of the columns to display : the first one followed by 25 unique random ones.

```<code>TOTAL_COLUMN_AMOUNT=1001
TARGET_COLUMN_AMOUNT=25

columns=(1)               # initialize an array with the columns that must always be picked
while [ ${#columns[@]} -lt $(( TARGET_COLUMN_AMOUNT + 1 )) ]; do #until we have enough data
    current_column=$(( (RANDOM % TOTAL_COLUMN_AMOUNT) + 1 ))     #pick a random index
    if [[ ! " ${columns[@]} " =~ " $current_column " ]]; then    #if it's not already there
        columns[${#columns[@]}]=$current_column                  #append it to the array
    fi
done
#echo ${columns[@]}
</code>```

Then, you can use awk to display only the selected columns :

```<code>awk -v var="${columns[*]}" 'BEGIN{split(columns,awk_columns," ")};{for (i in awk_columns) {print $i}}'
</code>```

Body:
I have a text file (tab delimited)

Name Attribute1 Attribute2 ..........Attribute1000
aaaa   1           100                  0
bbbb   0            20                  50
cccc   10           20                  30

I want to randomly choose 25 columns from the Attributes but always keep the first column (Name). How can I do this?

Body:
First, craft a sequence of the columns to display : the first one followed by 25 unique random ones.

TOTAL_COLUMN_AMOUNT=1001
TARGET_COLUMN_AMOUNT=25

columns=(1)               # initialize an array with the columns that must always be picked
while [ ${#columns[@]} -lt $(( TARGET_COLUMN_AMOUNT + 1 )) ]; do #until we have enough data
    current_column=$(( (RANDOM % TOTAL_COLUMN_AMOUNT) + 1 ))     #pick a random index
    if [[ ! " ${columns[@]} " =~ " $current_column " ]]; then    #if it's not already there
        columns[${#columns[@]}]=$current_column                  #append it to the array
    fi
done
#echo ${columns[@]}

Then, you can use awk to display only the selected columns :

awk -v var="${columns[*]}" 'BEGIN{split(columns,awk_columns," ")};{for (i in awk_columns) {print $i}}'


问:
WPF MainWindow to display other pages
I am trying to create a Main Window that will have a Header for navigation/buttons, and a footer for displaying information.
(similar to the top and bottom bars on StackOverflow.com)

What is the best way to make the Main Window function as a container that could display any page in between the header/footer?

答:
You can use a Grid</p>

```<code><Grid >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
 <local:TopPage Grid.Column="0" Grid.Row="0" />
 <local:MidPage Grid.Column="0" Grid.Row="1" />
 <local:BottomPage Grid.Column="0" Grid.Row="2" />
 </Grid>
</code>```

Title: WPF MainWindow to display other pages

Body:
You can use a Grid

<Grid >
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
 <local:TopPage Grid.Column="0" Grid.Row="0" />
 <local:MidPage Grid.Column="0" Grid.Row="1" />
 <local:BottomPage Grid.Column="0" Grid.Row="2" />
 </Grid>


问:
Regex to identify 3+ consecutive of same alpha/numeric
I have been trying to write/find a regex that will identify where there are 3+ consecutive instances of an alpha/numeric.

Example:

```<code>CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER
</code>```

this would be a match b/c of the '**AAAAAAA**'

Thanks!

答:
the

```<code>echo 'CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER' | grep -E -o '([A-Z])\1{2,}'
</code>```

outputs:

```<code>AAAAAAA
</code>```

grep tool for Unix and Linux

-E  PATTERN is an extended regular expression (ERE)

-o  show only the part of a line matching PATTERN

 ([A-Z]) matches a single character and takes care of the match as a back-reference

\1{2,} using that back-reference plus 2 or more that is equal 3 consecutive character or more

So:

```<code>echo 'not nn nnn oo ooo tt ttt 123 11 111' | grep -E -o '(\w)\1{2,}'
</code>```

will match:

```<code>nnn
ooo
ttt
111
</code>```

Or:

```<code>echo 'not nnn ooo ttt 123 111' | grep -E -o '([[:alpha:]]|[[:digit:]])\1{2,}'
</code>```

has the same output.

But as may or may not you know \w match the _ as well therefore using character class like [a-z] or build-in character class like [[:alpha:]] is a better choice.

Body:
I have been trying to write/find a regex that will identify where there are 3+ consecutive instances of an alpha/numeric.

Example:

CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER

this would be a match b/c of the '**AAAAAAA**'

Thanks!

Body:
the

echo 'CHAIRMAN AAAAAAAND CHIEF EXECUTIVE OFFICER' | grep -E -o '([A-Z])\1{2,}'

outputs:

AAAAAAA

grep tool for Unix and Linux

-E  PATTERN is an extended regular expression (ERE)

-o  show only the part of a line matching PATTERN

 ([A-Z]) matches a single character and takes care of the match as a back-reference

\1{2,} using that back-reference plus 2 or more that is equal 3 consecutive character or more

So:

echo 'not nn nnn oo ooo tt ttt 123 11 111' | grep -E -o '(\w)\1{2,}'

will match:

nnn
ooo
ttt
111

Or:

echo 'not nnn ooo ttt 123 111' | grep -E -o '([[:alpha:]]|[[:digit:]])\1{2,}'

has the same output.

But as may or may not you know \w match the _ as well therefore using character class like [a-z] or build-in character class like [[:alpha:]] is a better choice.


问:
How do I use MAMP standard on a Mac?
I have tried this 3 or 4 times, but it seems like the only version is MAMP pro, every time I install the .pkg file, it installs MAMP pro, the MAMP standard and pro version seems (according to the  docs) to be bundled together with the pro version. The docs say the standard version will work after the demo pro expires but all it does it lock down the entire app.

"This download package for Mac OS X contains the free MAMP and a free 14-day trial of MAMP PRO. MAMP can be used stand-alone without MAMP PRO."

^ Does this "stand-alone" even exist?

I selected customize, and I un-checked the Pro version but it does not do this. Every time I launch the app I have a demo expired error.

答: MAMP.app (the thing you need) is buried inside of the MAMP/ folder (unlike the pro version) so if you are good at where's waldo, then you won't have any trouble since its in a folder with dozens of other things that all render the same looking on Mac. PC users probably don't have this issue.</p>

Title: How do I use MAMP standard on a Mac?


问:
add non "type library" dll as reference to VS C++ 2008
I just received a request from colleague to work out why a specific dll cannot be added as a reference in Visual Studio 2008 Version 9.0.21022.8 RTM with MS .Net Framework Version 3.5 SP1.

The language used is Visual C++ 2008, I have never done anything in this language, although I've done a bit in C# before...

Please check the following two error messages, first one came from my laptop, the second from my colleague's:

From my Google research I am afraid the target dll is:

NOT a type library. Confirmed by running the tlbimp utility:

```<code>tlbimp C:\test\tm1api.dll

......

error TI0000 : The input file 'C:\test\tm1api.dll' is not a valid type library
</code>```

What does this mean, anything to convert it to a type library?

NOT a .NET assembly or a registered ActiveX Control. The dll was not programmed in VS I am   afraid. But how could I verify this?

Basically I am confused, because two VS 2008 show different error messages, is this issue specific to VS 2008 only? Or is there a general solution in VS for this sort of thing?

Many thanks to the help in advance.

答: you've probably got just a regular old dll.  use the dllimport to access its methods.  Be aware that there are usually all kinds of data marshalling issues when interacting with a C++ dll, like instead of int you might need to use short, and IntPtr instead of arrays...stuff like that.</p>

ContentLicense: CC BY-SA 2.5

Body:
I just received a request from colleague to work out why a specific dll cannot be added as a reference in Visual Studio 2008 Version 9.0.21022.8 RTM with MS .Net Framework Version 3.5 SP1.

The language used is Visual C++ 2008, I have never done anything in this language, although I've done a bit in C# before...

Please check the following two error messages, first one came from my laptop, the second from my colleague's:

From my Google research I am afraid the target dll is:

NOT a type library. Confirmed by running the tlbimp utility:

tlbimp C:\test\tm1api.dll

......

error TI0000 : The input file 'C:\test\tm1api.dll' is not a valid type library

What does this mean, anything to convert it to a type library?

NOT a .NET assembly or a registered ActiveX Control. The dll was not programmed in VS I am   afraid. But how could I verify this?

Basically I am confused, because two VS 2008 show different error messages, is this issue specific to VS 2008 only? Or is there a general solution in VS for this sort of thing?

Many thanks to the help in advance.


问:
mySQL lock records from cronjobs
I have a table that stores customer submitted forms.

There is also a cron script that selects records from this table for processing. It runs every minute.

SELECT * from Forms where to_CRM = 0 limit 10

The problem is sometimes the API takes a while to complete so that sometimes the next batch is already requested to run before the previous batch completes.

This causes the same person to be selected for processing as his To_CRM flag is still 0;

It is imperative that a lock does not lock the table from being able to insert new records.

What is the best way to solve this issue via transactions or a different approach like setting a column in the table while it's processing?

答:
Maybe you want to actually update the table:

```<code>UPDATE Forms SET to_CRM=1499358596 WHERE to_CRM=0 LIMIT 10
</code>```

Where that represents the time of execution. Then:

```<code>SELECT * From Forms WHERE to_CRM=1499358596
</code>```

This won't double up because each run will exclude those that it's operating on from subsequent runs due to the WHERE clause. I'm presuming you can use the to_CRM field here, but you could just as well add another specifically for locking/claiming.

Title: mySQL lock records from cronjobs

Body:
Maybe you want to actually update the table:

UPDATE Forms SET to_CRM=1499358596 WHERE to_CRM=0 LIMIT 10

Where that represents the time of execution. Then:

SELECT * From Forms WHERE to_CRM=1499358596

This won't double up because each run will exclude those that it's operating on from subsequent runs due to the WHERE clause. I'm presuming you can use the to_CRM field here, but you could just as well add another specifically for locking/claiming.


问:
Hide a React component in existing web project
I'm currently trying to integrate a React component into a legacy web project (a huge html index file and some js scripts using mostly jquery).

I am trying to add the rendered react component into a separate tab. Now the problem is that I cannot control the visibility of the top level React component.

Say I have the following src code in html:

```<code>...
<div id="wrapper">
    <div id="react-component"></div>
</div>
...
</code>```

I render the inner component using React. Now is there any way to control the visibility of either "#wrapper" or "#react-component" ? jquery does not help.

I am relatively new to React and it seems that integrating it into old project can be a huge pain.

答:
I render the inner component using React. Now is there any way to control the visibility of either "#wrapper" or "#react-component" ?

Well those are two different worlds.

For the #wrapper you can just use DOM manipulation like $.hide() and $.show() or however you'd normally do it in jQuery.

For the #react-component you need to call ReactDOM.render(), and you can pass in a visible prop to change the visibility of the rendered elements. Something like:

```<code>ReactDOM.render(
  <MyComponent visible={isReactComponentVisible} />,
  document.getElementById("react-component")
);
</code>```

Now your React component can show or hide itself however you want.

```<code>class MyComponent extends React.Component {
  render() {
    return (
      <div style={{ display: this.props.visible ? "block" : "none" }}>
        ...
      </div>
    )
  }
}
</code>```

Of course its up to you to call ReactDOM.render() anytime that isReactComponentVisible changes. A formal state binding library like Redux could help you here, if the complexity warrants it.

Remember that React will diff the renders so calling ReactDOM.render() is not rebuilding the entire component's DOM (as jQuery would be), just what changed (ie the DOM effected by the visible prop: the style.display attribute.)

Body:
I'm currently trying to integrate a React component into a legacy web project (a huge html index file and some js scripts using mostly jquery).

I am trying to add the rendered react component into a separate tab. Now the problem is that I cannot control the visibility of the top level React component.

Say I have the following src code in html:

...

...

I render the inner component using React. Now is there any way to control the visibility of either "#wrapper" or "#react-component" ? jquery does not help.

I am relatively new to React and it seems that integrating it into old project can be a huge pain.

Body:
I render the inner component using React. Now is there any way to control the visibility of either "#wrapper" or "#react-component" ?

Well those are two different worlds.

For the #wrapper you can just use DOM manipulation like $.hide() and $.show() or however you'd normally do it in jQuery.

For the #react-component you need to call ReactDOM.render(), and you can pass in a visible prop to change the visibility of the rendered elements. Something like:

ReactDOM.render(
  <MyComponent visible={isReactComponentVisible} />,
  document.getElementById("react-component")
);

Now your React component can show or hide itself however you want.

class MyComponent extends React.Component {
  render() {
    return (
      <div style={{ display: this.props.visible ? "block" : "none" }}>
        ...
      </div>
    )
  }
}

Of course its up to you to call ReactDOM.render() anytime that isReactComponentVisible changes. A formal state binding library like Redux could help you here, if the complexity warrants it.

Remember that React will diff the renders so calling ReactDOM.render() is not rebuilding the entire component's DOM (as jQuery would be), just what changed (ie the DOM effected by the visible prop: the style.display attribute.)


问:
Select Data by Id PHP
I have trouble to select a set of specific data using ID from the database. For example, employee one has a unique id of e000000001, when I click the view button in the index will lead to employee detail page which shows the detail of that particular employee instead of all the employees' detail. Thank you.

//from index.php page

```<code>    <?php
    require_once 'db/dbEmpList.php';
    $sqlStr = "SELECT * FROM employees;";

    $result = $connection->query($sqlStr);

    if ($result->num_rows > 0) {

        echo "<table class='table table-sm'><thread><tr><th>Full Name</th><th>Employee ID</th><th>Position</th><th>View Employee's Details</th></tr>";
        while ($row = $result->fetch_assoc()) {

            echo "<tr><td>"
            . $row["empName"]. "</td><td>"
                    . $row["empID"]. "</td><td>"
                    . $row["position"]. "</td>"
                    . "<td> <a href='employeedetail.php?id={$row["empID"]}'>View</a>"
                    . "</td></tr>";
        }
    }
</code>```

// from employee page

```<code>require_once 'db/dbEmpDetail.php';
$sql = "SELECT * FROM employees where empID = '{$row["empID"]}' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
    }
} else {
    echo "0 results";
}
mysqli_close($connection);
?>
</code>```

答:
// FROM EMPLOYEE PAGE

The way you retrieve URL query string is wrong. You should be using $_GET to get the query string from URL. In your case it should be $_GET['id']. See the code below:

```<code>require_once 'db/dbEmpDetail.php';
$employeeid = trim(mysqli_real_escape_string($_GET['id']));
$sql = "SELECT * FROM employees where empID = '".$employeeid."' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
    }
}
else {
    echo "0 results";
}
mysqli_close($connection);
?>
</code>```

Title: Select Data by Id PHP

Body:
I have trouble to select a set of specific data using ID from the database. For example, employee one has a unique id of e000000001, when I click the view button in the index will lead to employee detail page which shows the detail of that particular employee instead of all the employees' detail. Thank you.

//from index.php page

    <?php
    require_once 'db/dbEmpList.php';
    $sqlStr = "SELECT * FROM employees;";

    $result = $connection->query($sqlStr);

    if ($result->num_rows > 0) {

        echo "
<thread>
Full Name	Employee ID	Position	View Employee's Details
";
        while ($row = $result->fetch_assoc()) {

            echo "
"
            . $row["empName"]. "	"
                    . $row["empID"]. "	"
                    . $row["position"]. "	"
                    . " View"
                    . "
";
        }
    }

// from employee page

require_once 'db/dbEmpDetail.php';
$sql = "SELECT * FROM employees where empID = '{$row["empID"]}' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo '
' .'' .$row["empName"].'	'.''. $row["position"].'	' .''.$row["empNRIC"].'	' .''.$row["empID"].'	' .''.$row["empEmail"].'	' .''.$row["empPwd"].'	' . "
";
    }
} else {
    echo "0 results";
}
mysqli_close($connection);
?>

Body:
// FROM EMPLOYEE PAGE

The way you retrieve URL query string is wrong. You should be using $_GET to get the query string from URL. In your case it should be $_GET['id']. See the code below:

require_once 'db/dbEmpDetail.php';
$employeeid = trim(mysqli_real_escape_string($_GET['id']));
$sql = "SELECT * FROM employees where empID = '".$employeeid."' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result)) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo '<tr>' .'<td>' .$row["empName"].'</td>'.'<td>'. $row["position"].'</td>' .'<td>'.$row["empNRIC"].'</td>' .'<td>'.$row["empID"].'</td>' .'<td>'.$row["empEmail"].'</td>' .'<td>'.$row["empPwd"].'</td>' . "</tr>";
    }
}
else {
    echo "0 results";
}
mysqli_close($connection);
?>