问:
Cosmos db graph vs Azure Sql Server - Performance and cost
Imagine a social network app. Users follow other users and users take photos. Photos have tags of other users.

I'm trying to get an effective Cosmos db implementation of a graph for that app. I provide an SQL Server version as well as a benchmark.

Here is the graph:

Here is a table version of it:

Here is the Gremlin query:

```<code>g.V('c39f435b-350e-4d08-a7b6-dfcadbe4e9c5')
.out('follows').as('name')
.out('took').order(local).by('postedAt', decr).as('id', 'postedAt')
.select('id', 'name', 'postedAt').by(id).by('name').by('postedAt')
.limit(10)
</code>```

Here is the equivalent SQL query (linq actually):

```<code>Follows
.Where(f => f.FollowerId == "c39f435b-350e-4d08-a7b6-dfcadbe4e9c5")
.Select(f => f.Followees)
.SelectMany(f => f.Photos)
.OrderByDescending(f => f.PostedAt)
.Select(f => new { f.User.Name, f.Id, f.PostedAt})
.Take(10)
</code>```

That user follows 136 users who collectively took 257 photos.

Both SQL Server and Cosmos db are in West Europe Azure location. I'm in France.
I did a bit of testing on Linpad.

The Gremlin Query runs in over 1.20s and consumes about 330 RU. FYI, 400RU/s costs 20$/month.

The SQL query runs in 70ms. The db is 10 DTU (1 instance of S0). So it costs 12.65eur / month

How can I get the feed faster and cheaper with cosmos db?

Note: In order to get the RU charged, I'm using Microsoft.Azure.Graph. But I can also use Gremlin.Net and get similar results.

答:
In case you have not noticed, in addition to relational model, SQL Server also has a graph model and you can use graph queries directly in SQL Server.

I also see that you have not used any partition key, which means the Graph queries will be lot slower.

Several months back, for a new product, we initially ran several tests like the one you had. When the number of records are more (in orders of few 100K, and the number of graph traversals are more than 3, then the Cosmos was cheaper than Azure SQL.

Body:
Imagine a social network app. Users follow other users and users take photos. Photos have tags of other users.

I'm trying to get an effective Cosmos db implementation of a graph for that app. I provide an SQL Server version as well as a benchmark.

Here is the graph:

Here is a table version of it:

Here is the Gremlin query:

g.V('c39f435b-350e-4d08-a7b6-dfcadbe4e9c5')
.out('follows').as('name')
.out('took').order(local).by('postedAt', decr).as('id', 'postedAt')
.select('id', 'name', 'postedAt').by(id).by('name').by('postedAt')
.limit(10)

Here is the equivalent SQL query (linq actually):

Follows
.Where(f => f.FollowerId == "c39f435b-350e-4d08-a7b6-dfcadbe4e9c5")
.Select(f => f.Followees)
.SelectMany(f => f.Photos)
.OrderByDescending(f => f.PostedAt)
.Select(f => new { f.User.Name, f.Id, f.PostedAt})
.Take(10)

That user follows 136 users who collectively took 257 photos.

Both SQL Server and Cosmos db are in West Europe Azure location. I'm in France.
I did a bit of testing on Linpad.

The Gremlin Query runs in over 1.20s and consumes about 330 RU. FYI, 400RU/s costs 20$/month.

The SQL query runs in 70ms. The db is 10 DTU (1 instance of S0). So it costs 12.65eur / month

How can I get the feed faster and cheaper with cosmos db?

Note: In order to get the RU charged, I'm using Microsoft.Azure.Graph. But I can also use Gremlin.Net and get similar results.


来源: stackexchange

问:
What's the difference between a "pull request" and a "branch"?
What's the difference between a "pull request" and a "branch"?

pull request
  branch

答:
In a nutshell, branch is where the real code is stored, and pull request allows you merge two or more branches into one.

Official definitions:

git-pull - Fetch from and integrate with another repository or a local branch

git-branch - List, create, or delete branches

Branch allows you to divide and manage the code, while pull allows you to merge them back together.

More detailed descriptions, along with examples, can be found here:

git pull: https://git-scm.com/docs/user-manual.html#sharing-development

git branch: https://git-scm.com/docs/user-manual.html#what-is-a-branch

Usually master is a standard branch that many other branches (such as dev etc.) get merged into, using the pull requests.

ContentLicense: CC BY-SA 4.0


问:
Redirect to same ajax page after reload or form submission with old input data
I have a dashboard with some side menus. Each menus loads a page through ajax call after it is clicked.
By default when dashboard is loaded it loads the page, there is also a "dashboard" menu to switch between others like profile and add student.

But if I am at profile page and I refresh It goes back to dashboard page. Also if I try to add student by filling the form and if the form has any error it goes back to dashboard again with all old input data lost.

Web.php

```<code>Route::prefix('admin')->group(function(){
Route::get('/dashboard','AdminController@dashboard')->name('admin.dashboard');
Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
Route::post('/add_student','AdminController@add_student');

    Route::middleware('ajax')->group(function(){
    Route::get('/summary','AdminController@summary')->name('admin.summary');
    Route::get('/profile', 'AdminController@profile')->name('admin.profile');
    Route::get('/add_student_form','AdminController@add_student_form')->name('admin.add_student');
});

});
</code>```

AdminController.php

```<code> public function add_student_form(){
    return view('admin.add_student');
}

public function add_student(Request $request)
{
    $this->validate($request,[

        'name'=>'required|string',
        'course_id'=>'required',
        'dob'=>'required|date',
        'gender'=>'required|string',
        'category'=>'required|string',
        'qualification'=>'required|string',
        'fathername'=>'required|string',
        'mothername'=>'required|string',
        'mob_no'=>'required|string|max:10',
        'address'=>'required|string',
        'email'=>'required|email',
        'PIN'=>'required|string|max:6',
    ]);

    $student = new Student;
    $student->name = $request['name'];
    $student->roll_no ='NITTI'.rand(10000,99999);
    $student->password = Hash::make($student['mob']);

    $student->fees = new StudentFees;
    $student->fees->paid_fees = $request['paid_fees'];
    $student->fees->balance_fees = 7000;
    $student->detail = new StudentDetail;
    $student->detail->course_id = $request['course_id'];
    $student->detail->gender = $request['gender'];
    $student->detail->category = $request['category'];
    $student->detail->qualification = $request['qualification'];
    $student->detail->fathername = $request['fathername'];
    $student->detail->mothername = $request['mothername'];
    $student->detail->mob_no = $request['mob_no'];
    $student->detail->email = $request['email'] ;
    $student->detail->address = $request['address'];
    $student->detail->PIN=$request['PIN'];
    $student->detail->dob = $request['dob'];
    $student->push();
    return redirect()->back();

}
</code>```

add_student.blade.php

```<code>  <form action="/admin/add_student" method="POST">
      @csrf
   //It has all the fields here and a submit button
   </form>
</code>```

dashboard.blade.php

```<code>   <div class="container-fluid">
      <div class="row">
         <div class="col-2  sidebar">
            <img src="{{asset('/img/admin.jpg')}}" class="fit-image">
             <p class="text-center">{{Auth::user()->name}}</p>
             <hr>

         <ul class="list-group">
            <li class="list-group-item" id="summary">Dashboard</li>
            <li class="list-group-item" id="admin_profile">Profile
            </li>
            <li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
           <ul class="sidenav list-group">
            <li class="list-group-item" id="add_student">Add Student</li>
            <li class="list-group-item" id="viewall">View All </li>
          </ul></li>
        </ul>
       </div>
         <div class="col-10 dashboard" id="admin">
         </div>
        </div>
         </div>
</code>```

dashboard.js

```<code>    $(document).ready(function(){
      $.ajax({
          url:'/admin/summary',
          type: "GET",
          success: function(data){
            $data = $(data);

            $('#admin').html($data).fadeIn();
            }
        });
      });

      $(document).on('click','#summary', function(){
        $.ajax({
            url:'/admin/summary',
            type: "GET",
            success: function(data){
              $data = $(data);
              $('#admin').html($data).fadeIn();
              }
          });
        });

    $(document).on('click','#admin_profile', function(){
        $.ajax({
            url:'/admin/profile',
            type: "GET",
            success: function(data){
              $data = $(data);
              $('#admin').html($data).fadeIn();
              }
          });
        });
          $(document).on('click','#add_student', function(){
            $.ajax({
                url:'/admin/add_student_form',
                type: "GET",
                success: function(data){
                  $data = $(data);  produced
                  $('#admin').html($data).fadeIn();
                  }
              });
            });
</code>```

I tried to redirect()->back->withInput('the fields');, but it didn't work.
If there is better way to load the pages which holds the same page after reloading or form submission I would welcome that.

答:
You could use ajax form posting.

I rewrote code to abstract ajax load.

JS:

```<code>$(document).ready(function(){
  //load summary by default
  loadPage('summary');

  //load on click menu item
  $(document).on('click','.menu-item', function(){
    loadPage($(this).attr('data-page'));
  });

  //send xcrf token in ajax header
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });

  //submit form
  $(document).on('submit', 'form', function(){
    let form = $(this);

    $.ajax({
      url: form.attr('action'),
      type: 'POST',
      dataType: 'json',
      success: function(data){
        if(data.page){
            //load page returned in controller
            loadPage(data.page);
        }
      },
      error: function(data){
        if(data.responseJSON && data.responseJSON.errors){
            $.each(data.responseJSON.errors, function(key, value){

                //convert laravel dotted rules to jquery selectors

                key = key.replace('.', '[').replace(/\./g, '][');

                if(key.indexOf('[') !== -1){
                    key += ']';
                }

                //do something with errored elements
                form.find('*[name="' + key + '"]').addClass('error');
            });
        }
      }
    });

    return false;
  });
});

function loadPage(page){
  $.ajax({
    url:'/admin/' + page,
    type: 'GET',
    success: function(data){
      $data = $(data);
      $('#admin').html($data).fadeIn();
    }
  });
}
</code>```

HTML:

Add to :

```<code><meta name="csrf-token" content="{{ csrf_token() }}">
</code>```

Change sidebar menu:

```<code><ul class="list-group">
    <li class="list-group-item menu-item" data-page="summary">Dashboard</li>
    <li class="list-group-item menu-item" data-page="profile">Profile</li>
    <li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
        <ul class="sidenav list-group">
            <li class="list-group-item menu-item" data-page="add_student_form">Add Student</li>
            <li class="list-group-item menu-item" data-page="viewall">View All </li>
        </ul>
    </li>
</ul>
</code>```

Controller method:

Replace return redirect()->back(); with return ['page' => 'viewall'];

Body:
I have a dashboard with some side menus. Each menus loads a page through ajax call after it is clicked.
By default when dashboard is loaded it loads the page, there is also a "dashboard" menu to switch between others like profile and add student.

But if I am at profile page and I refresh It goes back to dashboard page. Also if I try to add student by filling the form and if the form has any error it goes back to dashboard again with all old input data lost.

Web.php

Route::prefix('admin')->group(function(){
Route::get('/dashboard','AdminController@dashboard')->name('admin.dashboard');
Route::get('/login', 'Auth\AdminLoginController@showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController@login')->name('admin.login.submit');
Route::post('/add_student','AdminController@add_student');

    Route::middleware('ajax')->group(function(){
    Route::get('/summary','AdminController@summary')->name('admin.summary');
    Route::get('/profile', 'AdminController@profile')->name('admin.profile');
    Route::get('/add_student_form','AdminController@add_student_form')->name('admin.add_student');
});

});

AdminController.php

 public function add_student_form(){
    return view('admin.add_student');
}

public function add_student(Request $request)
{
    $this->validate($request,[

        'name'=>'required|string',
        'course_id'=>'required',
        'dob'=>'required|date',
        'gender'=>'required|string',
        'category'=>'required|string',
        'qualification'=>'required|string',
        'fathername'=>'required|string',
        'mothername'=>'required|string',
        'mob_no'=>'required|string|max:10',
        'address'=>'required|string',
        'email'=>'required|email',
        'PIN'=>'required|string|max:6',
    ]);

    $student = new Student;
    $student->name = $request['name'];
    $student->roll_no ='NITTI'.rand(10000,99999);
    $student->password = Hash::make($student['mob']);

    $student->fees = new StudentFees;
    $student->fees->paid_fees = $request['paid_fees'];
    $student->fees->balance_fees = 7000;
    $student->detail = new StudentDetail;
    $student->detail->course_id = $request['course_id'];
    $student->detail->gender = $request['gender'];
    $student->detail->category = $request['category'];
    $student->detail->qualification = $request['qualification'];
    $student->detail->fathername = $request['fathername'];
    $student->detail->mothername = $request['mothername'];
    $student->detail->mob_no = $request['mob_no'];
    $student->detail->email = $request['email'] ;
    $student->detail->address = $request['address'];
    $student->detail->PIN=$request['PIN'];
    $student->detail->dob = $request['dob'];
    $student->push();
    return redirect()->back();

}

add_student.blade.php

  <form action="/admin/add_student" method="POST">
      @csrf
   //It has all the fields here and a submit button
   </form>

dashboard.blade.php

{{Auth::user()->name}}

Dashboard

Profile

Students

Add Student

View All

dashboard.js

    $(document).ready(function(){
      $.ajax({
          url:'/admin/summary',
          type: "GET",
          success: function(data){
            $data = $(data);

            $('#admin').html($data).fadeIn();
            }
        });
      });

      $(document).on('click','#summary', function(){
        $.ajax({
            url:'/admin/summary',
            type: "GET",
            success: function(data){
              $data = $(data);
              $('#admin').html($data).fadeIn();
              }
          });
        });

    $(document).on('click','#admin_profile', function(){
        $.ajax({
            url:'/admin/profile',
            type: "GET",
            success: function(data){
              $data = $(data);
              $('#admin').html($data).fadeIn();
              }
          });
        });
          $(document).on('click','#add_student', function(){
            $.ajax({
                url:'/admin/add_student_form',
                type: "GET",
                success: function(data){
                  $data = $(data);  produced
                  $('#admin').html($data).fadeIn();
                  }
              });
            });

I tried to redirect()->back->withInput('the fields');, but it didn't work.
If there is better way to load the pages which holds the same page after reloading or form submission I would welcome that.

Body:
You could use ajax form posting.

I rewrote code to abstract ajax load.

JS:

$(document).ready(function(){
  //load summary by default
  loadPage('summary');

  //load on click menu item
  $(document).on('click','.menu-item', function(){
    loadPage($(this).attr('data-page'));
  });

  //send xcrf token in ajax header
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });

  //submit form
  $(document).on('submit', 'form', function(){
    let form = $(this);

    $.ajax({
      url: form.attr('action'),
      type: 'POST',
      dataType: 'json',
      success: function(data){
        if(data.page){
            //load page returned in controller
            loadPage(data.page);
        }
      },
      error: function(data){
        if(data.responseJSON && data.responseJSON.errors){
            $.each(data.responseJSON.errors, function(key, value){

                //convert laravel dotted rules to jquery selectors

                key = key.replace('.', '[').replace(/\./g, '][');

                if(key.indexOf('[') !== -1){
                    key += ']';
                }

                //do something with errored elements
                form.find('*[name="' + key + '"]').addClass('error');
            });
        }
      }
    });

    return false;
  });
});

