问:
[UIViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance
I have a tabbar view that is connected to some items.

I want that one of these items contains a TableView, but I don't want to use a TableViewController because I want to put something else in the head of the page.

My ViewController implements the 2 protocols UITableViewDataSource and UITableViewDelegate and contains the following functions:

```<code>        func tableView(_ tableView: UITableView, numberOfRowsInSection
      section: Int) ->
    Int {
        // Return the number of rows in the section.
        return annunci.count
     }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath:
      IndexPath) ->
    UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier:
         cellIdentifier, for: indexPath)
        // Configure the cell...
        cell.textLabel?.text = annunci[indexPath.row]
        return cell }
</code>```

Then, from the storyboard I added a prototype cell with identifier "Cell" and linked the tableView to the viewController as DataSource and Delegate.

When I run the app it is ok, but when I select the item that contains the table view the app throws this exception:

```<code>       *** Terminating app due to uncaught exception
     'NSInvalidArgumentException', reason: '-[UIViewController
      tableView:numberOfRowsInSection:
      unrecognized selector sent to instance 0x101c29370'
</code>```

How can I put something on the top of the page and then the tableView or how can i solve this problem?

I am using Swift 3 and Xcode 8.2.1

答:
For me it was that I had forgotten to include the delegate and data source.

```<code>class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { ... }
</code>```

For other reasons, see this minimal working version of a UITableView. Run it in a new new project and compare your code to it to find the bug.

Body:
I have a tabbar view that is connected to some items.

I want that one of these items contains a TableView, but I don't want to use a TableViewController because I want to put something else in the head of the page.

My ViewController implements the 2 protocols UITableViewDataSource and UITableViewDelegate and contains the following functions:

        func tableView(_ tableView: UITableView, numberOfRowsInSection
      section: Int) ->
    Int {
        // Return the number of rows in the section.
        return annunci.count
     }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath:
      IndexPath) ->
    UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier:
         cellIdentifier, for: indexPath)
        // Configure the cell...
        cell.textLabel?.text = annunci[indexPath.row]
        return cell }

Then, from the storyboard I added a prototype cell with identifier "Cell" and linked the tableView to the viewController as DataSource and Delegate.

When I run the app it is ok, but when I select the item that contains the table view the app throws this exception:

       *** Terminating app due to uncaught exception
     'NSInvalidArgumentException', reason: '-[UIViewController
      tableView:numberOfRowsInSection:
      unrecognized selector sent to instance 0x101c29370'

How can I put something on the top of the page and then the tableView or how can i solve this problem?

I am using Swift 3 and Xcode 8.2.1

Body:
For me it was that I had forgotten to include the delegate and data source.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { ... }

For other reasons, see this minimal working version of a UITableView. Run it in a new new project and compare your code to it to find the bug.


来源: stackexchange

问:
"Undefined" updating or delete a fresh new comment using Ajax and Laravel
When i create a new comment it displays good but i can't edit it or delete, to do it i have to refresh the page first.. The reason? In console="Undefined".. when the whole html with the new comment data is regenerated once created, looks like it doesn't gives me the id of the new comment.. Like i said i have to refresh the page to edit or delete the new comments.

This is how i regenerate and create the new comments:

Ajax:

```<code>$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#add-comment').serialize();
   var $btn = $(this).button('loading');
   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
           $('#post-comments').append(
'<section class="comment-list'+data.id+'"><article class="row"><div class="col-md-2 col-sm-2 hidden-xs"><figure class="comment-list-image"><img class="img-responsive img-circle" src="/uploads/avatars/'+data.picture+'"/></figure></div><div class="col-md-9 col-sm-9"><div class="panel panel-default"><div class="panel-body"><header class="text-left"><div class="comment-user"><i class="fa fa-user"></i> '+data.name+' '+data.lastname+' <time class="comment-date p-l-10"><i class="fa fa-clock-o"></i> '+data.timestamp+'</time></div></header><div id="comment-post" data-commentid="'+data.id+'"><p id="display-comment" class="store-comment p-t-10">'+data.comment+'</p></div></div><div class="panel-footer list-inline comment-footer"><a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment" value="'+data.id+'" data-name="'+data.comment+'">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment"class="delete-comment" data-id="'+data.id+'" data-name="'+ data.comment+'">Eliminar</a></div></div></div></article></section>'
          );

            toastr.success('Comentario enviado.', '', {timeOut: 7000})
            $('#comment-new').val('');

         }
         else {
           toastr.warning(" "+ data.message +" ", '', {timeOut: 7000})
         }

      }, // <- La coma
      error: function () {
        toastr.warning('No hemos podido enviar el comentario, intenta nevamente.', '', {timeOut: 7000})
      }, // <- La coma
      complete: function () {
        $btn.button('reset');
      }
   });
});
</code>```

This is my create function in the controller:

```<code>public function store(Request $request, $post_id)
{
  if(!$request->has('comment') || empty($request->comment))
  {
    return response()->json([
      'message' => 'No puedes enviar un comentario vacío.',
      'success' => false
    ]);
  }

  $post = Post::find($post_id);
  $comment = new Comment();
  $comment->comment   = $request->comment;
  $comment->approved  = true;
  $comment->user_id   = auth()->id();
  $comment->user->profilepic = $comment->user->profilepic;
  $comment->post_id   = $post_id;
  $comment->save();
  return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'picture' => $comment->user->profilepic,
    'name'    => $comment->user->name,
    'lastname' => $comment->user->last_name,
    'timestamp' => $comment->created_at->diffForHumans(),
    'post_slug' => $post->slug,
    'success' => true
  ]);
}
</code>```

I wonder if there's a character limit when writing the new html. I get the whole code regenerated but i don't know, i needed to reduce some code lines because part of the code didn't get highlighted before..

答:
I guess it's because you are not using document in your javascript.

try this in all your ajax requests:

```<code>$(document).on('click', '.send', function(e){
    //your ajax code
});
</code>```

and also update or delete methodes:

```<code>$(document).on('click', '.edit', function(e){
    //your ajax code
});

$(document).on('click', '.delete', function(e){
    //your ajax code
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When i create a new comment it displays good but i can't edit it or delete, to do it i have to refresh the page first.. The reason? In console="Undefined".. when the whole html with the new comment data is regenerated once created, looks like it doesn't gives me the id of the new comment.. Like i said i have to refresh the page to edit or delete the new comments.

This is how i regenerate and create the new comments:

Ajax:

$('.send').click(function(e){
   e.preventDefault();
   var dataSerialize = $('#add-comment').serialize();
   var $btn = $(this).button('loading');
   $.ajax({
      method: 'post',
      url: urlPostComment,
      data: dataSerialize,
      dataType: 'json', // <- La coma
      success: function (data) {
         console.log(data); // <- Revisar JSON en la consola del navegador
         if( data.success )
         {
           $('#post-comments').append(
'

 '+data.name+' '+data.lastname+' <time class="comment-date p-l-10"> '+data.timestamp+'</time>

'+data.comment+'

Editar Eliminar

'
          );

            toastr.success('Comentario enviado.', '', {timeOut: 7000})
            $('#comment-new').val('');

         }
         else {
           toastr.warning(" "+ data.message +" ", '', {timeOut: 7000})
         }

      }, // <- La coma
      error: function () {
        toastr.warning('No hemos podido enviar el comentario, intenta nevamente.', '', {timeOut: 7000})
      }, // <- La coma
      complete: function () {
        $btn.button('reset');
      }
   });
});

This is my create function in the controller:

public function store(Request $request, $post_id)
{
  if(!$request->has('comment') || empty($request->comment))
  {
    return response()->json([
      'message' => 'No puedes enviar un comentario vacío.',
      'success' => false
    ]);
  }

  $post = Post::find($post_id);
  $comment = new Comment();
  $comment->comment   = $request->comment;
  $comment->approved  = true;
  $comment->user_id   = auth()->id();
  $comment->user->profilepic = $comment->user->profilepic;
  $comment->post_id   = $post_id;
  $comment->save();
  return response()->json([
    'comment' => $comment->comment,
    'user_id' => $comment->user_id,
    'post_id' => $comment->post_id,
    'picture' => $comment->user->profilepic,
    'name'    => $comment->user->name,
    'lastname' => $comment->user->last_name,
    'timestamp' => $comment->created_at->diffForHumans(),
    'post_slug' => $post->slug,
    'success' => true
  ]);
}

I wonder if there's a character limit when writing the new html. I get the whole code regenerated but i don't know, i needed to reduce some code lines because part of the code didn't get highlighted before..

Body:
I guess it's because you are not using document in your javascript.

try this in all your ajax requests:

$(document).on('click', '.send', function(e){
    //your ajax code
});

and also update or delete methodes:

$(document).on('click', '.edit', function(e){
    //your ajax code
});

$(document).on('click', '.delete', function(e){
    //your ajax code
});


问:
Number which occurs only once in the array

Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

```<code>a[1..n] = [1,2,3,4,3,1,2]
</code>```

should return 4

答:
Well i only know of the Brute force algo and it is to traverse whole array and check

Code will be like (in C#):

```<code>k=0;
for(int i=0 ; i < array.Length ; i++)
{
    k ^= array[i];
}
return k;
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  Finding a single number in a list