function loadPage(page){
  $.ajax({
    url:'/admin/' + page,
    type: 'GET',
    success: function(data){
      $data = $(data);
      $('#admin').html($data).fadeIn();
    }
  });
}

HTML:

Add to <head>:

<meta name="csrf-token" content="{{ csrf_token() }}">

Change sidebar menu:

<ul class="list-group">
    <li class="list-group-item menu-item" data-page="summary">Dashboard</li>
    <li class="list-group-item menu-item" data-page="profile">Profile</li>
    <li class="list-group-item" id="students">Students <i class="fas fa-angle-right ml-5"></i>
        <ul class="sidenav list-group">
            <li class="list-group-item menu-item" data-page="add_student_form">Add Student</li>
            <li class="list-group-item menu-item" data-page="viewall">View All </li>
        </ul>
    </li>
</ul>

Controller method:

Replace return redirect()->back(); with return ['page' => 'viewall'];


问:
How can I add a border to an image that has padding?
I have an image on my webpage that I added padding to so it wouldn't be in the corner. I also wanted to give it a border but the border is showing up around the empty space instead of just the image... What am I doing wrong?

The image also has a float attribute.

```<code>img {
  float: right;
  width: 300px;
  padding: 25px;
  border-style: solid;
  border-color: #fdb924;
}
</code>```

答: Change the padding to margin. padding is the space between the border and the image, while margin is the space between the border and everything outside of it: https://jsfiddle.net/632t5g8x/

Body:
I have an image on my webpage that I added padding to so it wouldn't be in the corner. I also wanted to give it a border but the border is showing up around the empty space instead of just the image... What am I doing wrong?

The image also has a float attribute.

img {
  float: right;
  width: 300px;
  padding: 25px;
  border-style: solid;
  border-color: #fdb924;
}


问:
Match Substrings between Multiple Dataframes and Sum Weighted Value in Separate Column
I'm trying to categorise a list of strings called keywords based on whether they contain 1 or more substrings from another DataFrame.

The substring is weighted so that at the end each keyword has a weight in approximately 4 columns. These columns will be called loan, mortgage, accounts, and cards.

I've attempted to use join(), concat() and merge() to join multiple dataframes, as well as attempting to use where(), isin() and contains().

I've come close a few times to achieve my desired goal but thwarted either by errors or scalability. I have limited experience with Python and Pandas, so there may be a completely different approach that I've not considered.

import pandas as pd

df = pd.read_csv('Inputs/keyword.csv', header=0)
df['loan'] = 0
df2 = pd.read_csv('Essentials/Groups/loans.csv', header=0)

#review the data in df
print(df.head())

output:
           keywords  search_volume  loan
0             loans         132000     0
1    funding circle          81000     0
2        government          36000     0
3  short term loans          30000     0
4           company          27000     0
```

<p>In the above code I'm loading up my list of keywords including an associated search volume. It currently has no loan column so I've added one with the default value set to 0.</p>

<p>Below, I have another DataFrame that includes a list of terms and an associated weighting. I've arbitrarily picked an integer of 5 that I would like added to the existing total.</p>

<pre class="lang-py prettyprint-override"><code>#review the data in df2
print(df2.head())

output:
      terms  weight
0      loan       5
1     loans       5
2  personal       3
3  business       3
4       apr       4
</code>```

There is a problem that I have spotted but don't know how to resolve.

My list includes both loan and loans. It is fine for me to have these duplicates on my end. However, row 3 has a value of 'short term loans' and is marked as False.

Since the term loan and loans both appear in short term loans, I would have expected it to be marked as True. I've tried reversing the .isin() statement so that I'm searching df2['terms'] in df['keywords'], but the result came out the same.

#review the true/false for overlaps
print(df['keywords'].isin(df2['terms']).head())

output:
0     True
1    False
2    False
3    False
4    False
```

<p>Lastly, once we fix this boolean issue, I don't know how to vectorise a sum change in <code>df['loan']</code> based on matches. I'm trying to avoid for loops because I'm expecting the keyword list to include around 100,000+ rows and each category DataFrame may include 1,000 terms.</p>

<p>The desired output would look something like this:</p>

<pre class="lang-py prettyprint-override"><code>output:
           keywords  search_volume  loan  mortgage  accounts  cards
0             loans         132000     10        0         0      0
1    funding circle          81000     0         0         0      0
2        government          36000     0         0         0      0
3  short term loans          30000     10        0         0      0
4           company          27000     0         0         0      0
</code>```

答:
Here's a way to find the amount of matches. This might help you more in the right direction.

First explode our strings to seperate rows using this function:

```<code>df = explode_str(df, 'keywords', ' ')

     keywords  search_volume  loan
0       loans         132000     0
1     funding          81000     0
1      circle          81000     0
2  government          36000     0
3       short          30000     0
3        term          30000     0
3       loans          30000     0
4     company          27000     0
</code>```

Then we use the difflib module to get the closest matches, for example loan with loans:

```<code>import difflib

df['loan'] = df.set_index('keywords').index.map(lambda x: difflib.get_close_matches(x, df2.set_index('terms').index))

     keywords  search_volume           loan
0       loans         132000  [loans, loan]
1     funding          81000             []
1      circle          81000             []
2  government          36000             []
3       short          30000             []
3        term          30000             []
3       loans          30000  [loans, loan]
4     company          27000             []
</code>```

Then we groupby on the index to get our original dataframe back and count the length of the matches:

```<code>df = df.groupby(df.index).agg({'keywords':' '.join,
                               'search_volume':'last',
                               'loan':'last'})

df['count'] = df['loan'].str.len()

           keywords  search_volume           loan  count
0             loans         132000  [loans, loan]      2
1    funding circle          81000             []      0
2        government          36000             []      0
3  short term loans          30000  [loans, loan]      2
4           company          27000             []      0
</code>```

Only thing left is to multiply the count with the weight and you got what you want.

Body:
I'm trying to categorise a list of strings called keywords based on whether they contain 1 or more substrings from another DataFrame.

The substring is weighted so that at the end each keyword has a weight in approximately 4 columns. These columns will be called loan, mortgage, accounts, and cards.

I've attempted to use join(), concat() and merge() to join multiple dataframes, as well as attempting to use where(), isin() and contains().

I've come close a few times to achieve my desired goal but thwarted either by errors or scalability. I have limited experience with Python and Pandas, so there may be a completely different approach that I've not considered.

import pandas as pd

df = pd.read_csv('Inputs/keyword.csv', header=0)
df['loan'] = 0
df2 = pd.read_csv('Essentials/Groups/loans.csv', header=0)

#review the data in df
print(df.head())

output:
           keywords  search_volume  loan
0             loans         132000     0
1    funding circle          81000     0
2        government          36000     0
3  short term loans          30000     0
4           company          27000     0

In the above code I'm loading up my list of keywords including an associated search volume. It currently has no loan column so I've added one with the default value set to 0.

Below, I have another DataFrame that includes a list of terms and an associated weighting. I've arbitrarily picked an integer of 5 that I would like added to the existing total.

#review the data in df2
print(df2.head())

output:
      terms  weight
0      loan       5
1     loans       5
2  personal       3
3  business       3
4       apr       4

There is a problem that I have spotted but don't know how to resolve.

My list includes both loan and loans. It is fine for me to have these duplicates on my end. However, row 3 has a value of 'short term loans' and is marked as False.

Since the term loan and loans both appear in short term loans, I would have expected it to be marked as True. I've tried reversing the .isin() statement so that I'm searching df2['terms'] in df['keywords'], but the result came out the same.

#review the true/false for overlaps
print(df['keywords'].isin(df2['terms']).head())

output:
0     True
1    False
2    False
3    False
4    False

Lastly, once we fix this boolean issue, I don't know how to vectorise a sum change in df['loan'] based on matches. I'm trying to avoid for loops because I'm expecting the keyword list to include around 100,000+ rows and each category DataFrame may include 1,000 terms.

The desired output would look something like this:

output:
           keywords  search_volume  loan  mortgage  accounts  cards
0             loans         132000     10        0         0      0
1    funding circle          81000     0         0         0      0
2        government          36000     0         0         0      0
3  short term loans          30000     10        0         0      0
4           company          27000     0         0         0      0

Body:
Here's a way to find the amount of matches. This might help you more in the right direction.

First explode our strings to seperate rows using this function:

df = explode_str(df, 'keywords', ' ')

     keywords  search_volume  loan
0       loans         132000     0
1     funding          81000     0
1      circle          81000     0
2  government          36000     0
3       short          30000     0
3        term          30000     0
3       loans          30000     0
4     company          27000     0

Then we use the difflib module to get the closest matches, for example loan with loans:

import difflib

df['loan'] = df.set_index('keywords').index.map(lambda x: difflib.get_close_matches(x, df2.set_index('terms').index))

     keywords  search_volume           loan
0       loans         132000  [loans, loan]
1     funding          81000             []
1      circle          81000             []
2  government          36000             []
3       short          30000             []
3        term          30000             []
3       loans          30000  [loans, loan]
4     company          27000             []

Then we groupby on the index to get our original dataframe back and count the length of the matches:

df = df.groupby(df.index).agg({'keywords':' '.join,
                               'search_volume':'last',
                               'loan':'last'})

df['count'] = df['loan'].str.len()

           keywords  search_volume           loan  count
0             loans         132000  [loans, loan]      2
1    funding circle          81000             []      0
2        government          36000             []      0
3  short term loans          30000  [loans, loan]      2
4           company          27000             []      0

Only thing left is to multiply the count with the weight and you got what you want.


问:
change of datepicker format in android
i have used a datepicker but i wanted to use dd/mm/yy format can i do this ??
please provide sample code</p>

答:
check here ,

DatePicker Widget Format

ContentLicense: CC BY-SA 3.0

Title: change of datepicker format in android

Body:
check here ,

DatePicker Widget Format


问:
ASP.NET 2.0 "BC2017: could not find library" - How to force .NET to look for correct version?
A precompiled ASP.NET 2.0 (Visual Studio 2005) application is throwing this error when we try to access it.

Compiler Error Message: BC2017: could not find library 'C:\WINDOWS\assembly\GAC_MSIL\System.Web.Mobile\2.0.0.0__b03f5f7f11d50a3a\System.Web.Mobile.dll'

Two immediate problems spring to mind:

We're running .NET version 2.0.50727, not 2.0.0.0

Our GAC is located at "C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files," not "C:\WINDOWS\assembly\GAC_MSIL\"

So obviously it's looking for an outdated version of the assembly and it's looking for it in the wrong place.

Unfortunately, we can't recompile the application because we're hosting it for a client and the source code can't be obtained from the original developer.  Is there any way to force the ASP.NET application to use the current version of System.Web.Mobile.dll and whatever other standard .NET assemblies it needs?

We will of course lecture them the perils of paying developers and not getting the source code, but we'd sure like to help them get this thing running until they can replace it.

Edit: It turns out that the problem was due to some disk corruption that affected the GAC.  Now we're having some other .NET problems related to rebuilding the GAC, but that's another story.  Closing this question.

答: I had some classes that appeared to have been included in the project, but turns out they weren't.   Removed/Added back in, and now it builds, the class library DLL exists for the other projects and error gone.</p>

OwnerDisplayName: John Booty

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Fabian Steeg


问:
setcookie() in php showing undefined index error
I'm learning about superglobal variables.I'm getting undefined index error while accessing the created cookie using $_COOKIE

I've created a cookie using setcookie('name','saravana') and i accessed it immediately using $_COOKIE['name']  (inside the if statement) .... it didn't work when I Accessed it inside "if" but when i Accessed it outside the "if" it worked ....
  Then After the cookie gets created in my browser ,I can access the cookie inside the if statement without any problem ...Then I deleted the cookie from my browser and tried to access the cookie from inside the 'if' it again showed undefined index error.
  The Question I'm Having is does the cookie get created after interpreting the line setcookie() or it gets created after completing the 'if' statement..
  If it gets created by the time of interpreting setcookie() then why I can't  access the cookie with if statement.
    Thanks in advance.Sorry for bad grammer!!

```<code>//Creating cookie for the first time
<?php
 if (setcookie("name","saravana")){
   echo "cookie is created".$_COOKIE['name'];
   //undefined index error
}
//echo $_COOKIE['name']
//works fine.How??
?>
</code>```

Ouput of 1st code:
Notice: Undefined index: name in C:\xampp\htdocs\Test\cookies.php on line 3
cookie is created

答: After setting up cookie will be available in next request (see documentation for setcookie() function). You can't access the cookie right after setting it up.</p>

Body:
I'm learning about superglobal variables.I'm getting undefined index error while accessing the created cookie using $_COOKIE

I've created a cookie using setcookie('name','saravana') and i accessed it immediately using $_COOKIE['name']  (inside the if statement) .... it didn't work when I Accessed it inside "if" but when i Accessed it outside the "if" it worked ....
  Then After the cookie gets created in my browser ,I can access the cookie inside the if statement without any problem ...Then I deleted the cookie from my browser and tried to access the cookie from inside the 'if' it again showed undefined index error.
  The Question I'm Having is does the cookie get created after interpreting the line setcookie() or it gets created after completing the 'if' statement..
  If it gets created by the time of interpreting setcookie() then why I can't  access the cookie with if statement.
    Thanks in advance.Sorry for bad grammer!!

//Creating cookie for the first time
<?php
 if (setcookie("name","saravana")){
   echo "cookie is created".$_COOKIE['name'];
   //undefined index error
}
//echo $_COOKIE['name']
//works fine.How??
?>

Ouput of 1st code:
Notice: Undefined index: name in C:\xampp\htdocs\Test\cookies.php on line 3
cookie is created


问:
How to create K8S cluster with non-root user?
How to create K8S cluster with non-root user?
Include..
etcd,
flannel or Calico,
K8S API,
kubelet....etc

Regards

Asura

答:
After Docker 19.03, which can be installed as rootless, you also have the experiment rootless-containers/usernetes:

Kubernetes installable under $HOME, without the root privileges

That comes with:

Moby (dockerd)

Kubernetes

dockershim

CRI-O

containerd

Multi-node CNI

Flannel (VXLAN)


问:
How to add horizontal bar in table row whose width depends on the value passed
I am implementing vote application in which i need to show horizontal bar in table row whose width is depended on particular value. This horizontal bar will act as a indicator to show percentage of vote.</p>

答:
You can use progress bar in the 'cell. backgroundView'.
or you can have imageView and overriding its draw rect method to draw the percentage of votes</p>


问:
How to delete all the nodes of BST for reuse in c++
I couldn't delete all the nodes of BST for reuse.For the first set of inputs my code works properly but fails later input.
I googled a lot and couldn't find any solution related my problem.
For clarification I am pasting my full source code.
I found this kind of question previously asked here
How to delete all nodes of a Binary Search Tree
I don't know python very much.
For this a asked here again about this topic.</p>

```<code>    #include<bits/stdc++.h>
    using namespace std;
    int size,c=0;
    struct BstNode {
      int data;
      BstNode* left;
      BstNode* right;
    };

    BstNode* insert(BstNode* root,int data) {
      if(root==NULL) {
        root=new BstNode();
        root->data=data;
        root->left=root->right=NULL;
      }
      else if(data<root->data) {
        root->left=insert(root->left,data);
      }
      else {
        root->right=insert(root->right,data);
      }
      return root;
    }

    void preorderTraversal(BstNode* root) {
      if(root!=NULL) {

        c++;
        if(c==size) cout<<root->data<<endl;
        else cout<<root->data<<" ";
        preorderTraversal(root->left);
        preorderTraversal(root->right);
      }
    }

    void inorderTraversal(BstNode* root) {
      if(root!=NULL) {
        inorderTraversal(root->left);
        c++;
        if(c==size) cout<<root->data<<endl;
        else cout<<root->data<<" ";
        inorderTraversal(root->right);
      }
    }

    void postorderTraversal(BstNode* root) {
      if(root!=NULL) {
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        c++;
        if(c==size) cout<<root->data<<endl;
        else cout<<root->data<<" ";
      }
    }

    void deletepostorderTraversal(BstNode* root) {
      if(root!=NULL) {
        deletepostorderTraversal(root->left);
        deletepostorderTraversal(root->right);
        delete root;
      }
    }

    int main() {
      int test_case;
      while(cin>>test_case) {
        cin>>size;
        BstNode* root=NULL; //create the root
        for(int i=0;i<size;i++) {
          int data;cin>>data;
          root=insert(root,data);
        }
        c=0;
        cout<<"Pre.: ";
        preorderTraversal(root);
        cout<<"In..: ";
        c=0;
        inorderTraversal(root);
        cout<<"Post: ";
        c=0;
        postorderTraversal(root);
        cout<<endl;
        deletepostorderTraversal(root); //delete all the nodes
        //i can't reuse this code again.
       // root=NULL;
      //  if(root==NULL) cout<<"Deleted"<<endl;
      }
    }
</code>```