Given an array of numbers, except for one number all the others, occur
twice. What should be the algorithm to find that number which occurs only once in the
array?

Example

a[1..n] = [1,2,3,4,3,1,2]

should return 4

Body:
Well i only know of the Brute force algo and it is to traverse whole array and check

Code will be like (in C#):

k=0;
for(int i=0 ; i < array.Length ; i++)
{
    k ^= array[i];
}
return k;


问:
Python PPTX - How to set chart axis number format and range
I'm trying to accommodate a Bar Chart Y axis with a range from 0 to 1 with 1 decimal place like: 1.2 for tick labels:

I can set it to start at 0 with:

```<code> Thisvalue_axis.minimum_scale = 0
</code>```

And I can set the top value with:

```<code> Thisvalue_axis.major_unit = 1
</code>```

But the intermediate tick labels are not showing

here is my code:

```<code>Thisvalue_axis = ThisChart.value_axis
Thisvalue_axis.minimum_scale = 0
Thisvalue_axis.major_unit = 1
Thisvalue_axis.minor_tick_mark = XL_TICK_MARK.OUTSIDE
Thisvalue_axis.has_minor_gridlines = True
</code>```

Is it possible to Make the values between 0 and 1 display and set the numberformat?

答:
You should set the top value by using:

```<code>value_axis.maximum_scale = 1
</code>```

And then set the major unit to 0.1 or 0.2 or whatever suits:

```<code>value_axis.major_unit = 0.1
</code>```

This particular example would show 0.0, 0.1, 0.2, ... 1.0 as the tick mark labels.

Another look results from setting the major unit as 1 and setting the minor unit to 0.1 (or whatever you like). This would generally show a more prominent tick mark for the major unit and a less prominent one for the minor unit. Note however that tick labels only appear on the major tick marks.

The number format is set using the TickLabels object available on Axis.tick_labels:

```<code>value_axis.tick_labels.number_format = '0.0'
</code>```

Body:
I'm trying to accommodate a Bar Chart Y axis with a range from 0 to 1 with 1 decimal place like: 1.2 for tick labels:

I can set it to start at 0 with:

 Thisvalue_axis.minimum_scale = 0

And I can set the top value with:

 Thisvalue_axis.major_unit = 1

But the intermediate tick labels are not showing

here is my code:

Thisvalue_axis = ThisChart.value_axis
Thisvalue_axis.minimum_scale = 0
Thisvalue_axis.major_unit = 1
Thisvalue_axis.minor_tick_mark = XL_TICK_MARK.OUTSIDE
Thisvalue_axis.has_minor_gridlines = True

Is it possible to Make the values between 0 and 1 display and set the numberformat?

Body:
You should set the top value by using:

value_axis.maximum_scale = 1

And then set the major unit to 0.1 or 0.2 or whatever suits:

value_axis.major_unit = 0.1

This particular example would show 0.0, 0.1, 0.2, ... 1.0 as the tick mark labels.

Another look results from setting the major unit as 1 and setting the minor unit to 0.1 (or whatever you like). This would generally show a more prominent tick mark for the major unit and a less prominent one for the minor unit. Note however that tick labels only appear on the major tick marks.

The number format is set using the TickLabels object available on Axis.tick_labels:

value_axis.tick_labels.number_format = '0.0'


问:
How to arrange firebase database data in ascending or descending order?
I have setup a firebase database and I was wondering how I'd make it so that my listView shows my data in ascending or descending order.

For example: if I wanted something thats the most expensive I'd have it at the top of my listView and the cheaper ones at the bottom.

Basically I'm trying to create a ranking activity where I've two seperate listviews that rank by cost and count individually.

This is what I have for my count:

```<code>  @Override
    protected void onStart() {
        super.onStart();

        itemlists=new ArrayList<String>();
        databaseItems.child("items").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
                    String itemname=itemSnapShot.child("itemName").getValue().toString();

                    itemlists.add(itemname);
                    adapter = new ArrayAdapter(SearchActivity.this,android.R.layout.simple_list_item_1,itemlists);
                    listFinalCount.setAdapter(adapter);

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }
</code>```

答:
If you want to order the results of a Firebase database query, you need to use numbers as values and not Strings. If you keep the Strings, as I see in your screenshot, you need to know that the Strings are ordered lexicographically and I'm sure this is not what you are looking for.

The simplest way to order data in ascending or descending order, would be on client side. Firebase can order the results in ascending order by a given property by default. There is no method in Firebase to order in descending order but there a few tweaks that can be made.

If you are using a RecyclerView to display data, the simplest way would be to use the following code:

```<code>LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);
</code>```

This approch will reverse you the order.

Another approach would be to create your own adapter that extends FirebaseListAdapter and override getItem() method.

Another approach would be to get the data from the database, add it to a Collection, a List would be a good solution and then use Collections.reverse(yourList);.

Body:
I have setup a firebase database and I was wondering how I'd make it so that my listView shows my data in ascending or descending order.

For example: if I wanted something thats the most expensive I'd have it at the top of my listView and the cheaper ones at the bottom.

Basically I'm trying to create a ranking activity where I've two seperate listviews that rank by cost and count individually.

This is what I have for my count:

  @Override
    protected void onStart() {
        super.onStart();

        itemlists=new ArrayList<String>();
        databaseItems.child("items").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot itemSnapShot : dataSnapshot.getChildren()) {
                    String itemname=itemSnapShot.child("itemName").getValue().toString();

                    itemlists.add(itemname);
                    adapter = new ArrayAdapter(SearchActivity.this,android.R.layout.simple_list_item_1,itemlists);
                    listFinalCount.setAdapter(adapter);

                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

Body:
If you want to order the results of a Firebase database query, you need to use numbers as values and not Strings. If you keep the Strings, as I see in your screenshot, you need to know that the Strings are ordered lexicographically and I'm sure this is not what you are looking for.

The simplest way to order data in ascending or descending order, would be on client side. Firebase can order the results in ascending order by a given property by default. There is no method in Firebase to order in descending order but there a few tweaks that can be made.

If you are using a RecyclerView to display data, the simplest way would be to use the following code:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(layoutManager);

This approch will reverse you the order.

Another approach would be to create your own adapter that extends FirebaseListAdapter and override getItem() method.

Another approach would be to get the data from the database, add it to a Collection, a List would be a good solution and then use Collections.reverse(yourList);.

ContentLicense: CC BY-SA 4.0


问:
Is there a way to make drawRect work right NOW?
If you are an advanced user of drawRect, you will know that of course drawRect will not actually run until "all processing is finished."

setNeedsDisplay flags a view as invalidated and the OS, and basically waits until all processing is done. This can be infuriating in the common situation where you want to have:

a view controller 1

starts some function 2

which incrementally 3

creates a more and more complicated artwork and 4

at each step, you setNeedsDisplay (wrong!) 5

until all the work is done 6

Of course, when you do the above 1-6, all that happens is that drawRect is run once only after step 6.

Your goal is for the view to be refreshed at point 5. What to do?

答:
You can do this repeatedly in a loop and it'll work fine, no threads, no messing with the runloop, etc.

```<code>[CATransaction begin];
// modify view or views
[view setNeedsDisplay];
[CATransaction commit];
</code>```

If there is an implicit transaction already in place prior to the loop you need to commit that with [CATransaction commit] before this will work.

Body:
You can do this repeatedly in a loop and it'll work fine, no threads, no messing with the runloop, etc.

[CATransaction begin];
// modify view or views
[view setNeedsDisplay];
[CATransaction commit];

If there is an implicit transaction already in place prior to the loop you need to commit that with [CATransaction commit] before this will work.


问:
Constraint Layout measures incorrect height if it is nested into scrollview

```<code><android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

///Content

    </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>
</code>```

In this case constraint layout to long. I also have problem with marginEnd of child views. I have a lot of child views similar to

```<code> <TextView
            android:id="@+id/tvDurationPlan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_medium"
            android:textSize="@dimen/txt_size_small"
            style="@style/WhiteTextViewStyle"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="@+id/tvPlanLabel"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvPlanLabel"
            app:layout_constraintVertical_bias="0.0"
            android:layout_marginEnd="16dp"
            tools:text="TextView" />
</code>```

and layout_marginEnd doesn't work.
Please help me!

答: as I could say, this bug was fixed in com.android.support.constraint:constraint-layout:1.1.0-beta3</p>

Body:
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

///Content

    </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>

In this case constraint layout to long. I also have problem with marginEnd of child views. I have a lot of child views similar to

 <TextView
            android:id="@+id/tvDurationPlan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/margin_medium"
            android:textSize="@dimen/txt_size_small"
            style="@style/WhiteTextViewStyle"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="@+id/tvPlanLabel"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvPlanLabel"
            app:layout_constraintVertical_bias="0.0"
            android:layout_marginEnd="16dp"
            tools:text="TextView" />

and layout_marginEnd doesn't work.
Please help me!


问:
Design Pattern to handle actions based on multiple inputs in C#
Let's say that there are two properties in a business model for eg., country and type, and we need to handle different logic for each country and for each type.

```<code>if(country=="us"){
    if(type=="type1){
        usType1Handler.Execute();
    }
    else if(type=="type2"){
        usType2Handler.Execute();
    }
    .
    .
    .
    else{
        usDefaultHandler.Execute();
    }
}
else if(country=="uk"){
    if(type=="type1){
        ukType1Handler.Execute();
    }
    else if(type=="type2"){
        ukType2Handler.Execute();
    }
    .
    .
    .
    else{
        ukDefaultHandler.Execute();
    }
}
else{
    throw exception("unknown country");
}
</code>```

There will be lot of if's to mix and match the each implementation specific to each country type combination. Is there any design pattern we can use to handle this scenario?

答:
I would recommend in this instance to use a nested switch:</p>

```<code>switch (country)
{
    case "us":
        switch (type)
        {
            case "type1":
                usType1Handler.Execute();
                break;
            case "type2":
                usType2Handler.Execute();
                break;
            default:
                break;
        }
        break;
    case "uk":
        switch (type)
        {
            case "type1":
                ukType1Handler.Execute();
                break;
            case "type2":
                ukType2Handler.Execute();
                break;
            default:
                break;
        }
        break;
}
</code>```

Body:
Let's say that there are two properties in a business model for eg., country and type, and we need to handle different logic for each country and for each type.

if(country=="us"){
    if(type=="type1){
        usType1Handler.Execute();
    }
    else if(type=="type2"){
        usType2Handler.Execute();
    }
    .
    .
    .
    else{
        usDefaultHandler.Execute();
    }
}
else if(country=="uk"){
    if(type=="type1){
        ukType1Handler.Execute();
    }
    else if(type=="type2"){
        ukType2Handler.Execute();
    }
    .
    .
    .
    else{
        ukDefaultHandler.Execute();
    }
}
else{
    throw exception("unknown country");
}

There will be lot of if's to mix and match the each implementation specific to each country type combination. Is there any design pattern we can use to handle this scenario?

Body:
I would recommend in this instance to use a nested switch:

switch (country)
{
    case "us":
        switch (type)
        {
            case "type1":
                usType1Handler.Execute();
                break;
            case "type2":
                usType2Handler.Execute();
                break;
            default:
                break;
        }
        break;
    case "uk":
        switch (type)
        {
            case "type1":
                ukType1Handler.Execute();
                break;
            case "type2":
                ukType2Handler.Execute();
                break;
            default:
                break;
        }
        break;
}


问:
How array of uibutton to apply different colors each
I would like to apply different color (by the code) at different uiButton.
I thinked to create 2 arrays. The first with my uiButtons, and the other with differents colors.
After that, to make a first loop with my buttons, and inside this loop, to make an other loop with the colors (random result). The last step, apply the colors at the button.
Can this way work?</p>

答:
You can try this.Its working code just call the method from viewDidLoad and see how it works

```<code>func createButtonsWithDifferentTitleColor(){
    // create array of different colors
    let colorArray = [UIColor.red,UIColor.green,UIColor.blue,UIColor.brown,UIColor.purple]

    for i in 0...colorArray.count-1 {
        let button = UIButton(frame: CGRect(x: 0, y: i*55, width: 130, height: 50))
        //set different title colors for each button
        button.setTitleColor(colorArray[i], for: .normal)
        // set different title for button
        button.setTitle("Button No \(i+1)", for: .normal)
         // add all buttons to main view, so that they can be visible
        view.addSubview(button)

    }

}
</code>```

For setting random color you ned to do some thing like this

```<code> func createButtonsWithDifferentTitleColor(){
    // create array of different colors
    let colorArray = [UIColor.red,UIColor.green,UIColor.blue,UIColor.brown,UIColor.purple]

    for i in 0...colorArray.count-1 {
        let button = UIButton(frame: CGRect(x: 0, y: i*55, width: 130, height: 50))
        // generate random index
        let index = Int(arc4random_uniform(UInt32(colorArray.count)));
        //set different title color for each button
        button.setTitleColor(colorArray[index], for: .normal)
        // set different title for button
        button.setTitle("Button No \(i+1)", for: .normal)
         // add all buttons to main view, so that they can be visible
        view.addSubview(button)

    }

}
</code>```

Body:
You can try this.Its working code just call the method from viewDidLoad and see how it works

func createButtonsWithDifferentTitleColor(){
    // create array of different colors
    let colorArray = [UIColor.red,UIColor.green,UIColor.blue,UIColor.brown,UIColor.purple]

    for i in 0...colorArray.count-1 {
        let button = UIButton(frame: CGRect(x: 0, y: i*55, width: 130, height: 50))
        //set different title colors for each button
        button.setTitleColor(colorArray[i], for: .normal)
        // set different title for button
        button.setTitle("Button No \(i+1)", for: .normal)
         // add all buttons to main view, so that they can be visible
        view.addSubview(button)

    }

}

For setting random color you ned to do some thing like this

 func createButtonsWithDifferentTitleColor(){
    // create array of different colors
    let colorArray = [UIColor.red,UIColor.green,UIColor.blue,UIColor.brown,UIColor.purple]

    for i in 0...colorArray.count-1 {
        let button = UIButton(frame: CGRect(x: 0, y: i*55, width: 130, height: 50))
        // generate random index
        let index = Int(arc4random_uniform(UInt32(colorArray.count)));
        //set different title color for each button
        button.setTitleColor(colorArray[index], for: .normal)
        // set different title for button
        button.setTitle("Button No \(i+1)", for: .normal)
         // add all buttons to main view, so that they can be visible
        view.addSubview(button)

    }

}


问:
How to process POST data from Golang into PHP using Wordpress
I am trying to call a PHP post api in Golang using HTTP package with some post values. After sending these parameters from Golang I am trying to get it into PHP $_POST array in Wordpress. But I am not able to access any index of $_POST array in PHP code.

Here is my code:

```<code>func SaveProviderInGlobalDb(providerId int, providerEmail string, businessName string) (*http.Response, error){
    postValues := url.Values{}
    providerIdString := strconv.Itoa(providerId)
    postValues.Add("provider_id", providerIdString)
    postValues.Add("provider_email", providerEmail)
    postValues.Add("business_name", businessName)
    response, err := http.PostForm("http://localhost/provider.php", postValues)
    return response, err
}
</code>```

PHP code:

```<code>if(isset($_POST) && count($_POST) > 0){
    if(isset($_POST["business_name"]) && $_POST["business_name"] != ''){
        $providersCount = GetProviderCount($_POST["business_name"], $_POST["provider_email"]);
        if($providersCount > 0) {
            $response["response"] = "This provider is already registered for ".$_POST["business_name"];
            $response["code"] = 400;
        }else{
            $result = SaveProvider($_POST);
            if($result){
                $response["response"] = "Provider saved successfully.";
                $response["code"] = 200;
            }else{
                $response["response"] = "Error while saving provider.";
                $response["code"] = 400;
            }
        }
    }else {
        $response["response"] = "No merchant found.";
        $response["code"] = 400;
    }
    echo json_encode($response);
}
</code>```

In the above PHP code I am not able to check if "business_name" is set in $_POST or not. Due to this, It always gives me error message that "No merchant found."

EDITED

```<code>Array
(
    [------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition:_form-data;_name] => \"provider_email\"

john_doe_1234@example.com
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"provider_id\"

54
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"business_name\"

testkom1
------WebKitFormBoundaryGPuoAolbEsWBZnVh--

)
</code>```

It is the response which I am getting after printing $_POST.

Can anyone tell me how do I solve this problem ?

Thanks!

答:
Actually I have accidentally passed x-WWW-form-urlencoded headers in post request. Due to this it was generating output like above. When I removed this header, It worked fine.

Thanks!

Body:
I am trying to call a PHP post api in Golang using HTTP package with some post values. After sending these parameters from Golang I am trying to get it into PHP $_POST array in Wordpress. But I am not able to access any index of $_POST array in PHP code.

Here is my code:

func SaveProviderInGlobalDb(providerId int, providerEmail string, businessName string) (*http.Response, error){
    postValues := url.Values{}
    providerIdString := strconv.Itoa(providerId)
    postValues.Add("provider_id", providerIdString)
    postValues.Add("provider_email", providerEmail)
    postValues.Add("business_name", businessName)
    response, err := http.PostForm("http://localhost/provider.php", postValues)
    return response, err
}

PHP code:

if(isset($_POST) && count($_POST) > 0){
    if(isset($_POST["business_name"]) && $_POST["business_name"] != ''){
        $providersCount = GetProviderCount($_POST["business_name"], $_POST["provider_email"]);
        if($providersCount > 0) {
            $response["response"] = "This provider is already registered for ".$_POST["business_name"];
            $response["code"] = 400;
        }else{
            $result = SaveProvider($_POST);
            if($result){
                $response["response"] = "Provider saved successfully.";
                $response["code"] = 200;
            }else{
                $response["response"] = "Error while saving provider.";
                $response["code"] = 400;
            }
        }
    }else {
        $response["response"] = "No merchant found.";
        $response["code"] = 400;
    }
    echo json_encode($response);
}

In the above PHP code I am not able to check if "business_name" is set in $_POST or not. Due to this, It always gives me error message that "No merchant found."

EDITED

Array
(
    [------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition:_form-data;_name] => \"provider_email\"

john_doe_1234@example.com
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"provider_id\"

54
------WebKitFormBoundaryGPuoAolbEsWBZnVh
Content-Disposition: form-data; name=\"business_name\"

testkom1
------WebKitFormBoundaryGPuoAolbEsWBZnVh--

)

It is the response which I am getting after printing $_POST.

Can anyone tell me how do I solve this problem ?

Thanks!


问:
Batch file script to register specific dll in a folder not all dll
I have about 5-10 DLL out of 100 which are to be registered during the build and unregistered after the whole build is completed, all DLL are in a single folder. For registering I wrote a post build event , but now to unregistered just these 5-10 DLL out of 100 can't seem to get any idea, I am new to batch script so get confused early. I searched some places, but all show how to register/unregistered all files in folder not specific DLL writing a prebuild event to unregister doesn't seem to work in case of rebuild option used to build solution

答:
here is a way to do it with a text file containing *.dll names to Register Unregister

```<code>@echo off

::For /f will look for *.dll names in files.txt
::Than Do register/unregister *.dll as specified in regsvr32
::

for /f %%i in (files.txt) do regsvr32 /u /s C:\Windows\System32\%%i

exit
</code>```

For /? for help

usage

FOR /F  %variable IN (file-set) DO command [command-parameters]

RegSvr32 command usage

```<code>Usage: regsvr32 [/u] [/s] [/n] [/i[:cmdline]] dllname
/u -    Unregister server
/s -    Silent; display no message boxes
/i -    Call DllInstall passing it an optional [cmdline]; when used with /u calls dll uninstall
/n -    do not call DllRegisterServer; this option must be used with /i
</code>```

Body:
here is a way to do it with a text file containing *.dll names to Register Unregister

@echo off

::For /f will look for *.dll names in files.txt
::Than Do register/unregister *.dll as specified in regsvr32
::

for /f %%i in (files.txt) do regsvr32 /u /s C:\Windows\System32\%%i

exit

For /? for help

usage

FOR /F  %variable IN (file-set) DO command [command-parameters]

RegSvr32 command usage

Usage: regsvr32 [/u] [/s] [/n] [/i[:cmdline]] dllname
/u -    Unregister server
/s -    Silent; display no message boxes
/i -    Call DllInstall passing it an optional [cmdline]; when used with /u calls dll uninstall
/n -    do not call DllRegisterServer; this option must be used with /i


问:
How to run Jquery after Ajax DOM Holder complete loading?
I have page with two tabs; one of them randomly will be active and its date will be loaded by default. The second tab, will be inactive until the user will click it then it will load the content using Ajax. (never been loaded yet)

All what I need to do is to fire this code in both tabs:

```<code>$('#listings').attr('class', 'mobile row');
</code>```

But I fail to make it run in the inactive tab as the JQuery always stop before Ajax complete loading.

This is the tab HTML code:

```<code><ul class="tabs tabs-hash">
  <li class="" id="tab_listings" lang="listings">
    <a href="#listings" data-target="listings">Property</a>
  </li>
  <li class="active" id="tab_automobile" lang="automobile">
    <a href="#automobile" data-target="automobile">Vehicles</a>
  </li>
</ul>
</code>```

And this is the content will show when each tab will clicked:

Tab#1 (Active)

```<code><div class="tab_area" id="area_automobile" style="display: block;">
  <section id="listings" class="mobile row">
    some content here
  </section>
</div>
</code>```

Tab#2 (Inactive)

```<code><div class="tab_area hide" id="area_listings" style="display: none;">
    <span class="text-notice">**Loading...** </span><!-- This span is loading content using Ajax and JQuery finish before its complete and this content will have new section with the target class need to be changed by Jquery -->
</div>
</code>```

Once Inactive tab become Active and Ajax complete loading

this section will appear and the class="mobile row" need to be changed

```<code>  <section id="listings" class="mobile row">
    some content here
  </section>
</code>```

I tried to search Stack Overflow but all the post I found did not solve my problem.

Is it possible someone can explain a way to achieve target?

答:
After deep search, I found the solution did what I want in mozilla.org

Which explained there in details, but the short summary its the way to  instantiating new DOM mutation observers with compatibility with all new major browser.

So, If the DOM class, id, attributes, etc... will appear in the future  MutationObserver will detected it and apply the rule (we can stop it any time) and its support:

child elements target's

Attributes target's

Data target's descendants

Attribute value

Data before the mutation (Past/Old data)

Local names (without namespace)

The code I used to complete the above target as the following:

```<code>var observer = new MutationObserver(function(mutations) {
 mutations.forEach(function(mutation) {
  if (!mutation.addedNodes) return
  for (var i = 0; i < mutation.addedNodes.length; i++) {
   $('section#listings').attr('class', 'mobile row');
   var node = mutation.addedNodes[i]
  }
 })
})
 observer.observe(document.body, {
  childList: true
  , subtree: true
  , attributes: false
  , characterData: false
 })
</code>```

I hope this can help others and for me this is the best solution for now unless some one else  give me extra help and better advise.

NOTE:
The above code, is taken from one post of Stackoverflow posts, unfortunately,
By mistake I closed the tab of my browser, and I coudl't get the post back even by search on Google. I wish if I could gave credit to the adviser with this code, and I should say thank you for both, StackOverFlow, and The code maker.

Edited:
I change the Class attr. code to be like this:

```<code>$('section.list').attr('class', 'mobile row');
</code>```

As my page include 3 section with the same #ID and this cause the JQuery to stop once he found ID match but not with the Class(s)
Tariq

Body:
I have page with two tabs; one of them randomly will be active and its date will be loaded by default. The second tab, will be inactive until the user will click it then it will load the content using Ajax. (never been loaded yet)

All what I need to do is to fire this code in both tabs:

$('#listings').attr('class', 'mobile row');

But I fail to make it run in the inactive tab as the JQuery always stop before Ajax complete loading.

This is the tab HTML code:

    Property

    Vehicles

And this is the content will show when each tab will clicked:

Tab#1 (Active)

    some content here

Tab#2 (Inactive)

    **Loading...**

Once Inactive tab become Active and Ajax complete loading

this section will appear and the class="mobile row" need to be changed

    some content here

I tried to search Stack Overflow but all the post I found did not solve my problem.

Is it possible someone can explain a way to achieve target?

Body:
After deep search, I found the solution did what I want in mozilla.org

Which explained there in details, but the short summary its the way to  instantiating new DOM mutation observers with compatibility with all new major browser.

So, If the DOM class, id, attributes, etc... will appear in the future  MutationObserver will detected it and apply the rule (we can stop it any time) and its support:

child elements target's

Attributes target's

Data target's descendants

Attribute value

Data before the mutation (Past/Old data)

Local names (without namespace)

The code I used to complete the above target as the following:

var observer = new MutationObserver(function(mutations) {
 mutations.forEach(function(mutation) {
  if (!mutation.addedNodes) return
  for (var i = 0; i < mutation.addedNodes.length; i++) {
   $('section#listings').attr('class', 'mobile row');
   var node = mutation.addedNodes[i]
  }
 })
})
 observer.observe(document.body, {
  childList: true
  , subtree: true
  , attributes: false
  , characterData: false
 })

I hope this can help others and for me this is the best solution for now unless some one else  give me extra help and better advise.

NOTE:
The above code, is taken from one post of Stackoverflow posts, unfortunately,
By mistake I closed the tab of my browser, and I coudl't get the post back even by search on Google. I wish if I could gave credit to the adviser with this code, and I should say thank you for both, StackOverFlow, and The code maker.

Edited:
I change the Class attr. code to be like this:

$('section.list').attr('class', 'mobile row');

As my page include 3 section with the same #ID and this cause the JQuery to stop once he found ID match but not with the Class(s)
Tariq


问:
How to make two buttons on the same row in eclipse programmatically?
```<code>LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);
</code>```

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:

答:
use table.setOrientation(LinearLayout.HORIZONTAL); .

Hope it Helps.

Body:
LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);

btnControl = new Button(this);
    btnControl.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnControl.setPadding(0,40,0,40);//x,y,w,h
    btnControl.setBackgroundColor(Color.parseColor("#1C344E"));
    btnControl.setTextColor(Color.WHITE);
    setMargins(btnControl, 50, 50, 50, 50);

btnLogs = new Button(this);
        btnLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnLogs.setPadding(0,40,0,40);//x,y,w,h
        btnLogs.setBackgroundColor(Color.parseColor("#1C344E"));
        btnLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnLogs.setId(5);
        btnLogs.setOnClickListener(this);

        btnTermLogs = new Button(this);
        btnTermLogs.setLayoutParams(new LayoutParams(380, LayoutParams.WRAP_CONTENT));
        btnTermLogs.setPadding(0,40,0,40);//x,y,w,h
        btnTermLogs.setBackgroundColor(Color.parseColor("#CC6675"));
        btnTermLogs.setTextColor(Color.WHITE);
        setMargins(btnLogs, 50, 50, 50, 50);
        btnTermLogs.setId(6);
        btnTermLogs.setOnClickListener(this);

btnLogout = new Button(this);
    btnLogout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    btnLogout.setPadding(0,40,0,40);//x,y,w,h
    btnLogout.setBackgroundColor(Color.parseColor("#CC6675"));
    btnLogout.setTextColor(Color.WHITE);

    table.addView(btnLogs);
        table.addView(btnTermLogs);

I want the two buttons to be aligned together horizontally. However it just align themselves vertically which i dont want.

My buttons look like this:

what i want is to look like this:


问:
constraint layout inside scrollview white space at bottom?
I am using Scroll View inside constraint layout and it generate white space at the bottom
 XML code  Here

答: this bug was fixed in com.android.support.constraint:constraint-layout:1.1.0-beta3, but some other bugs added - for example after shared element transition constraint braking for my list element</p>


问:
codeigniter active record against match error
why this will make an error?

```<code>$this->db->where('MATCH (title) AGAINST ("stackoverflow")', NULL, TRUE);
</code>```

You have an error in your SQL syntax;
  check the manual that corresponds to
  your MySQL server version for the
  right syntax to use near 'AGAINST
  ("stackoverflow") LIMIT 4' at line 3

SELECT * FROM (table) WHERE MATCH
  (title) AGAINST ("stackoverflow")
  LIMIT 4

when change to FALSE,the query will ok,but i want to protect mytable with with backticks

答:
Standard SQL uses single quotes, not double quotes.

```<code>MATCH (title) AGAINST ('stackoverflow')
</code>```

You can test whether this is really the problem with a string as your WHERE clause.

```<code>$where = "MATCH (title) AGAINST ('stackoverflow') LIMIT 4";
$this->db->where($where);
</code>```

Body:
why this will make an error?

$this->db->where('MATCH (title) AGAINST ("stackoverflow")', NULL, TRUE);

You have an error in your SQL syntax;
  check the manual that corresponds to
  your MySQL server version for the
  right syntax to use near 'AGAINST
  ("stackoverflow") LIMIT 4' at line 3

SELECT * FROM (table) WHERE MATCH
  (title) AGAINST ("stackoverflow")
  LIMIT 4

when change to FALSE,the query will ok,but i want to protect mytable with with backticks

Body:
Standard SQL uses single quotes, not double quotes.

MATCH (title) AGAINST ('stackoverflow')

You can test whether this is really the problem with a string as your WHERE clause.

$where = "MATCH (title) AGAINST ('stackoverflow') LIMIT 4";
$this->db->where($where);


问:
OpenCV, How to pass parameters into cv2.TrackerMedianFlow_create function?
I'm trying to create MEDIANFLOW tracker with OpenCV3.3 using opencv-python with Python3.6. I need to pass some arguments into the constructor according to this page of OpenCV docs.

The problem is I don't know how to pass available arguments into this function correctly? I wasn't able to find any information about it.

What I do (and it works):

```<code>tracker = cv2.TrackerMedianFlow_create()
</code>```

What I want to do:

```<code>tracker = cv2.TrackerMedianFlow_create(maxLevel=3)
</code>```

But it doesn't work and gives me an error:

```<code>SystemError: <built-in function TrackerMedianFlow_create> returned NULL without setting an error
</code>```

Could you help?

答:
I search the intermediate code generated by cmake/make when compiling the OpenCV 3.3 for Python 3.5, just cannot find the methods to set the parameters for cv2.TrackerXXX.

In modules/python3/pyopencv_generated_funcs.h, I find this function:

```<code>static PyObject* pyopencv_cv_TrackerMedianFlow_create(PyObject* , PyObject* args, PyObject* kw)
{
    using namespace cv;

    Ptr<TrackerMedianFlow> retval;

    if(PyObject_Size(args) == 0 && (kw == NULL || PyObject_Size(kw) == 0))
    {
        ERRWRAP2(retval = cv::TrackerMedianFlow::create());
        return pyopencv_from(retval);
    }

    return NULL;
}
</code>```

This is to say, you cann't pass any parameter to cv::TrackerMedianFlow_create().

In modules/python3/pyopencv_generated_types.h, I find this one:

```<code>static PyGetSetDef pyopencv_TrackerMedianFlow_getseters[] =
{
    {NULL}  /* Sentinel */
};
</code>```

This to say, you have no way to change the parameters for Python wrapper by default, Unless you modified the source code and recompile it.

Body:
I'm trying to create MEDIANFLOW tracker with OpenCV3.3 using opencv-python with Python3.6. I need to pass some arguments into the constructor according to this page of OpenCV docs.

The problem is I don't know how to pass available arguments into this function correctly? I wasn't able to find any information about it.

What I do (and it works):

tracker = cv2.TrackerMedianFlow_create()

What I want to do:

tracker = cv2.TrackerMedianFlow_create(maxLevel=3)

But it doesn't work and gives me an error:

SystemError: <built-in function TrackerMedianFlow_create> returned NULL without setting an error

Could you help?

Body:
I search the intermediate code generated by cmake/make when compiling the OpenCV 3.3 for Python 3.5, just cannot find the methods to set the parameters for cv2.TrackerXXX.

In modules/python3/pyopencv_generated_funcs.h, I find this function:

static PyObject* pyopencv_cv_TrackerMedianFlow_create(PyObject* , PyObject* args, PyObject* kw)
{
    using namespace cv;

    Ptr<TrackerMedianFlow> retval;

    if(PyObject_Size(args) == 0 && (kw == NULL || PyObject_Size(kw) == 0))
    {
        ERRWRAP2(retval = cv::TrackerMedianFlow::create());
        return pyopencv_from(retval);
    }

    return NULL;
}

This is to say, you cann't pass any parameter to cv::TrackerMedianFlow_create().

In modules/python3/pyopencv_generated_types.h, I find this one:

static PyGetSetDef pyopencv_TrackerMedianFlow_getseters[] =
{
    {NULL}  /* Sentinel */
};

This to say, you have no way to change the parameters for Python wrapper by default, Unless you modified the source code and recompile it.


问:
Install TensorFlow's tf-nightly and tf-nightly-gpu on macOS
I have run into a known issue with TensorFlow 1.4 and Python 3.6, which manifests itself by this RuntimeWarning:

```<code>compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util'
does not match runtime version 3.6
</code>```

I would like to overcome by installing the latest tf-nightly and tf-nightly-gpu, as currently recommended. So far, I have so far followed normal instructions for installing TensorFlow (on macOS) like so:

```<code>virtualenv --system-site-packages ~/tensorflow
source ~/tensorflow/bin/activate
(tensorflow)$ easy_install -U pip
(tensorflow)$ pip install --upgrade tensorflow
</code>```

What (minimal) changes to these steps so that they perform installation from tf-nightly and tf-nightly-gpu?

答: Using command pip install tf-nightly instead of pip install --upgrade tensorflow seems to work. It currently leads to installation from tf_nightly-1.5.0.dev20171206-cp36-cp36m-macosx_10_11_x86_64.whl.

Body:
I have run into a known issue with TensorFlow 1.4 and Python 3.6, which manifests itself by this RuntimeWarning:

compiletime version 3.5 of module 'tensorflow.python.framework.fast_tensor_util'
does not match runtime version 3.6

I would like to overcome by installing the latest tf-nightly and tf-nightly-gpu, as currently recommended. So far, I have so far followed normal instructions for installing TensorFlow (on macOS) like so:

virtualenv --system-site-packages ~/tensorflow
source ~/tensorflow/bin/activate
(tensorflow)$ easy_install -U pip
(tensorflow)$ pip install --upgrade tensorflow

What (minimal) changes to these steps so that they perform installation from tf-nightly and tf-nightly-gpu?


问:
Plot line from pandas dataframe in Python
I have the dataframe below in pandas currently

```<code>|  x  | ID   | Num
|-----|------|-----
|  1  | 100  | 35
|  2  | 100  | 50
|  3  | 150  | 34
|  4  | 150  | 25
|  5  | 150  | 46
|  6  | 200  | 13
|  7  | 200  | 75
|  8  | 100  | 37
|  9  | 150  | 61
</code>```

I'm trying to create a multi-line graph where the 'x' column is the index and on the x-axis, while the ID and Num columns form the lines.

I tried to do a single line version with just x and ID with the following code, but it returns nothing, and I'm not sure how to upgrade to a two line graph.

```<code>s1 = df_iter.resample('LowestAcceptedValue')
s2 = df_iter.resample('SwapsValue')
df = pd.concat([s1, s2], axis=1)
df.plot()
</code>```

答:
Use set_index to put x as the data frame index, then plot the rest:

```<code>import matplotlib.pyplot as plt

df.set_index('x').plot()

plt.show()
</code>```

Body:
I have the dataframe below in pandas currently

|  x  | ID   | Num
|-----|------|-----
|  1  | 100  | 35
|  2  | 100  | 50
|  3  | 150  | 34
|  4  | 150  | 25
|  5  | 150  | 46
|  6  | 200  | 13
|  7  | 200  | 75
|  8  | 100  | 37
|  9  | 150  | 61

I'm trying to create a multi-line graph where the 'x' column is the index and on the x-axis, while the ID and Num columns form the lines.

I tried to do a single line version with just x and ID with the following code, but it returns nothing, and I'm not sure how to upgrade to a two line graph.

s1 = df_iter.resample('LowestAcceptedValue')
s2 = df_iter.resample('SwapsValue')
df = pd.concat([s1, s2], axis=1)
df.plot()

Body:
Use set_index to put x as the data frame index, then plot the rest:

import matplotlib.pyplot as plt

df.set_index('x').plot()

plt.show()


问:
Pick one value from multiple values satisfying a condition
Suppose I have a list like this:

```<code>a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']
</code>```

Then the output should be:

```<code>new_list = ['eddy','dye','ed']
</code>```

First element will always be taken (i.e. 'eddy') and then the length of the next element should be one less character than the previous element (in this case, length of 'dye' is one less character than that of 'eddy' and so on). I only need first element satisfying the condition. (no need of 'dey' even though it is satisfying the condition. Need only one element satisfying the condition)

There can be multiple ways to implement this but I can't seem to find a way to implement it correctly. Below is what I've tried so far.

```<code>a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']
temp=[a[0]] #first element will always be taken
i=0

while i<len(a):
  if len(a[i]) == len(temp[0])-1:
     temp.append(a[i])
  i+=1
</code>```

This is giving me below output which is not correct:

```<code>['eddy', 'dye', 'dey']
</code>```

@Mad Physicist: I provided below list:

```<code>    a=['abaca', 'baa', 'cab', 'aba', 'ab', 'ba', 'aa']
</code>```

It gave me below output:

```<code>    ['abaca']
</code>```

答:
This is happening because in your if statement, it's always checking against the length of the first element, not the new 'length' that it should be using. Thus, you keep grabbing elements of length 3.

```<code>newIndex = 0
while i < len(a):
  if len(a[i]) == len(temp[newIndex])-1:
     temp.append(a[i])
     newIndex = i
  i+=1
</code>```

Try that out.

Body:
Suppose I have a list like this:

a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']

Then the output should be:

new_list = ['eddy','dye','ed']

First element will always be taken (i.e. 'eddy') and then the length of the next element should be one less character than the previous element (in this case, length of 'dye' is one less character than that of 'eddy' and so on). I only need first element satisfying the condition. (no need of 'dey' even though it is satisfying the condition. Need only one element satisfying the condition)

There can be multiple ways to implement this but I can't seem to find a way to implement it correctly. Below is what I've tried so far.

a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']
temp=[a[0]] #first element will always be taken
i=0

while i<len(a):
  if len(a[i]) == len(temp[0])-1:
     temp.append(a[i])
  i+=1

This is giving me below output which is not correct:

['eddy', 'dye', 'dey']

@Mad Physicist: I provided below list:

    a=['abaca', 'baa', 'cab', 'aba', 'ab', 'ba', 'aa']

It gave me below output:

    ['abaca']

Body:
This is happening because in your if statement, it's always checking against the length of the first element, not the new 'length' that it should be using. Thus, you keep grabbing elements of length 3.

newIndex = 0
while i < len(a):
  if len(a[i]) == len(temp[newIndex])-1:
     temp.append(a[i])
     newIndex = i
  i+=1

Try that out.


答:
You should use setLayoutParams

Add setOrientation(LinearLayout.HORIZONTAL);

Set the layout parameters associated with this view. These supply
  parameters to the parent of this view specifying how it should be
  arranged. There are many subclasses of ViewGroup.LayoutParams, and
  these correspond to the different subclasses of ViewGroup that are
  responsible for arranging their children.

Code Structure

```<code>    LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);
    table.setOrientation(LinearLayout.HORIZONTAL);

    Button Btn1 = new Button(Activity.this);
    Btn1.setText("Button 1");
    LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    childParam.weight = 0.5f;
    Btn1.setLayoutParams(childParam);

    Button Btn2 = new Button(Activity.this);
    Btn2.setText("Button 2");
    LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    childParam2.weight = 0.5f;
    Btn2.setLayoutParams(childParam2);

    table.addView(Btn1);
    table.addView(Btn2);
</code>```

Respected OP

Title: How to make two buttons on the same row in eclipse programmatically?

Body:
You should use setLayoutParams

Add setOrientation(LinearLayout.HORIZONTAL);

Set the layout parameters associated with this view. These supply
  parameters to the parent of this view specifying how it should be
  arranged. There are many subclasses of ViewGroup.LayoutParams, and
  these correspond to the different subclasses of ViewGroup that are
  responsible for arranging their children.

Code Structure

    LinearLayout table = (LinearLayout)findViewById(R.id.linearlayout);
    table.setOrientation(LinearLayout.HORIZONTAL);

    Button Btn1 = new Button(Activity.this);
    Btn1.setText("Button 1");
    LinearLayout.LayoutParams childParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
    childParam.weight = 0.5f;
    Btn1.setLayoutParams(childParam);

    Button Btn2 = new Button(Activity.this);
    Btn2.setText("Button 2");
    LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    childParam2.weight = 0.5f;
    Btn2.setLayoutParams(childParam2);

    table.addView(Btn1);
    table.addView(Btn2);

Respected OP


问:
Is it possible for a UIWebView to save and autofill previously entered form values (e.g., username & password)?
I'm building an iPhone app that is just a UIWebView of an existing mobile site that has a form-based login. When I login to the mobile site on iPhone Safari, I'm prompted to save my username/password, and it's then autofilled when I go back to the site later.

I'd like to enable the same functionality in the UIWebView, but for the life of me, I can't figure out how to do it.  Any ideas?

Solution

Following Michael's basic model (see accepted answer), I was able to get this done.  Here's what I did:

SETTING DATA

```<code>- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {

    //save form data
    if(navigationType == UIWebViewNavigationTypeFormSubmitted) {

        //grab the data from the page
        NSString *username = [self.webView stringByEvaluatingJavaScriptFromString: @"document.myForm.username.value"];
        NSString *password = [self.webView stringByEvaluatingJavaScriptFromString: @"document.myForm.password.value"];

        //store values locally
        [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
        [SFHFKeychainUtils storeUsername:username andPassword:password forServiceName:@"MyService" updateExisting:YES error:nil];

    }

}
</code>```

GETTING DATA

```<code>- (void)webViewDidFinishLoad:(UIWebView *)webView{

    //verify view is on the login page of the site (simplified)
    NSURL *requestURL = [self.webView.request URL];
    if ([requestURL.host isEqualToString:@"www.mydomain.com"]) {

        //check for stored login credentials
        NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];

        if (username.length != 0 ) {

            //create js strings
            NSString *loadUsernameJS = [NSString stringWithFormat:@"document.myForm.username.value ='%@'", username];
            NSString *password = [SFHFKeychainUtils getPasswordForUsername: username andServiceName:@"MyService" error:nil];
            if (password.length == 0 ) password = @"";
            NSString *loadPasswordJS = [NSString stringWithFormat:@"document.myForm.password.value ='%@'", password];

            //autofill the form
            [self.webView stringByEvaluatingJavaScriptFromString: loadUsernameJS];
            [self.webView stringByEvaluatingJavaScriptFromString: loadPasswordJS];

        }
    }
}
</code>```

Note that I'm using Buzz Andersen's awesome SFHFKeychainUtils package to store sensitive data to the iOs Keychain.

In order to get SFHFKeychainUtils working, you need to do a few things:

Add SFHFKeychainUtils.h and SFHFKeychainUtils.m to your project

Add the Security.framework to your project

#import <Security/Security.h> and #import "SFHFKeychainUtils.h"

答:
From my looking I don't think there is an easy way to do it. Here is an idea of what might work though:

create your uiwebview

create a nsurlrequest

after your webview delegate page loaded function fires look in the request's http body

find the form for login (regex for common login forms?)

retrieve give the user the option to save it and then retrieve later

Body:
I'm building an iPhone app that is just a UIWebView of an existing mobile site that has a form-based login. When I login to the mobile site on iPhone Safari, I'm prompted to save my username/password, and it's then autofilled when I go back to the site later.

I'd like to enable the same functionality in the UIWebView, but for the life of me, I can't figure out how to do it.  Any ideas?

Solution

Following Michael's basic model (see accepted answer), I was able to get this done.  Here's what I did:

SETTING DATA

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType; {

    //save form data
    if(navigationType == UIWebViewNavigationTypeFormSubmitted) {

        //grab the data from the page
        NSString *username = [self.webView stringByEvaluatingJavaScriptFromString: @"document.myForm.username.value"];
        NSString *password = [self.webView stringByEvaluatingJavaScriptFromString: @"document.myForm.password.value"];

        //store values locally
        [[NSUserDefaults standardUserDefaults] setObject:username forKey:@"username"];
        [SFHFKeychainUtils storeUsername:username andPassword:password forServiceName:@"MyService" updateExisting:YES error:nil];

    }

}

GETTING DATA

- (void)webViewDidFinishLoad:(UIWebView *)webView{

    //verify view is on the login page of the site (simplified)
    NSURL *requestURL = [self.webView.request URL];
    if ([requestURL.host isEqualToString:@"www.mydomain.com"]) {

        //check for stored login credentials
        NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"];

        if (username.length != 0 ) {

            //create js strings
            NSString *loadUsernameJS = [NSString stringWithFormat:@"document.myForm.username.value ='%@'", username];
            NSString *password = [SFHFKeychainUtils getPasswordForUsername: username andServiceName:@"MyService" error:nil];
            if (password.length == 0 ) password = @"";
            NSString *loadPasswordJS = [NSString stringWithFormat:@"document.myForm.password.value ='%@'", password];

            //autofill the form
            [self.webView stringByEvaluatingJavaScriptFromString: loadUsernameJS];
            [self.webView stringByEvaluatingJavaScriptFromString: loadPasswordJS];

        }
    }
}

Note that I'm using Buzz Andersen's awesome SFHFKeychainUtils package to store sensitive data to the iOs Keychain.

In order to get SFHFKeychainUtils working, you need to do a few things:

Add SFHFKeychainUtils.h and SFHFKeychainUtils.m to your project

Add the Security.framework to your project

#import <Security/Security.h> and #import "SFHFKeychainUtils.h"


问:
Call to undefined relationship [person] on model [App\Note]
I have a notes, cards and person table where the notes table has card_id and person_id.

Once I load card data I also want to load person name's name but Laravel give this error:

Call to undefined relationship [person] on model [App\Note].

sorry my English is not good.

These are my relationships:

notes:

```<code>public function card()
   {
       return $this->blongsTo(Card::class);
   }

public function person()
  {
      return $this->blongsTo(Person::class);
  }
</code>```

cards:

```<code>public function notes()
{
    return $this->hasMany(Note::class);
}

</code>```

persons:

```<code>public function notes()
{
    return $this->hasMany(Note::class);
}

</code>```

and this my action:

```<code>        public function showCard(Card $card)
        {

           $card->load('notes.person');

           return view('cards.card',compact('card'));
        }
</code>```

what's wrong?

答:
You have a spelling mistake. Check the relationship, it says: ->blongsTo instead of belongsTo.</p>

```<code>public function card()
{
    return $this->belongsTo(Card::class);
}

public function person()
{
    return $this->belongsTo(Person::class);
}
</code>```

Body:
I have a notes, cards and person table where the notes table has card_id and person_id.

Once I load card data I also want to load person name's name but Laravel give this error:

Call to undefined relationship [person] on model [App\Note].

sorry my English is not good.

These are my relationships:

notes:

public function card()
   {
       return $this->blongsTo(Card::class);
   }

public function person()
  {
      return $this->blongsTo(Person::class);
  }

cards:

public function notes()
{
    return $this->hasMany(Note::class);
}

persons:

public function notes()
{
    return $this->hasMany(Note::class);
}

and this my action:

        public function showCard(Card $card)
        {

           $card->load('notes.person');

           return view('cards.card',compact('card'));
        }

what's wrong?

Body:
You have a spelling mistake. Check the relationship, it says: ->blongsTo instead of belongsTo.

public function card()
{
    return $this->belongsTo(Card::class);
}

public function person()
{
    return $this->belongsTo(Person::class);
}


问:
Hardware differences for ARKit?
Are there any differences in what's available for ARKit depending on hardware? Is iPhone 8 a more potent AR platform than older models in terms of pure functionality?</p>

答:
The face tracking features in ARKit (ARFaceTrackingConfiguration) require a front-facing TrueDepth camera. As yet there’s only one device with that — iPhone X — so the face tracking performance and feature set is the same on all devices that support it.

World tracking (with the back-facing camera) is available on any iOS device with an A9 processor or better. As of this writing that spans three years’ worth of iPhone and iPad hardware releases. Once you meet the bar for supporting ARKit (world / orientation tracking) at all, though, there are no feature set differences between devices.

Depending on what you do with an ARKit session — what technology you use to render overlay content and how complex such content is — you’ll probably find differences in performance across major device generations.

Title: Hardware differences for ARKit?


问:
Apply function to a column in dataframe - python
I wrote a function to eliminate spaces of a value in my dataframe.

```<code>def eliminate_space(words):
    return words.replace(' ', '')
</code>```

Now I want to apply that function to each row in my 'words' column of my dataframe.

```<code>df['words']=df['words'].apply(eliminate_space(words))
</code>```

It's saying the name 'words' is not defined.  How do I adjust my code to be able to apply the function to each value in that column of my dataframe?

答:
You can use apply with lambda for that column of row:

```<code>df['words']=df['words'].apply(lambda row: eliminate_space(row))
</code>```

Testing with example:

```<code>df = pd.DataFrame({'words':['word is 1', 'word is 2', 'word is 3']})
print(df)
</code>```

Initial dataframe:

```<code>     words
0  word is 1
1  word is 2
2  word is 3
</code>```

Using function:

```<code>df['words']=df['words'].apply(lambda row: eliminate_space(row))
</code>```

Result:

```<code>     words
0  wordis1
1  wordis2
2  wordis3
</code>```

Body:
I wrote a function to eliminate spaces of a value in my dataframe.

def eliminate_space(words):
    return words.replace(' ', '')

Now I want to apply that function to each row in my 'words' column of my dataframe.

df['words']=df['words'].apply(eliminate_space(words))

It's saying the name 'words' is not defined.  How do I adjust my code to be able to apply the function to each value in that column of my dataframe?

Body:
You can use apply with lambda for that column of row:

df['words']=df['words'].apply(lambda row: eliminate_space(row))

Testing with example:

df = pd.DataFrame({'words':['word is 1', 'word is 2', 'word is 3']})
print(df)

Initial dataframe:

     words
0  word is 1
1  word is 2
2  word is 3

Using function:

df['words']=df['words'].apply(lambda row: eliminate_space(row))

Result:

     words
0  wordis1
1  wordis2
2  wordis3


答:
The fundamental problem with your solution is that you are comparing with the length of the original element instead of the last appended one. To do that, you can use Python's handy negative indexing feature. Just change if len(a[i]) == len(temp[0])-1: to if len(a[i]) == len(temp[-1])-1:.

There is actually another problem, that your secondary dataset showcases. You only check if the next word is exactly one shorter than the previous, but you really want to check if it is any amount shorter. So really if len(a[i]) == len(temp[0]) - 1: should be if len(a[i]) < len(temp[-1]):.

Here is an IDEOne link.

That being said, there are a number of other improvements you can make to your code. It is not very idiomatic to loop over arrays in Python using a while loop and an index counter, especially since you don't really care about the index at all. A better way would be to do something like

```<code>a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']
temp=[a[0]] #first element will always be taken

for word in a:
  if len(word) < len(temp[-1]):
     temp.append(word)
</code>```

Here is an IDEOne link.

And finally, this being Python, there has to be a one line solution to something like this, as a matter of course. In this case, you could use itertools.groupby with a key of len:

```<code>from itertools import groupby
a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']

temp = [next(group) for key, group in groupby(a, len)]
</code>```

Here is an IDEOne link.

Title: Pick one value from multiple values satisfying a condition

Body:
The fundamental problem with your solution is that you are comparing with the length of the original element instead of the last appended one. To do that, you can use Python's handy negative indexing feature. Just change if len(a[i]) == len(temp[0])-1: to if len(a[i]) == len(temp[-1])-1:.

There is actually another problem, that your secondary dataset showcases. You only check if the next word is exactly one shorter than the previous, but you really want to check if it is any amount shorter. So really if len(a[i]) == len(temp[0]) - 1: should be if len(a[i]) < len(temp[-1]):.

Here is an IDEOne link.

That being said, there are a number of other improvements you can make to your code. It is not very idiomatic to loop over arrays in Python using a while loop and an index counter, especially since you don't really care about the index at all. A better way would be to do something like

a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']
temp=[a[0]] #first element will always be taken

for word in a:
  if len(word) < len(temp[-1]):
     temp.append(word)

Here is an IDEOne link.

And finally, this being Python, there has to be a one line solution to something like this, as a matter of course. In this case, you could use itertools.groupby with a key of len:

from itertools import groupby
a = ['eddy', 'dyed', 'dye', 'dey', 'ed', 'ye', 'de']

temp = [next(group) for key, group in groupby(a, len)]

Here is an IDEOne link.