答:
```<code>private static void deleteBinaryTree(Node root) {
    if(root == null) {
        return;
    }
    deleteBinaryTree(root.left);
    deleteBinaryTree(root.right);
    System.out.println("deleted node "+root.data);
    root = null;
}
</code>```

NOTE : Post Order Deletion is happening here as Root has to get deleted once their left and right children deletion is done

Body:
I couldn't delete all the nodes of BST for reuse.For the first set of inputs my code works properly but fails later input.
I googled a lot and couldn't find any solution related my problem.
For clarification I am pasting my full source code.
I found this kind of question previously asked here
How to delete all nodes of a Binary Search Tree
I don't know python very much.
For this a asked here again about this topic.

    #include<bits/stdc++.h>
    using namespace std;
    int size,c=0;
    struct BstNode {
      int data;
      BstNode* left;
      BstNode* right;
    };

    BstNode* insert(BstNode* root,int data) {
      if(root==NULL) {
        root=new BstNode();
        root->data=data;
        root->left=root->right=NULL;
      }
      else if(data<root->data) {
        root->left=insert(root->left,data);
      }
      else {
        root->right=insert(root->right,data);
      }
      return root;
    }

    void preorderTraversal(BstNode* root) {
      if(root!=NULL) {

        c++;
        if(c==size) cout<<root->data<<endl;
        else cout<<root->data<<" ";
        preorderTraversal(root->left);
        preorderTraversal(root->right);
      }
    }

    void inorderTraversal(BstNode* root) {
      if(root!=NULL) {
        inorderTraversal(root->left);
        c++;
        if(c==size) cout<<root->data<<endl;
        else cout<<root->data<<" ";
        inorderTraversal(root->right);
      }
    }

    void postorderTraversal(BstNode* root) {
      if(root!=NULL) {
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        c++;
        if(c==size) cout<<root->data<<endl;
        else cout<<root->data<<" ";
      }
    }

    void deletepostorderTraversal(BstNode* root) {
      if(root!=NULL) {
        deletepostorderTraversal(root->left);
        deletepostorderTraversal(root->right);
        delete root;
      }
    }

    int main() {
      int test_case;
      while(cin>>test_case) {
        cin>>size;
        BstNode* root=NULL; //create the root
        for(int i=0;i<size;i++) {
          int data;cin>>data;
          root=insert(root,data);
        }
        c=0;
        cout<<"Pre.: ";
        preorderTraversal(root);
        cout<<"In..: ";
        c=0;
        inorderTraversal(root);
        cout<<"Post: ";
        c=0;
        postorderTraversal(root);
        cout<<endl;
        deletepostorderTraversal(root); //delete all the nodes
        //i can't reuse this code again.
       // root=NULL;
      //  if(root==NULL) cout<<"Deleted"<<endl;
      }
    }

Body:
private static void deleteBinaryTree(Node root) {
    if(root == null) {
        return;
    }
    deleteBinaryTree(root.left);
    deleteBinaryTree(root.right);
    System.out.println("deleted node "+root.data);
    root = null;
}

NOTE : Post Order Deletion is happening here as Root has to get deleted once their left and right children deletion is done


问:
Stripe checkout is not working
We are use stripe payments method in a php script. We are getting the following  error:

```<code>Fatal error: Uncaught exception 'Stripe\Error\InvalidRequest' with message
    'Amount must be at least 50 cents' in /stripe-php/lib/ApiRequestor.php:102
     from API request 'req_7w4X4j80cfWZoS'
Stack trace:
#0 /lib/ApiRequestor.php(216):
       Stripe\ApiRequestor->handleApiError('{\n "error": {\n...', 400, Array, Array)
#1 /stripe-php/lib/ApiRequestor.php(60):
       Stripe\ApiRequestor->_interpretResponse('{\n "error": {\n...', 400, Array)
#2 /stripe-php/lib/ApiResource.php(105):
        Stripe\ApiRequestor->request('post', '/v1/charges', Array, Array)
#3 stripe-php/lib/ApiResource.php(137):
         Stripe\ApiResource::_staticRequest('post', '/v1/charges', Array, NULL)
#4 /home/imarkinfo/donogifts.com/stripe-php/lib/Charge.php(37):
          Stripe\ApiResource::_create(Array, NULL)
#5 /form_section.php(81):
          Stripe\Charge::create(Array)
#6 {main} thrown in stripe-php/lib/ApiRequestor.php on line 102
</code>```

Please suggest how we can fix it

答: If you want to charge $1 you must set amount=100 as stripe uses cents.</p>

Title: Stripe checkout is not working

Body:
We are use stripe payments method in a php script. We are getting the following  error:

Fatal error: Uncaught exception 'Stripe\Error\InvalidRequest' with message
    'Amount must be at least 50 cents' in /stripe-php/lib/ApiRequestor.php:102
     from API request 'req_7w4X4j80cfWZoS'
Stack trace:
#0 /lib/ApiRequestor.php(216):
       Stripe\ApiRequestor->handleApiError('{\n "error": {\n...', 400, Array, Array)
#1 /stripe-php/lib/ApiRequestor.php(60):
       Stripe\ApiRequestor->_interpretResponse('{\n "error": {\n...', 400, Array)
#2 /stripe-php/lib/ApiResource.php(105):
        Stripe\ApiRequestor->request('post', '/v1/charges', Array, Array)
#3 stripe-php/lib/ApiResource.php(137):
         Stripe\ApiResource::_staticRequest('post', '/v1/charges', Array, NULL)
#4 /home/imarkinfo/donogifts.com/stripe-php/lib/Charge.php(37):
          Stripe\ApiResource::_create(Array, NULL)
#5 /form_section.php(81):
          Stripe\Charge::create(Array)
#6 {main} thrown in stripe-php/lib/ApiRequestor.php on line 102

Please suggest how we can fix it


问:
How to set up android SDK for command line development on linux?
I'm trying to set up the android SDK to develop a simple program on the command line in Linux (Ubuntu 9.10). I tried eclipse, but it has know problems running on Ubuntu, so I gave up on it. Here's what I've done so far:

downloaded  android-sdk_r05-linux_86.tgz  from   http://developer.android.com/sdk/index.html

tar xvzf android-sdk_r05-linux_86.tgz

ln -s android-sdk-linux_86 android

in .tcshrc added setenv PATH .....:/home/user/android/tools

source .tcshrc

ran 'android'. This opened a gui. Under available packages: I installed everything,   and quit the gui.

ran 'android list targets' and It listed these:

Available Android targets:

id: 1 or "android-3"
       Name: Android 1.5
       Type: Platform
       API level: 3
       Revision: 1
       Skins: HVGA-P, HVGA (default), QVGA-P, QVGA-L, HVGA-L

id: 2 or "Google Inc.:Google APIs:3"
       Name: Google APIs
       Type: Add-On
       Vendor: Google Inc.
       Revision: 3
       Description: Android + Google APIs
       Based on Android 1.5 (API level 3)
       Libraries:
        * com.google.android.maps (maps.jar)
            API for Google Maps
       Skins: QVGA-P, HVGA-L, HVGA (default), QVGA-L, HVGA-P

id: 3 or "android-4"
       Name: Android 1.6
       Type: Platform
       API level: 4
       Revision: 1
       Skins: HVGA (default), WVGA800, WVGA854, QVGA

id: 4 or "Google Inc.:Google APIs:4"
       Name: Google APIs
       Type: Add-On
       Vendor: Google Inc.
       Revision: 2
       Description: Android + Google APIs
       Based on Android 1.6 (API level 4)
       Libraries:
        * com.google.android.maps (maps.jar)
            API for Google Maps
       Skins: WVGA854, HVGA (default), QVGA, WVGA800

id: 5 or "android-6"
       Name: Android 2.0.1
       Type: Platform
       API level: 6
       Revision: 1
       Skins: WQVGA432, HVGA (default), WVGA800, WVGA854, WQVGA400, QVGA id: 6
  or "Google Inc.:Google APIs:6"
       Name: Google APIs
       Type: Add-On
       Vendor: Google Inc.
       Revision: 1
       Description: Android + Google APIs
       Based on Android 2.0.1 (API level 6)
       Libraries:
        * com.google.android.maps (maps.jar)
            API for Google Maps
       Skins: WQVGA400, WVGA854, HVGA (default), WQVGA432, QVGA, WVGA800

id: 7 or "android-7"
       Name: Android 2.1
       Type: Platform
       API level: 7
       Revision: 1
       Skins: WQVGA432, HVGA (default), WVGA800, WVGA854, WQVGA400, QVGA

id: 8 or "Google Inc.:Google APIs:7"
       Name: Google APIs
       Type: Add-On
       Vendor: Google Inc.
       Revision: 1
       Description: Android + Google APIs
       Based on Android 2.1 (API level 7)
       Libraries:
        * com.google.android.maps (maps.jar)
            API for Google Maps
       Skins: WQVGA400, WVGA854, HVGA (default), WQVGA432, QVGA, WVGA800

I want to create a simple hello world program for my motorola droid. Which of these targets should I use?

How do I see the Skins?

If I run 'android' from the command line it says that that there are no virtual devices. Is a virtual device the same as a target?

How do I get a droid skin and/or a droid target and/or a droid virtual device?

I THINK that I need to run something like 'android create avd --target 2 --name my_avd', but not sure. Is there a step-by-step list of how to do this somewhere?

thanks,
Bob

Later:

I figured out that I had to create targets (=virtual devices) like this:

android create avd -t 1 -n myavd1

  .......

  android create avd -t 8 -n myavd8

This gave me 8 virtual devices in the gui when I ran 'android' from the command line.

Does anyone know what api level / platform to use for the Droid? And where to get the right skin? Is there anything hardware-specifications, that I need to know for Droid development?

Finally, are there any lists of steps to create a hello world app from the command line (linux) and run it on the emulator and then run it on a real phone?

Bob

答:
Use android list target to list the available targets. This will contain following information :

 -Target ID : Each target will have a different id and it should be used in all other commands.

 -Skin : Each target contains the list of skins supported

 -API Level : API level for particular target

Creating avd:

```<code>android create avd --target 8 --name DROID_EMULATOR --sdcard 128M --skin WVGA854
</code>```

Creating a HelloWorld project :

```<code>android create project --name "HelloWorld" --target 8 --package com.test.helloworld --activity HelloWorld --path HelloWorld
</code>```

This will create a HelloWorld directory in current directory. It will also create a build.xml in current directory.

You can use ant compile to compile the project and ant install to compile and install the project. This will install the app on available emulator or device. You can use ant to see the different build targets available.

HTH!

PS : I'm using Android SDK Tools, revision 9 and Platform-tools, revision 3.

Body:
Use android list target to list the available targets. This will contain following information :

 -Target ID : Each target will have a different id and it should be used in all other commands.

 -Skin : Each target contains the list of skins supported

 -API Level : API level for particular target

Creating avd:

android create avd --target 8 --name DROID_EMULATOR --sdcard 128M --skin WVGA854

Creating a HelloWorld project :

android create project --name "HelloWorld" --target 8 --package com.test.helloworld --activity HelloWorld --path HelloWorld

This will create a HelloWorld directory in current directory. It will also create a build.xml in current directory.

You can use ant compile to compile the project and ant install to compile and install the project. This will install the app on available emulator or device. You can use ant to see the different build targets available.

HTH!

PS : I'm using Android SDK Tools, revision 9 and Platform-tools, revision 3.


问:
Is it possible to implement a Paint Bucket using Konva.js?
I’ve managed to implement, using konva, multiple tools that allow users to draw different shapes and patterns like: rectangle, circle, arrows, free draw, eraser, et. c.

I’m trying to achieve something like: using a paint bucket, users should be able to fill different parts of a shape, if over that shape are drawn other shapes or patterns.

Maybe this use case helps to understand better my question:

The user draws a circle.

Afterwards he draws lines over that circle so will be split in multiple areas.

The user uses now the paint bucket and tries to fill only the areas of that circle.

I’m wondering if, using konva, is possible to achieve this functionality.

Until now I've manage only to fill entire shapes, similar to this.

Update

Added images for the use case above.

1 & 2. User draws a circle and lines over it:

Using paint bucket user can fill certain areas of that circle:

Any feedback will be very welcomed.

答:
Bad news: What you want cannot be done with Konvajs, as it is designed to work with vectorial images. Each figure is created as a whole by an equation and is "separated" of other figures (as the lines X and Y and the circle are separate in the Snippet below. It is not a raster layer. To do a paint bucket tool in vector graphics is hard.

(See Good news at the end!)

var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height
});

var layer = new Konva.Layer();

var circle = new Konva.Circle({
  x: 180,
  y: 120,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4
});
var lineX = new Konva.Line({
  x: 180, // 180-50
  y: 120,
  points: [-100, 0, 100, 0],
  stroke: 'black',
  strokeWidth: 4
});
var lineY = new Konva.Line({
  x: 180, // 180-50
  y: 120,
  points: [0, -100, 0, 100],
  stroke: 'black',
  strokeWidth: 4
});

circle.on('click', function() {
  var fill = this.fill() == 'red' ? '#00d00f' : 'red';
  this.fill(fill);
  layer.draw();
});

layer.add(circle);
layer.add(lineX);
layer.add(lineY);
stage.add(layer);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f0f0f0;
}</code>```

```

Good news: But you can do it with Canvas, HTML5 and Javascript.

Here you have a good tutorial which includes a DEMO (on top of the page) and the SOURCE CODE to Create a Paint Bucket Tool in HTML5 and JavaScript

Hope this helps you!

Body:
Bad news: What you want cannot be done with Konvajs, as it is designed to work with vectorial images. Each figure is created as a whole by an equation and is "separated" of other figures (as the lines X and Y and the circle are separate in the Snippet below. It is not a raster layer. To do a paint bucket tool in vector graphics is hard.

(See Good news at the end!)

var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
  container: 'container',
  width: width,
  height: height
});

var layer = new Konva.Layer();

var circle = new Konva.Circle({
  x: 180,
  y: 120,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4
});
var lineX = new Konva.Line({
  x: 180, // 180-50
  y: 120,
  points: [-100, 0, 100, 0],
  stroke: 'black',
  strokeWidth: 4
});
var lineY = new Konva.Line({
  x: 180, // 180-50
  y: 120,
  points: [0, -100, 0, 100],
  stroke: 'black',
  strokeWidth: 4
});

circle.on('click', function() {
  var fill = this.fill() == 'red' ? '#00d00f' : 'red';
  this.fill(fill);
  layer.draw();
});

layer.add(circle);
layer.add(lineX);
layer.add(lineY);
stage.add(layer);

body {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #f0f0f0;
}

<script src="https://unpkg.com/konva@3.2.6/konva.min.js"></script>
<div id="container"></div>

Good news: But you can do it with Canvas, HTML5 and Javascript.

Here you have a good tutorial which includes a DEMO (on top of the page) and the SOURCE CODE to Create a Paint Bucket Tool in HTML5 and JavaScript

Hope this helps you!


问:
How to get max row in openpyxl library?
I am trying to get max row which has data from excel using openpyxl library in python
I am using Python 3.7 and openpyxl 2.6.1.
Here is the code I am using:

APIworkbook = openpyxl.load_workbook("../../Excel/myfile.xlsx")
APISheet = APIworkbook["mybook"]
row = APISheet.max_row
print(row)
```

This is printing some random number, but I am expecting the last row which has data filled.

答:
You can try this and get max row count

max_row_count = 0

APIworkbook = openpyxl.load_workbook("../../Excel/myfile.xlsx")
APISheet = APIworkbook["mybook"]
for row in APISheet.rows:
    for cell in row:
        if cell.value:
            max_row_count += 1
            break

print(max_row_count)
```

Title: How to get max row in openpyxl library?

Body:
I am trying to get max row which has data from excel using openpyxl library in python
I am using Python 3.7 and openpyxl 2.6.1.
Here is the code I am using:

APIworkbook = openpyxl.load_workbook("../../Excel/myfile.xlsx")
APISheet = APIworkbook["mybook"]
row = APISheet.max_row
print(row)

This is printing some random number, but I am expecting the last row which has data filled.


问:
Efficient method for counting number of data points inside sphere of fixed radius centered on each data point
I have a database with many data-points each with an x,y,z coordinate. I want to count the number of points that are within a certain distance to neighboring points. Some points will have a pair that is within a radius R, others will not. I simply want to count the number of pairs within some distance. I could easily write an algorithm to do this but it would not be efficient enough (for I would iterate over every single data point).

This seems like something that must already exist in astropy, scipy, etc. but I cannot seem to find what I am looking for. Is there anything out there that accomplishes this?

答:
I don't have direct experience with it but scipy.spatial.distance.pdist may be what you're looking for.

This link may be helpful as well. It gives an example of how to solve the problem as I understand it.


问:
got positional argument error when using decorator in python
I have defined a decorator function in python, but I get positional argument error when using it. This is my code:

```<code>def my_upper_case(func):

    def wrapper():
        return func().upper()

    return wrapper

@my_upper_case
def print_name(name):
    return name

if __name__ == "__main__":
    print(print_name("zeinab"))
</code>```

Returned error is:

```<code>Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(print_name("zeinab"))
TypeError: wrapper() takes no arguments (1 given)
</code>```

I tried running the code with both python 2.7 and python 3.6. Both returned exact error.

答:
As the error says, your wrapper function doesn't accept any arguments. It needs to accept the same args as the function it is wrapping.</p>

```<code>def wrapper(arg):
    return func(arg).upper()
</code>```

Body:
I have defined a decorator function in python, but I get positional argument error when using it. This is my code:

def my_upper_case(func):

    def wrapper():
        return func().upper()

    return wrapper

@my_upper_case
def print_name(name):
    return name

if __name__ == "__main__":
    print(print_name("zeinab"))

Returned error is:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    print(print_name("zeinab"))
TypeError: wrapper() takes no arguments (1 given)

I tried running the code with both python 2.7 and python 3.6. Both returned exact error.

Body:
As the error says, your wrapper function doesn't accept any arguments. It needs to accept the same args as the function it is wrapping.

def wrapper(arg):
    return func(arg).upper()


问:
How do I check that composer package installed in bash script
I'm trying to install composer package if it not installed in bash script. But now it doesn't work, and no_package function always pass

```<code>#!/bin/bash -e

no_package() {
    composer show | grep matchish/laravel-scout-elasticsearch | test
}

if [ no_package ]; then
  composer require "matchish/laravel-scout-elasticsearch"
else
  echo 'Package installed'
fi
</code>```

UPD: Here is solution

```<code>package_installed() {
    composer show | grep matchish/laravel-scout-elasticsearch --quiet
}
if package_installed; then
  echo 'Package installed'
else
  composer require "matchish/laravel-scout-elasticsearch"
fi
</code>```

答:
I tested the test command, and I found that the test command returned the same result no matter what I piped in.

So it is better to run in this way

```<code>package_exist() {
    composer show | grep matchish/laravel-scout-elasticsearch >/dev/null
}

if package_exist; then
    echo 'installed'
else
    echo 'uninstalled'
    echo 'installing matchish/laravel-scout-elasticsearch'
    composer require "matchish/laravel-scout-elasticsearch"
fi
</code>```

Body:
I'm trying to install composer package if it not installed in bash script. But now it doesn't work, and no_package function always pass

#!/bin/bash -e

no_package() {
    composer show | grep matchish/laravel-scout-elasticsearch | test
}

if [ no_package ]; then
  composer require "matchish/laravel-scout-elasticsearch"
else
  echo 'Package installed'
fi

UPD: Here is solution

package_installed() {
    composer show | grep matchish/laravel-scout-elasticsearch --quiet
}
if package_installed; then
  echo 'Package installed'
else
  composer require "matchish/laravel-scout-elasticsearch"
fi

Body:
I tested the test command, and I found that the test command returned the same result no matter what I piped in.

So it is better to run in this way

package_exist() {
    composer show | grep matchish/laravel-scout-elasticsearch >/dev/null
}

if package_exist; then
    echo 'installed'
else
    echo 'uninstalled'
    echo 'installing matchish/laravel-scout-elasticsearch'
    composer require "matchish/laravel-scout-elasticsearch"
fi


问:
How to add customized cell in tableview when user selects cell
I want to add my customized tableviewcell in my tableview when user selects a cell I have some buttons on that customized cell and want to give user option as soon he selects a cell.

Any suggestions and guidance to move on from here?

答: you have to use customize cell when cell is created and change the image of the cell when it will selected.</p>


问:
Custom ggplot2 axis and label formatting
I'm trying to draw labels which look informative, clear and tidy.

I was following example and raised one more question about label and axis formatting.

For example, I have sales data which includes Brand, Categories and Expenditure in EUR. When sum of EUR is big (millions or more) labels look really hard to read and not informative.

As a result, x-axis is in Scientific notation and also looks really uncleanly.

I've manage to format labels in custom way: it shows Eur in thousands.
 geom_text(aes(label= paste(round(EUR/1000,0),"€"), y=pos), colour="white")
Is there an easier or automated way?

As Scientific notation looks really unclear, for axis I tried using scale_y_continuous(formatter = "dollar"), but this seems do not work. Moreover, I was unable to find if there is Eur also implemented instead of dollar. I believe that it would be the best to show y-axis in thousands.
Any solutions?

Also, I enclose reproducible example:

```<code>library(plyr)
library(dplyr)
library(ggplot2)
library(scales)

set.seed(1992)
n=68

Category <- sample(c("Black", "Red", "Blue", "Cyna", "Purple"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:5, n, replace = TRUE, prob = NULL))
EUR <- abs(rnorm(n))*100000

df <- data.frame(Category, Brand, EUR)

df.summary = df %>% group_by(Brand, Category) %>%
  summarise(EUR = sum(EUR)) %>%   # Within each Brand, sum all values in each Category
  mutate( pos = cumsum(EUR)-0.5*EUR)

ggplot(df.summary, aes(x=reorder(Brand,EUR,function(x)+sum(x)), y=EUR, fill=Category)) +
  geom_bar(stat='identity',  width = .7, colour="black", lwd=0.1) +
  geom_text(aes(label=ifelse(EUR>100,paste(round(EUR/1000,0),"€"),""),
                y=pos), colour="white") +
  coord_flip()+
  labs(y="", x="")
</code>```

答:
This also works

```<code>scale_y_continuous(labels = function(x) paste0(x, "€"))
</code>```

You can put any symbol you want in lieu of the €

Body:
I'm trying to draw labels which look informative, clear and tidy.

I was following example and raised one more question about label and axis formatting.

For example, I have sales data which includes Brand, Categories and Expenditure in EUR. When sum of EUR is big (millions or more) labels look really hard to read and not informative.

As a result, x-axis is in Scientific notation and also looks really uncleanly.

I've manage to format labels in custom way: it shows Eur in thousands.
 geom_text(aes(label= paste(round(EUR/1000,0),"€"), y=pos), colour="white")
Is there an easier or automated way?

As Scientific notation looks really unclear, for axis I tried using scale_y_continuous(formatter = "dollar"), but this seems do not work. Moreover, I was unable to find if there is Eur also implemented instead of dollar. I believe that it would be the best to show y-axis in thousands.
Any solutions?

Also, I enclose reproducible example:

library(plyr)
library(dplyr)
library(ggplot2)
library(scales)

set.seed(1992)
n=68

Category <- sample(c("Black", "Red", "Blue", "Cyna", "Purple"), n, replace = TRUE, prob = NULL)
Brand <- sample("Brand", n, replace = TRUE, prob = NULL)
Brand <- paste0(Brand, sample(1:5, n, replace = TRUE, prob = NULL))
EUR <- abs(rnorm(n))*100000

df <- data.frame(Category, Brand, EUR)

df.summary = df %>% group_by(Brand, Category) %>%
  summarise(EUR = sum(EUR)) %>%   # Within each Brand, sum all values in each Category
  mutate( pos = cumsum(EUR)-0.5*EUR)

ggplot(df.summary, aes(x=reorder(Brand,EUR,function(x)+sum(x)), y=EUR, fill=Category)) +
  geom_bar(stat='identity',  width = .7, colour="black", lwd=0.1) +
  geom_text(aes(label=ifelse(EUR>100,paste(round(EUR/1000,0),"€"),""),
                y=pos), colour="white") +
  coord_flip()+
  labs(y="", x="")

Body:
This also works

scale_y_continuous(labels = function(x) paste0(x, "€"))

You can put any symbol you want in lieu of the €


问:
How can you take a panorama picture using Ionic?
How to take a panorama picture using Ionic ? i tried using the camera plugin on ionic but no luck. it just take a simple picture.</p>

答: Extra Camera features such as panorama mode (with multiple images blending etc) are not yet exposed by platforms APIs unfortunately. You can not achieve it in Ionic since current plugins do not have those functions.</p>


问:
How to prevent dispatch group to not crash?
I am using the below code to wait for async tasks to be completed. It works a couple of times and crashes. The updateFromTable always invokes callback() so that the group calls are balanced, but it still crashes.

```<code>- (void)updateFromTable:(Table *)table env:(Env *)env callback:(void (^)(void))callback {
    [someasync usingBlock:^{
        callback()
    }];
}

- (NSString * _Nullable)process {
    JSL * __weak weakSelf = self;
    NSString __block *ret = nil;
    dispatch_group_enter(_dispatchGroup);
    dispatch_async(_repQueue, ^{
        JSL *this = weakSelf;
        [this updateFromTable:[this->_env table] env:this->_env callback:^{
            ret = [some op .. ];
            dispatch_group_leave(this->_dispatchGroup);
        }];
    });
    dispatch_group_wait(_dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC));
    info(@"%@", @"done");
    return ret;
}
</code>```

Any idea why it crashes randomly and how to fix this? Basically, what I am trying to achieve is invoke couple of async tasks, wait for all of them to complete and then proceed with the rest.

Referring: How to wait past dispatch_async before proceeding?

答:
You cannot dereference ivars with -> if this is nil. So, the typical solution is to create strong reference that can’t be deallocated while the closure runs, and return if it’s nil:

```<code>- (NSString * _Nullable)process {
    typeof(self) __weak weakSelf = self;
    [self asynchronousMethodWithCompletion:^{
        typeof(self) strongSelf = weakSelf;
        if (!strongSelf) { return; }

        // can now safely use `strongSelf` here
    });

    ...
}
</code>```

This is “weakSelf-strongSelf dance”. You use it in situations where you need to make sure that self isn’t nil when you use it, e.g. dereferencing ivars (strongSelf->ivar) .

Thus:

```<code>- (NSString * _Nullable)process {
    typeof(self) __weak weakSelf = self;
    NSString __block *ret = nil;
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_async(_repQueue, ^{
        typeof(self) strongSelf = weakSelf;
        if (!strongSelf) { return; }

        [strongSelf updateFromTable:[strongSelf->_env table] env:strongSelf->_env callback:^{
            ret = [some op .. ];
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    info(@"%@", @"done");
    return ret;
}
</code>```

A few other observations:

The dispatch group should be a local variable of the method rather than an ivar. There’s no need for anything else in your code referencing this group.

Make sure that your dispatch_group_leave calls don’t exceed the number of dispatch_group_enter calls (i.e. that this completion handler block isn’t called multiple times).

I’d suggest waiting for DISPATCH_TIME_FOREVER (assuming you want it to really wait for it to finish).

Also, if these are properties (which I’m guessing they are on the basis of the underscores), then using self.env rather than self->_env is safer, as it won’t crash if self is nil, but rather will just return nil.

I must confess that this still doesn’t look right (e.g. if updateFromTable is asynchronous already, why bother dispatching this asynchronously to _repQueue; if it is synchronous, then again, why dispatch this asynchronously only to wait for it). But it’s impossible to comment further without seeing the updateFromTable implementation.

Or, better, make the method asynchronous:

```<code>- (void)processWithCompletion:(void (^)(NSString *))callback {
    typeof(self) __weak weakSelf = self;
    dispatch_async(_repQueue, ^{
        typeof(self) strongSelf = weakSelf;
        if (!strongSelf) { return; }

        [strongSelf updateFromTable:[strongSelf->_env table] env:strongSelf->_env callback:^{
            NSString *ret = [some op .. ];
            callback(ret);
        }];
    });
}
</code>```

Body:
I am using the below code to wait for async tasks to be completed. It works a couple of times and crashes. The updateFromTable always invokes callback() so that the group calls are balanced, but it still crashes.

- (void)updateFromTable:(Table *)table env:(Env *)env callback:(void (^)(void))callback {
    [someasync usingBlock:^{
        callback()
    }];
}

- (NSString * _Nullable)process {
    JSL * __weak weakSelf = self;
    NSString __block *ret = nil;
    dispatch_group_enter(_dispatchGroup);
    dispatch_async(_repQueue, ^{
        JSL *this = weakSelf;
        [this updateFromTable:[this->_env table] env:this->_env callback:^{
            ret = [some op .. ];
            dispatch_group_leave(this->_dispatchGroup);
        }];
    });
    dispatch_group_wait(_dispatchGroup, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC));
    info(@"%@", @"done");
    return ret;
}

Any idea why it crashes randomly and how to fix this? Basically, what I am trying to achieve is invoke couple of async tasks, wait for all of them to complete and then proceed with the rest.

Referring: How to wait past dispatch_async before proceeding?

Body:
You cannot dereference ivars with -> if this is nil. So, the typical solution is to create strong reference that can’t be deallocated while the closure runs, and return if it’s nil:

- (NSString * _Nullable)process {
    typeof(self) __weak weakSelf = self;
    [self asynchronousMethodWithCompletion:^{
        typeof(self) strongSelf = weakSelf;
        if (!strongSelf) { return; }

        // can now safely use `strongSelf` here
    });

    ...
}

This is “weakSelf-strongSelf dance”. You use it in situations where you need to make sure that self isn’t nil when you use it, e.g. dereferencing ivars (strongSelf->ivar) .

Thus:

- (NSString * _Nullable)process {
    typeof(self) __weak weakSelf = self;
    NSString __block *ret = nil;
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    dispatch_async(_repQueue, ^{
        typeof(self) strongSelf = weakSelf;
        if (!strongSelf) { return; }

        [strongSelf updateFromTable:[strongSelf->_env table] env:strongSelf->_env callback:^{
            ret = [some op .. ];
            dispatch_group_leave(group);
        }];
    });
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    info(@"%@", @"done");
    return ret;
}

A few other observations:

The dispatch group should be a local variable of the method rather than an ivar. There’s no need for anything else in your code referencing this group.

Make sure that your dispatch_group_leave calls don’t exceed the number of dispatch_group_enter calls (i.e. that this completion handler block isn’t called multiple times).

I’d suggest waiting for DISPATCH_TIME_FOREVER (assuming you want it to really wait for it to finish).

Also, if these are properties (which I’m guessing they are on the basis of the underscores), then using self.env rather than self->_env is safer, as it won’t crash if self is nil, but rather will just return nil.

I must confess that this still doesn’t look right (e.g. if updateFromTable is asynchronous already, why bother dispatching this asynchronously to _repQueue; if it is synchronous, then again, why dispatch this asynchronously only to wait for it). But it’s impossible to comment further without seeing the updateFromTable implementation.

Or, better, make the method asynchronous:

- (void)processWithCompletion:(void (^)(NSString *))callback {
    typeof(self) __weak weakSelf = self;
    dispatch_async(_repQueue, ^{
        typeof(self) strongSelf = weakSelf;
        if (!strongSelf) { return; }

        [strongSelf updateFromTable:[strongSelf->_env table] env:strongSelf->_env callback:^{
            NSString *ret = [some op .. ];
            callback(ret);
        }];
    });
}


问:
In Swift, how do you detect which UIControlEvents triggered the action?
I currently have 4 UITextField's

```<code>@IBOutlet weak var fNameTextField: UITextField!
@IBOutlet weak var lNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!
</code>```

and I want to keep track of their various events:

```<code>[UIControlEvents.EditingChanged, UIControlEvents.EditingDidBegin, UIControlEvents.EditingDidEnd ]
</code>```

but I don't want to have 3 event separate event handlers so I created a single function like this. This function does a great job of telling me which UITextField fired an event but it doesn't tell me which event was triggered.:

```<code>fNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
lNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
emailTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
phoneTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)

func onChangeTextField(sender:UITextField){
    switch(sender){
        case fNameTextField:
            print("First Name")
        case lNameTextField:
            print("Last Name")
        case emailTextField:
            print("E-mail")
        case phoneTextField:
            print("Phone")
        default: break
    }
}
</code>```

How can I print both the name of the sender and the name of the event triggered (ex: .EditingDidEnd, .EditingDidEnd, .EditingDidEnd)?

Ideally, I do not want to write multiple event handlers, I'd prefer a single function.

Something like this:

```<code>func onChangeTextField(sender:UITextField){
    switch(sender.eventTriggerd){
        case UIControlEvents.EditingChanged:
            println("EditingChanged")
        case UIControlEvents.EditingDidBegin:
            println("EditingDidBegin")
        case UIControlEvents.EditingDidEnd:
            println("EditingDidEnd")
        default: break
    }
}
</code>```

答:
Alternatively you could use this little helper which converts a UIEvent (or UITouch) to a UIControl.Event. It works by checking the Phase of the touch, getting its location in the sending view, and comparing it to the previous location. If you use UIEvent it will use the first touch.

Be forewarned, however: it cannot handle .touchDownRepeat well. The tapCount property of UIEvent has a longer timing duration than a normally triggered .touchDownRepeat. Additionally, it seems to send multiple actions on .touchDownRepeat.

And, of course, it doesn't handle the other UIControl.Event like .editingDidBegin, etc.

```<code>public extension UIEvent {

    func firstTouchToControlEvent() -> UIControl.Event? {
            guard let touch = self.allTouches?.first else {
                print("firstTouchToControlEvent() Error: couldn't get the first touch. \(self)")
            return nil
        }
        return touch.toControlEvent()
    }

}

public extension UITouch {

    func toControlEvent() -> UIControl.Event? {
        guard let view = self.view else {
            print("UITouch.toControlEvent() Error: couldn't get the containing view. \(self)")
            return nil
        }
        let isInside = view.bounds.contains(self.location(in: view))
        let wasInside = view.bounds.contains(self.previousLocation(in: view))
        switch self.phase {
        case .began:
            if isInside {
                if self.tapCount > 1 {
                    return .touchDownRepeat
                }
                return .touchDown
            }
            print("UITouch.toControlEvent() Error: unexpected touch began outs1ide of view. \(self)")
            return nil
        case .moved:
            if isInside && wasInside {
                return .touchDragInside
            } else if isInside && !wasInside {
                return .touchDragEnter
            } else if !isInside && wasInside {
                return .touchDragExit
            } else if !isInside && !wasInside {
                return .touchDragOutside
            } else {
                print("UITouch.toControlEvent() Error: couldn't determine touch moved boundary. \(self)")
                return nil
            }
        case .ended:
            if isInside {
                return .touchUpInside
            } else {
                return.touchUpOutside
            }
        case .cancelled:
            return .touchCancel
        default:
            print("UITouch.toControlEvent() Warning: couldn't handle touch event. \(self)")
            return nil
        }
    }

}
</code>```

Use it like so:

```<code>class TestControl: UIControl {

    func setupTouchEvent() {
        self.addTarget(self, action: #selector(handleTouchEvent(_:forEvent:)), for: .allTouchEvents)
    }

    @objc func handleTouchEvent(_ sender: TestControl, forEvent event: UIEvent) {
        guard let controlEvent = event.firstTouchToControlEvent() else {
            print("Error: couldn't convert event to control event: \(event)")
            return
        }
        switch controlEvent {
        case .touchDown:
            print("touchDown")
        case .touchDownRepeat:
            print("touchDownRepeat")
        case .touchUpInside:
            print("touchUpInside")
        case .touchUpOutside:
            print("touchUpOutside")
        case .touchDragEnter:
            print("touchDragEnter")
        case .touchDragExit:
            print("touchDragExit")
        case .touchDragInside:
            print("touchDragInside")
        case .touchDragOutside:
            print("touchDragOutside")
        default:
            print("Error: couldn't convert event to control event, or unhandled event case: \(event)")
        }
    }
}
</code>```

To implement .touchDownRepeat you could wrap this method in a little class and save the time on each touch down, or simply save the tap time in your control.

Body:
I currently have 4 UITextField's

@IBOutlet weak var fNameTextField: UITextField!
@IBOutlet weak var lNameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var phoneTextField: UITextField!

and I want to keep track of their various events:

[UIControlEvents.EditingChanged, UIControlEvents.EditingDidBegin, UIControlEvents.EditingDidEnd ]

but I don't want to have 3 event separate event handlers so I created a single function like this. This function does a great job of telling me which UITextField fired an event but it doesn't tell me which event was triggered.:

fNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
lNameTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
emailTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)
phoneTextField.addTarget(self, action: "onChangeTextField:", forControlEvents: UIControlEvents.AllTouchEvents)

func onChangeTextField(sender:UITextField){
    switch(sender){
        case fNameTextField:
            print("First Name")
        case lNameTextField:
            print("Last Name")
        case emailTextField:
            print("E-mail")
        case phoneTextField:
            print("Phone")
        default: break
    }
}

How can I print both the name of the sender and the name of the event triggered (ex: .EditingDidEnd, .EditingDidEnd, .EditingDidEnd)?

Ideally, I do not want to write multiple event handlers, I'd prefer a single function.

Something like this:

func onChangeTextField(sender:UITextField){
    switch(sender.eventTriggerd){
        case UIControlEvents.EditingChanged:
            println("EditingChanged")
        case UIControlEvents.EditingDidBegin:
            println("EditingDidBegin")
        case UIControlEvents.EditingDidEnd:
            println("EditingDidEnd")
        default: break
    }
}

Body:
Alternatively you could use this little helper which converts a UIEvent (or UITouch) to a UIControl.Event. It works by checking the Phase of the touch, getting its location in the sending view, and comparing it to the previous location. If you use UIEvent it will use the first touch.

Be forewarned, however: it cannot handle .touchDownRepeat well. The tapCount property of UIEvent has a longer timing duration than a normally triggered .touchDownRepeat. Additionally, it seems to send multiple actions on .touchDownRepeat.

And, of course, it doesn't handle the other UIControl.Event like .editingDidBegin, etc.

public extension UIEvent {

    func firstTouchToControlEvent() -> UIControl.Event? {
            guard let touch = self.allTouches?.first else {
                print("firstTouchToControlEvent() Error: couldn't get the first touch. \(self)")
            return nil
        }
        return touch.toControlEvent()
    }

}

public extension UITouch {

    func toControlEvent() -> UIControl.Event? {
        guard let view = self.view else {
            print("UITouch.toControlEvent() Error: couldn't get the containing view. \(self)")
            return nil
        }
        let isInside = view.bounds.contains(self.location(in: view))
        let wasInside = view.bounds.contains(self.previousLocation(in: view))
        switch self.phase {
        case .began:
            if isInside {
                if self.tapCount > 1 {
                    return .touchDownRepeat
                }
                return .touchDown
            }
            print("UITouch.toControlEvent() Error: unexpected touch began outs1ide of view. \(self)")
            return nil
        case .moved:
            if isInside && wasInside {
                return .touchDragInside
            } else if isInside && !wasInside {
                return .touchDragEnter
            } else if !isInside && wasInside {
                return .touchDragExit
            } else if !isInside && !wasInside {
                return .touchDragOutside
            } else {
                print("UITouch.toControlEvent() Error: couldn't determine touch moved boundary. \(self)")
                return nil
            }
        case .ended:
            if isInside {
                return .touchUpInside
            } else {
                return.touchUpOutside
            }
        case .cancelled:
            return .touchCancel
        default:
            print("UITouch.toControlEvent() Warning: couldn't handle touch event. \(self)")
            return nil
        }
    }

}

Use it like so:

class TestControl: UIControl {

    func setupTouchEvent() {
        self.addTarget(self, action: #selector(handleTouchEvent(_:forEvent:)), for: .allTouchEvents)
    }

    @objc func handleTouchEvent(_ sender: TestControl, forEvent event: UIEvent) {
        guard let controlEvent = event.firstTouchToControlEvent() else {
            print("Error: couldn't convert event to control event: \(event)")
            return
        }
        switch controlEvent {
        case .touchDown:
            print("touchDown")
        case .touchDownRepeat:
            print("touchDownRepeat")
        case .touchUpInside:
            print("touchUpInside")
        case .touchUpOutside:
            print("touchUpOutside")
        case .touchDragEnter:
            print("touchDragEnter")
        case .touchDragExit:
            print("touchDragExit")
        case .touchDragInside:
            print("touchDragInside")
        case .touchDragOutside:
            print("touchDragOutside")
        default:
            print("Error: couldn't convert event to control event, or unhandled event case: \(event)")
        }
    }
}

To implement .touchDownRepeat you could wrap this method in a little class and save the time on each touch down, or simply save the tap time in your control.


问:
Node Creation Takes too long and failed
I installed Blockchain platform v2 beta then I tried to configure it and add nodes.
My Question is:
is there anyone faced long delay in node creation like CA node for example.
I faced this problem and cannot find from where I can check logs.

Notification Error Image:

Note:
the node did not be created till now since 2 days.

答:
As per the IBM Cloud documentation,

If you use Enterprise Plan networks, you can view component logs in a
  text file format. If you use Starter Plan networks, component logs are
  gathered by the IBM Cloud Log Analysis service and
  you can view the logs in Kibana.

Each component generates logs from different activities. This is
  because each component plays different roles within the Hyperledger
  Fabric network architecture and transaction flows.

Certificate Authority logs The Certificate Authority manages the
  identity of participants within the network. In Certificate Authority
  logs, you can find logs from when participants generate public and
  private keys to communicate with the network (enroll), or when new
  members, peers, or applications register with the Certificate
  Authority. You can also use the CA logs to debug if there are any
  problems with certificate verification.

So, you should be able to see the logs in the IBM Cloud Log Analysis service. By default, your logs are collected by the Lite Plan of the Log Analysis service. This plan is free and stores your logs for three days before discarding them. It also allows you to search only the first 500 MB of your logs per day. If your network logs exceed 500 MB, you cannot view new logs in Kibana. If your network generates more than 500 MB of logs, or you would like to retain your logs for more than three days, you can upgrade to a paid version of the Log Analysis Service.

For more info, refer the IBM cloud docs here

Title: Node Creation Takes too long and failed


问:
Who uses POSIX realtime signals and why?
I am not being flip I really don't get it.  I just read a whole bunch of material on them and I can't figure out the use case.  I am not talking talking so much about the API for which the advantages over things like signal() are clear enough.  Rather it seems RT signals are meant to be user space generated but to what end?  The only use seems to be a primitive IPC but everything points to them being a lousy form of IPC (e.g. awkward, limited information, not particularly efficient, etc).

So where and how are they used?

答:
It's an old question, but still.

POSIX threads on Linux in glibc (NPTL) are implemented using two real time signals. They are hidden from user (by adjusting min/max number constants). All events where library call must be propagated to all threads (like setuid) are done via those: calling thread sends signal to all threads to apply the change, waits for acknowledgement and continues.


问:
How to hide and show menu-items on action bar
I have a menu item system implemented into my action bar, I am trying to get a menu item to become invisible once clicked and then to become visible again after clicking a different menu item.

The reason for this is to prevent a menu item getting clicked more than once.

I have done the following attempt below however, I get a null pointer exception error. I believe I may need to implement some if statements here but I'm not sure how to go about it.

```<code>@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.tasklistmenu,menu);

    return true;
}//OnCreateOptionsMenu

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.allTasks:

            item.setVisible(false);

            MenuItem notStartedStatus = findViewById(R.id.notStartedStatus);
            notStartedStatus.setVisible(true);

            MenuItem inProgressStatus = findViewById(R.id.inProgressStatus);
            inProgressStatus.setVisible(true);

            MenuItem completeStatus = findViewById(R.id.completeStatus);
            completeStatus.setVisible(true);
</code>```

Log error

```<code>Attempt to invoke interface method 'android.view.MenuItem
android.view.MenuItem.setVisible(boolean)' on a null object reference
</code>```

NEW CODE

```<code> @Override
public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem allTasks = menu.findItem(R.id.allTasks);
    MenuItem notStartedStatus = menu.findItem(R.id.notStartedStatus);
    MenuItem completeStatus = menu.findItem(R.id.completeStatus);
    MenuItem inProgressStatus = menu.findItem(R.id.inProgressStatus);

    if(tasksIsVisible) {
        allTasks.setVisible(true);
    } else {
        allTasks.setVisible(false);
    }

    if(notStartedIsVisible) {
        notStartedStatus.setVisible(true);
    } else {
        notStartedStatus.setVisible(false);
    }

    if(completeIsVisible) {
        completeStatus.setVisible(true);
    } else {
        completeStatus.setVisible(false);
    }

    if(inProgressIsVisible) {
        inProgressStatus.setVisible(true);
    } else {
        inProgressStatus.setVisible(false);
    }

    return true;

}//OnPrepareOptions

 @Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.allTasks:

            tasksIsVisible = false;
            invalidateOptionsMenu();
</code>```

答:
Its not enough to change the isVisible variable. You have to call the setVisible() method every time you want to change the visibility. That method does more than just setting a boolean value, so just changing a boolean value will not do.

After changing the isVisible value to false, you need to call invalidateOptionsMenu() which will re-launch the menu by calling onPrepareOptionsMenu() again.

```<code>public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem notStartedStatus = menu.findItem(R.id.notStartedStatus);
    if(isVisible)
    {
        notStartedStatus.setVisible(true);
    }
    else
    {
        notStartedStatus.setVisible(false);
    }
    return true;
}
</code>```

Try this code for making the menu items unvisible:

```<code>...
isVisible = false;
invalidateOptionsMenu();
...
</code>```

Body:
I have a menu item system implemented into my action bar, I am trying to get a menu item to become invisible once clicked and then to become visible again after clicking a different menu item.

The reason for this is to prevent a menu item getting clicked more than once.

I have done the following attempt below however, I get a null pointer exception error. I believe I may need to implement some if statements here but I'm not sure how to go about it.

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.tasklistmenu,menu);

    return true;
}//OnCreateOptionsMenu

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.allTasks:

            item.setVisible(false);

            MenuItem notStartedStatus = findViewById(R.id.notStartedStatus);
            notStartedStatus.setVisible(true);

            MenuItem inProgressStatus = findViewById(R.id.inProgressStatus);
            inProgressStatus.setVisible(true);

            MenuItem completeStatus = findViewById(R.id.completeStatus);
            completeStatus.setVisible(true);

Log error

Attempt to invoke interface method 'android.view.MenuItem
android.view.MenuItem.setVisible(boolean)' on a null object reference

NEW CODE

 @Override
public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem allTasks = menu.findItem(R.id.allTasks);
    MenuItem notStartedStatus = menu.findItem(R.id.notStartedStatus);
    MenuItem completeStatus = menu.findItem(R.id.completeStatus);
    MenuItem inProgressStatus = menu.findItem(R.id.inProgressStatus);

    if(tasksIsVisible) {
        allTasks.setVisible(true);
    } else {
        allTasks.setVisible(false);
    }

    if(notStartedIsVisible) {
        notStartedStatus.setVisible(true);
    } else {
        notStartedStatus.setVisible(false);
    }

    if(completeIsVisible) {
        completeStatus.setVisible(true);
    } else {
        completeStatus.setVisible(false);
    }

    if(inProgressIsVisible) {
        inProgressStatus.setVisible(true);
    } else {
        inProgressStatus.setVisible(false);
    }

    return true;

}//OnPrepareOptions

 @Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {

        case R.id.allTasks:

            tasksIsVisible = false;
            invalidateOptionsMenu();

Body:
Its not enough to change the isVisible variable. You have to call the setVisible() method every time you want to change the visibility. That method does more than just setting a boolean value, so just changing a boolean value will not do.

After changing the isVisible value to false, you need to call invalidateOptionsMenu() which will re-launch the menu by calling onPrepareOptionsMenu() again.

public boolean onPrepareOptionsMenu(Menu menu)
{
    MenuItem notStartedStatus = menu.findItem(R.id.notStartedStatus);
    if(isVisible)
    {
        notStartedStatus.setVisible(true);
    }
    else
    {
        notStartedStatus.setVisible(false);
    }
    return true;
}

Try this code for making the menu items unvisible:

...
isVisible = false;
invalidateOptionsMenu();
...


问:
Anonymous user form submission drupal 7
I have a situation where after doing the basic registration the user is redirected to a page where he needs to fill a small form.

i aim at implementing the hook_user_insert and hook_menu to do something like this

```<code>function registration_user_insert(&$edit, $account, $category){
drupal_goto('splan/'.$edit['uid']);
}

function registration_menu() {
$items['splan/%'] = array(
'title' => 'Select a Plan',
'page callback' => 'drupal_get_form',
'page arguments' => array('selectplan_form'),
'access callback' => TRUE,
'type' => MENU_CALLBACK
);
return $items;
}
</code>```

In selectplan_form i will define my new form and then using the uid i would save data into user table.

Now what is happening is after the basic user registration form is being submitted the redirection to splan/uid is happening but i also get the following error.

```<code>You are not authorized to access this page.
</code>```

Now i have changed permissions to allow anony. users to create and edit webform but still the problem exists.

Please help!!!!!!!!

答:
Try removing 'access callback' => TRUE, and add 'access arguments' => array('access content'), instead.

Perhaps you forgot to clear the cache?

Title: Anonymous user form submission drupal 7

Body:
I have a situation where after doing the basic registration the user is redirected to a page where he needs to fill a small form.

i aim at implementing the hook_user_insert and hook_menu to do something like this

function registration_user_insert(&$edit, $account, $category){
drupal_goto('splan/'.$edit['uid']);
}

function registration_menu() {
$items['splan/%'] = array(
'title' => 'Select a Plan',
'page callback' => 'drupal_get_form',
'page arguments' => array('selectplan_form'),
'access callback' => TRUE,
'type' => MENU_CALLBACK
);
return $items;
}

In selectplan_form i will define my new form and then using the uid i would save data into user table.

Now what is happening is after the basic user registration form is being submitted the redirection to splan/uid is happening but i also get the following error.

You are not authorized to access this page.

Now i have changed permissions to allow anony. users to create and edit webform but still the problem exists.

Please help!!!!!!!!


问:
What does (x:) mean in haskell
What does the x: mean in this Code

Implementation of inits using foldr

inits :: [a] -> [[a]]
inits = foldr ( \ x y -> [] : (map (x:) y) ) [[]]
```

答:
It's a function of a single argument that conses x to some list:

```<code>(x:) [] => [x]
(x:) [1, 2] => [x, 1, 2]
</code>```

Here "conses" means "prepends a value to some list". cons is the "canonical" name of a function that does this. So, the : function is the cons function.

Title: What does (x:) mean in haskell

Body:
It's a function of a single argument that conses x to some list:

(x:) [] => [x]
(x:) [1, 2] => [x, 1, 2]

Here "conses" means "prepends a value to some list". cons is the "canonical" name of a function that does this. So, the : function is the cons function.


问:
Getting json object data into html front end in Angular
I am returning a JSON array Object from an external API which I want to show in the HTML view on Angular front-end. But the view is not loading with below error

Output in console

ERROR Error: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."
ERROR CONTEXT
Object { view: {…}, nodeIndex: 3, nodeDef: {…}, elDef: {…}, elView: {…} }

```<code>getGifs() {
this.getData().subscribe(data => {
  console.log(data);
  this.data = data;
})
}
</code>```

In console logs I can see result as,

```<code>data: Array(25) [ {…}, {…}, {…}, …
meta: Object { status: 200, msg: "OK", response_id:       "5cea7c49386968693259fc04" }
pagination: Object { total_count: 2447, count: 25, offset: 0 }
<prototype>: Object { … }
</code>```

How can I read this data variable in my HTML page. Tried iterating with ngfor but it fails.

答:
You should assign the data property of the response to render on the HTML,

```<code>this.data = data.data;
</code>```

and render in HTML as

```<code>  <ul>
    <li *ngFor="let item of data">
       {{item.type}}. {{item.slug}}
    </li>
  </ul>
</code>```

EDIT

```<code>this.getData().subscribe((data:any) => {
  console.log(data);
  this.data = data.data;
})
</code>```

Body:
I am returning a JSON array Object from an external API which I want to show in the HTML view on Angular front-end. But the view is not loading with below error

Output in console

ERROR Error: "Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays."
ERROR CONTEXT
Object { view: {…}, nodeIndex: 3, nodeDef: {…}, elDef: {…}, elView: {…} }

getGifs() {
this.getData().subscribe(data => {
  console.log(data);
  this.data = data;
})
}

In console logs I can see result as,

data: Array(25) [ {…}, {…}, {…}, …
meta: Object { status: 200, msg: "OK", response_id:       "5cea7c49386968693259fc04" }
pagination: Object { total_count: 2447, count: 25, offset: 0 }
<prototype>: Object { … }

How can I read this data variable in my HTML page. Tried iterating with ngfor but it fails.

Body:
You should assign the data property of the response to render on the HTML,

this.data = data.data;

and render in HTML as

  <ul>
    <li *ngFor="let item of data">
       {{item.type}}. {{item.slug}}
    </li>
  </ul>

EDIT

this.getData().subscribe((data:any) => {
  console.log(data);
  this.data = data.data;
})