问:
Convert python list to bytearray and back
I have a list: ['qwe', 600, 0.1].

The goal is to convert the whole list to bytearray. I need to save types of items in list after decoding.

I have tried like this:

```<code>list = ['qwe', 600, 0.1]
new_list = []
for i in list:
   list_1 += [str(i)]
bytes = bytearray(','.join(new_list).encode('utf-8'))

#decoding is ugly:
item_list = [b.decode('utf-8') for b in bytes]
new_item_list = []
   for item in item_list:
      try:
         new_item_list += [int(item)]
      except ValueError:
         new_item_list += [item]
      final_list = []
      for item in new_item_list:
         if type(item) == int:
            final_list += [item]
         else:
            try:
               final_list += [float(item)]
            except ValueError:
               final_list += [item]
</code>```

The disadvantage of this method is

1)Converting data to str loosing original types of items

2)first item in list can be for example '123' or 'qwe,rty' - that leads to a bug while decoding

I have also thought of this logic:

```<code>list = ['qwe', 600, 0.1]
list_bytes=[]
for i in list:
   if type(i) == str:
      list_bytes += [bytearray(i.encode('utf-8'))]
   if type(i) == int or float:
      list_bytes += [i.to_bytes(2,byteorder='big')]
bytes = ','.join(list_bytes)
</code>```

but I was stacked with decoding, don't know how to test whether an encoded item in list_bytes is str, int or float.

答:
You can use pickle:

import pickle

data = ['qwe', 600, 0.1]

x = bytearray(pickle.dumps(data))
# x = bytearray(b'\x80\x04\x95\x17\x00\x00\x00\x00\x00\...')
y = pickle.loads(x)
# y = ['qwe', 600, 0.1]
```

Body:
I have a list: ['qwe', 600, 0.1].

The goal is to convert the whole list to bytearray. I need to save types of items in list after decoding.

I have tried like this:

list = ['qwe', 600, 0.1]
new_list = []
for i in list:
   list_1 += [str(i)]
bytes = bytearray(','.join(new_list).encode('utf-8'))

#decoding is ugly:
item_list = [b.decode('utf-8') for b in bytes]
new_item_list = []
   for item in item_list:
      try:
         new_item_list += [int(item)]
      except ValueError:
         new_item_list += [item]
      final_list = []
      for item in new_item_list:
         if type(item) == int:
            final_list += [item]
         else:
            try:
               final_list += [float(item)]
            except ValueError:
               final_list += [item]

The disadvantage of this method is

1)Converting data to str loosing original types of items

2)first item in list can be for example '123' or 'qwe,rty' - that leads to a bug while decoding

I have also thought of this logic:

list = ['qwe', 600, 0.1]
list_bytes=[]
for i in list:
   if type(i) == str:
      list_bytes += [bytearray(i.encode('utf-8'))]
   if type(i) == int or float:
      list_bytes += [i.to_bytes(2,byteorder='big')]
bytes = ','.join(list_bytes)

but I was stacked with decoding, don't know how to test whether an encoded item in list_bytes is str, int or float.


来源: stackexchange

问:
Laravel Gate custom response
I have laravel 5.5 application and i use gates to authorise users. When the authorisation fails, the response is This action is unauthorized How can i overwrite this response? I want to offer users a custom response.

The way i implemented it is by defining  gates in AuthServiceProvider class and then using these gates with the middleware in my routes. In later laravel versions there is something like:

```<code>Gate::define('edit-settings', function ($user) {
    return $user->isAdmin
                ? Response::allow()
                : Response::deny('You must be a super administrator.');
});
</code>```

But allow and deny methods don't exist in Laravel 5.5

答:
If you have a look at the HandlesAuthorization policy trait that handles custom messages, you can see that it throws a AuthorizationException with a custom message:

```<code>protected function deny($message = 'This action is unauthorized.')
{
    throw new AuthorizationException($message);
}
</code>```

So you should be able to do the same in your guard, something like this:

```<code>use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Gate;

Gate::define('edit-settings', function ($user) {
    if (! $user->isAdmin) {
        throw new AuthorizationException('You must be a super administrator.');
    }

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

ContentLicense: CC BY-SA 4.0

Title: Laravel Gate custom response

Body:
I have laravel 5.5 application and i use gates to authorise users. When the authorisation fails, the response is This action is unauthorized How can i overwrite this response? I want to offer users a custom response.

The way i implemented it is by defining  gates in AuthServiceProvider class and then using these gates with the middleware in my routes. In later laravel versions there is something like:

Gate::define('edit-settings', function ($user) {
    return $user->isAdmin
                ? Response::allow()
                : Response::deny('You must be a super administrator.');
});

But allow and deny methods don't exist in Laravel 5.5

Body:
If you have a look at the HandlesAuthorization policy trait that handles custom messages, you can see that it throws a AuthorizationException with a custom message:

protected function deny($message = 'This action is unauthorized.')
{
    throw new AuthorizationException($message);
}

So you should be able to do the same in your guard, something like this:

use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Support\Facades\Gate;

Gate::define('edit-settings', function ($user) {
    if (! $user->isAdmin) {
        throw new AuthorizationException('You must be a super administrator.');
    }

    return true;
});


问:
mp3 file corrupted after downloading it from libcurl
I'm using libcurl to access the IBM Watson API, and I'm downloading an mp3 file, but the downloaded file is corrupted. I was expecting a "hello world" message, but instead, I get either a corrupted mp3 file or the sounds of hell. I guess that the error is coming from when I convert the response to a const char * and it lost data because I'm writing binary data and C++ thinks that the null keywords are string enders. It outputs two different strings. Is there any fix for this?

Code:

#include <iostream>
#include <fstream>
#include <string>
#include <curl/curl.h>
size_t CurlWrite_CallbackFunc_StdString(void *contents, size_t size, size_t nmemb, std::string *s)
{
    size_t newLength = size * nmemb;
    try
    {
        s->append((char*)contents, newLength);
    }
    catch (std::bad_alloc &e)
    {
        return 0;
    }
    return newLength;
}
std::string CurlGetResponse(std::string url) {
    CURL *curl;
    CURLcode res;

    curl_global_init(CURL_GLOBAL_DEFAULT);

    curl = curl_easy_init();
    std::string response;

    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_USERNAME, "apikey");
        curl_easy_setopt(curl, CURLOPT_PASSWORD, "API Key");

        curl_easy_setopt(curl, CURLOPT_URL, url);

        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); //only for https
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); //only for https
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        res = curl_easy_perform(curl);
        if (res != CURLE_OK)
        {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
        }
        curl_easy_cleanup(curl);
    }
    return response;
}
int main()
{
    std::string response = CurlGetResponse("url");
    std::cout << response.data();
    std::cout << response;
    std::fstream file;
    file.open("C:\\Users\\maste\\HelloWorld_1.mp3", std::ios::binary);
    file.write(response, sizeof(response));
    file.close();
    return 0;
}
```

答:
The statement

```<code>file.write(response, sizeof(response));
</code>```

contains two errors:

First of all it passes the std::string object as an argument, but write expects a pointer to the bytes to write. You need to pass e.g. response.data().

The second problem (which I also mentioned in the comments) is that sizeof(response) is the size of the std::string object itself, not the string it contains. You need to use response.size() to get the size of the actual string.

All in all the statement should look like:

```<code>file.write(response.data(), response.size());
</code>```

Body:
The statement

file.write(response, sizeof(response));

contains two errors:

First of all it passes the std::string object as an argument, but write expects a pointer to the bytes to write. You need to pass e.g. response.data().

The second problem (which I also mentioned in the comments) is that sizeof(response) is the size of the std::string object itself, not the string it contains. You need to use response.size() to get the size of the actual string.

All in all the statement should look like:

file.write(response.data(), response.size());


问:
Exchange references between two same-level components
I have two custom-components that are spawned by a common parent with different data as two tabs on mat-tab-group.

<mat-tab-group>
  <mat-tab label="TAB1">
    <ng-template matTabContent>
      <custom-component [data]="tab1data"></custom-component>
    </ng-template>
  </mat-tab>
  <mat-tab label="TAB2">
    <ng-template matTabContent>
      <custom-component [data]="tab2data"></custom-component>
    </ng-template>
  </mat-tab>
</mat-tab-group>
```

<p>The <code>data</code> is a setter that sets the internal <code>_data</code> and wraps it in <code>MatTableDataSource</code>:  </p>

<pre class="lang-js prettyprint-override"><code>@Input()
set data(val: Data[]) {
    this._data = val;
    this.loadData();
}

loadData(): void {
    this.dataSource = new MatTableDataSource<Data>(this._data);
    this.dataSource.sort = this.sort;
}
</code>```

I have a situation where actions for component on the first tab should affect data on the other tab.
Is there any way to pass component references, so I could change _data and call loadData() from other component?

答:
From your first tab you can emit an output on dataChange to its parent component.

In Custom Component have a output like

```<code>@Output() public dataChange = new EventEmitter();
</code>```

on change of data emit this event like :-

```<code>this.dataChange.emit('changed data');
</code>```

In your parent component where the selector of this component is, change the selector to :-

HTML :-

```<code><custom-component [data]="tab1data" (dataChange)="modifyDataTab2($event)"></custom-component>
</code>```

TS :-

```<code>modifyDataTab2(firstTabData) {
   this.tab2Data = firstTabData;
   // or you can make other changes.
}
</code>```

Now because tab2 is already having tab2Data as input your loadData() will automatically be invoked.

If you want to modify data of tab1 on tab 2 change, no need to change the tab component again, each instance will have its own output. change will be in parent only. that will be :-

HTML :-

```<code><custom-component [data]="tab2data" (dataChange)="modifyDataTab1($event)"></custom-component>
</code>```

TS :-

```<code>modifyDataTab1(secondTabData) {
   this.tab1Data = secondTabData;
   // or you can make other changes.
}
</code>```

That's the benefit of having a common parent. if two childs want to communicate, they should do it via parent. because any data change in parent that is passed as an input, will trigger the changes required in child automatically.

Body:
I have two custom-components that are spawned by a common parent with different data as two tabs on mat-tab-group.

<mat-tab-group>
  <mat-tab label="TAB1">
    <ng-template matTabContent>
      <custom-component [data]="tab1data"></custom-component>
    </ng-template>
  </mat-tab>
  <mat-tab label="TAB2">
    <ng-template matTabContent>
      <custom-component [data]="tab2data"></custom-component>
    </ng-template>
  </mat-tab>
</mat-tab-group>

The data is a setter that sets the internal _data and wraps it in MatTableDataSource:

@Input()
set data(val: Data[]) {
    this._data = val;
    this.loadData();
}

loadData(): void {
    this.dataSource = new MatTableDataSource<Data>(this._data);
    this.dataSource.sort = this.sort;
}

I have a situation where actions for component on the first tab should affect data on the other tab.
Is there any way to pass component references, so I could change _data and call loadData() from other component?

Body:
From your first tab you can emit an output on dataChange to its parent component.

In Custom Component have a output like

@Output() public dataChange = new EventEmitter();

on change of data emit this event like :-

this.dataChange.emit('changed data');

In your parent component where the selector of this component is, change the selector to :-

HTML :-

<custom-component [data]="tab1data" (dataChange)="modifyDataTab2($event)"></custom-component>

TS :-

modifyDataTab2(firstTabData) {
   this.tab2Data = firstTabData;
   // or you can make other changes.
}

Now because tab2 is already having tab2Data as input your loadData() will automatically be invoked.

If you want to modify data of tab1 on tab 2 change, no need to change the tab component again, each instance will have its own output. change will be in parent only. that will be :-

HTML :-

<custom-component [data]="tab2data" (dataChange)="modifyDataTab1($event)"></custom-component>

TS :-

modifyDataTab1(secondTabData) {
   this.tab1Data = secondTabData;
   // or you can make other changes.
}

That's the benefit of having a common parent. if two childs want to communicate, they should do it via parent. because any data change in parent that is passed as an input, will trigger the changes required in child automatically.


问:
Java 1.7 or later is required to run Solr "4.10.2", but java version "14.0.1" installed
I have to run solr server on Windows 10, and installed Java version "14.0.1" 2020-04-14.

But when i run it, this java error appear

```<code>Java 1.7 or later is required to run SOLR.
</code>```

I have read the similar problem here, but decided to open a new question because the solution isn't clear enough (like what file i should edit on SOLR so i can use my SDK version of Java).

Status for now is :

I already set the env to be always run from the JDK version.

Java version that are found, with the detail : java version "14.0.1" 2020-04-14
Java(TM) SE Runtime Environment (build 14.0.1+7)
Java HotSpot(TM) 64-Bit Server VM (build 14.0.1+7, mixed mode, sharing)

Thank you for your help.

答:
That's a typical stupid programming error affecting numbers larger than 9. The programmer compares the version string as text instead of doing a numeric comparision.

So you need to use Java 7, 8 or 9.

Body:
I have to run solr server on Windows 10, and installed Java version "14.0.1" 2020-04-14.

But when i run it, this java error appear

Java 1.7 or later is required to run SOLR.

I have read the similar problem here, but decided to open a new question because the solution isn't clear enough (like what file i should edit on SOLR so i can use my SDK version of Java).

Status for now is :

I already set the env to be always run from the JDK version.

Java version that are found, with the detail : java version "14.0.1" 2020-04-14
Java(TM) SE Runtime Environment (build 14.0.1+7)
Java HotSpot(TM) 64-Bit Server VM (build 14.0.1+7, mixed mode, sharing)

Thank you for your help.


问:
Rails - NoMethodError (undefined method `collation' for nil:NilClass)
When I create User in my Rails app I get the following error...

```<code>NoMethodError (undefined method `collation' for nil:NilClass)
</code>```

I've been banging my head on a wall with rails trying to figure out what the problem is.

I'm not quite sure what is wrong with my code, as it is pretty much boilerplate as you can see below...

user.rb

```<code>class User < ApplicationRecord
  has_secure_password

  before_create do
    self.username = 'user-' + SecureRandom.hex(8)
  end

  validates :email, presence: true, uniqueness: true, length: { within: 4..255 }
  validates :username, uniqueness: true, length: { is: 13 }
  validates :password, presence: true, uniqueness: true, length: { within: 8..255 }
end
</code>```

user_controller.rb

```<code>class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  def index
    @users = User.all
  end

  def show; end

  def new
    @user = User.new
  end

  def edit; end

  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    end
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.fetch(:user).permit(:username, :email, :password, :password_confirmation)
  end
end
</code>```

_form.html.erb

```<code><%= form_for(@user, local: true) do |form| %>
  <div class="field">
    <%= form.label :email %>
    <%= form.text_field :email %>
  </div>

  <div class="field">
    <%= form.label :password %>
    <%= form.password_field :password %>
  </div>

  <div class="field">
    <%= form.label :password_confirmation, 'Password Confirmation' %>
    <%= form.password_field :password_confirmation %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>
</code>```

I have changed the encoding on the database as well, nothing seems to be working.

UPDATE
I'm not quite sure what was wrong, I reverted to my 'initial commit' of the project and regenerated everything, and it works fine, it uses the same code. I'll mark this as solved, but I have no proper solution other than regenerating.

答:
As said printfinn you have to remove uniqueness validation on password.
His answer should be the accepted one.

I had the same error message as you.

I was trying to validate a field (presence and uniqueness) with a mistake in the name. The name was the name of a function. Rails could validate the presence, but not the uniqueness.

Body:
When I create User in my Rails app I get the following error...

NoMethodError (undefined method `collation' for nil:NilClass)

I've been banging my head on a wall with rails trying to figure out what the problem is.

I'm not quite sure what is wrong with my code, as it is pretty much boilerplate as you can see below...

user.rb

class User < ApplicationRecord
  has_secure_password

  before_create do
    self.username = 'user-' + SecureRandom.hex(8)
  end

  validates :email, presence: true, uniqueness: true, length: { within: 4..255 }
  validates :username, uniqueness: true, length: { is: 13 }
  validates :password, presence: true, uniqueness: true, length: { within: 8..255 }
end

user_controller.rb

class UsersController < ApplicationController
  before_action :set_user, only: [:show, :edit, :update, :destroy]

  def index
    @users = User.all
  end

  def show; end

  def new
    @user = User.new
  end

  def edit; end

  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, notice: 'User was successfully created.' }
      else
        format.html { render :new }
      end
    end
  end

  def update
    respond_to do |format|
      if @user.update(user_params)
        format.html { redirect_to @user, notice: 'User was successfully updated.' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
    end
  end

  private

  def set_user
    @user = User.find(params[:id])
  end

  def user_params
    params.fetch(:user).permit(:username, :email, :password, :password_confirmation)
  end
end

_form.html.erb

<%= form_for(@user, local: true) do |form| %>

    <%= form.label :email %>
    <%= form.text_field :email %>

    <%= form.label :password %>
    <%= form.password_field :password %>

    <%= form.label :password_confirmation, 'Password Confirmation' %>
    <%= form.password_field :password_confirmation %>

    <%= form.submit %>

<% end %>

I have changed the encoding on the database as well, nothing seems to be working.

UPDATE
I'm not quite sure what was wrong, I reverted to my 'initial commit' of the project and regenerated everything, and it works fine, it uses the same code. I'll mark this as solved, but I have no proper solution other than regenerating.


问:
query with sql max function
table view with 4 records

Would the following query work if I wanted to select the 2nd and 3rd records?

```<code>select driver_name, driver_city, driver_email, max(due_date), max(completion_date)
from TableX
group by driver_name,driver_city,driver_email
</code>```

答: It will return 2nd and 4th records as result. Because the 3rd record has empty value in the DueDate column</p>

Title: query with sql max function

Body:
table view with 4 records

Would the following query work if I wanted to select the 2nd and 3rd records?

select driver_name, driver_city, driver_email, max(due_date), max(completion_date)
from TableX
group by driver_name,driver_city,driver_email


问:
React.js | what is different beetween this two functions?
I have a checkbox <input type='checkbox' onClick={ this.props.isTicked.bind(this,id)} />
I also have to do tasks:

```<code>  state = {
    todos: [
      {
        id:1,
        title: 'Earn 10 lvl Faceit',
        completed: false
      },
      {
        id:2,
        title: 'Achieve 10 badges',
        completed: false
      }
    ]
  }
</code>```

So id of checkbox equals id of its task. Then i want to make 'isTicked' function to make completed be an opposite value. I also have style for every task(that is different for true and false)

```<code>            <div style ={this.TaskStyle()}>

                <p>
                    <input type='checkbox' onClick={ this.props.isTicked.bind(this,id)} />
                    {title}
                </p>
            </div>
</code>```

TaskStyle:

```<code>    TaskStyle = () => {
        if (this.props.task_value.completed) {
            return {

                backgroundColor: 'darkgreen',
                fontFamily: 'Arial',
                padding:'10px'
            }
        }
        else {
            return {
                backgroundColor: 'gray',
                fontFamily: 'Arial',
                padding:'10px'
            }
        }

        }
</code>```

Back to the point, this is a working version of 'isTicked':

```<code>    this.setState({todos: this.state.todos.map(todo => {
      if (todo.id === id) {
        todo.completed = !todo.completed
      }
      return todo
    })})

</code>```

And this is mine and i dont know why it is not working....

```<code>  isTicked = (id) => {
    this.state.todos.forEach(todo => {
      if (todo.id === id) {
        todo.completed = !todo.completed
      }
      return todo
    });
  }
</code>```

Can someone help me?)

答:
You are manipulating state directly in this code:

```<code>isTicked = (id) => {
    this.state.todos.forEach(todo => {
      if (todo.id === id) {
        todo.completed = !todo.completed
      }
      return todo
    });
  }
</code>```

which can introduce all kind of unwanted behaviour (=bugs) into your code, as it circumvents Reacts state management. The first implementation is better, but not perfect, as through some weird coincidence the state you are mapping over could change. It would be better to use the callback syntax of setState:

```<code>this.setState(prevState => {
  const newState = prevState.todos.map(todo => {
    if (todo.id === id) {
      todo.completed = !todo.completed;
    }
    return todo;
  });

  return { ...prevState, newState };
});
</code>```

This should ensure that no side effects occur. Maybe this article is helpful for you.

Also, map returns a new value with the mapped over values while forEach just maps over all values, returning nothing.

Body:
I have a checkbox <input type='checkbox' onClick={ this.props.isTicked.bind(this,id)} />
I also have to do tasks:

  state = {
    todos: [
      {
        id:1,
        title: 'Earn 10 lvl Faceit',
        completed: false
      },
      {
        id:2,
        title: 'Achieve 10 badges',
        completed: false
      }
    ]
  }

So id of checkbox equals id of its task. Then i want to make 'isTicked' function to make completed be an opposite value. I also have style for every task(that is different for true and false)

                    <input type='checkbox' onClick={ this.props.isTicked.bind(this,id)} />
                    {title}

TaskStyle:

    TaskStyle = () => {
        if (this.props.task_value.completed) {
            return {

                backgroundColor: 'darkgreen',
                fontFamily: 'Arial',
                padding:'10px'
            }
        }
        else {
            return {
                backgroundColor: 'gray',
                fontFamily: 'Arial',
                padding:'10px'
            }
        }

        }

Back to the point, this is a working version of 'isTicked':

    this.setState({todos: this.state.todos.map(todo => {
      if (todo.id === id) {
        todo.completed = !todo.completed
      }
      return todo
    })})

And this is mine and i dont know why it is not working....

  isTicked = (id) => {
    this.state.todos.forEach(todo => {
      if (todo.id === id) {
        todo.completed = !todo.completed
      }
      return todo
    });
  }

Can someone help me?)

Body:
You are manipulating state directly in this code:

isTicked = (id) => {
    this.state.todos.forEach(todo => {
      if (todo.id === id) {
        todo.completed = !todo.completed
      }
      return todo
    });
  }

which can introduce all kind of unwanted behaviour (=bugs) into your code, as it circumvents Reacts state management. The first implementation is better, but not perfect, as through some weird coincidence the state you are mapping over could change. It would be better to use the callback syntax of setState:

this.setState(prevState => {
  const newState = prevState.todos.map(todo => {
    if (todo.id === id) {
      todo.completed = !todo.completed;
    }
    return todo;
  });

  return { ...prevState, newState };
});

This should ensure that no side effects occur. Maybe this article is helpful for you.

Also, map returns a new value with the mapped over values while forEach just maps over all values, returning nothing.


问:
See if Dictionary Item is the last one in the dictionary
Given the code ..

```<code>var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});
</code>```

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

```<code>bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;
</code>```

but that did not work...

答:
First, there is no ForEach extension method for a Dictionary or even an IEnumerable. So you will have to fix that problem first.

Second, the Last extension method will be painfully slow since it has to enumerate the entire collection.

Third, I am not sure it makes a whole lot of sense to do something special on the last item from a collection with an unpredictable order, but that is mostly tangential to your specific question.

Here is how I would approach the problem. Create two new extensions methods that operate on IEnumerable<T> instances. ForEach will be the equivalent of the List<T>.ForEach method and WithIndex will return another enumerator that contains the sequential index and an IsLast flag. This is a variation of another one of my answers to a similiar problem.

```<code>dictionary.WithIndex().ForEach(
  (item) =>
  {
    var kvp = item.Value; // This extracts the KeyValuePair
    if (item.IsLast)
    {
      Console.WriteLine("Key=" + kvp.Key.ToString() + "; Value=" + kvp.Value.ToString());
    }
  });
</code>```

Here are the new extension methods.

```<code>public static class ForEachHelperExtensions
{
    public sealed class Item<T>
    {
        public int Index { get; set; }
        public T Value { get; set; }
        public bool IsLast { get; set; }
    }

    public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
    {
        foreach (T item in enumerable)
        {
            action(item);
        }
    }

    public static IEnumerable<Item<T>> WithIndex<T>(this IEnumerable<T> enumerable)
    {
        Item<T> item = null;
        foreach (T value in enumerable)
        {
            Item<T> next = new Item<T>();
            next.Index = 0;
            next.Value = value;
            next.IsLast = false;
            if (item != null)
            {
                next.Index = item.Index + 1;
                yield return item;
            }
            item = next;
        }
        if (item != null)
        {
            item.IsLast = true;
            yield return item;
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Given the code ..

var dictionary = new Dictionary<string, string>{
  { "something", "something-else" },
  { "another", "another-something-else" }
};

dictionary.ForEach( item => {
  bool isLast = // ... ?

  // do something if this is the last item
});

I basically want to see if the item I am working with inside of the ForEach iteration is the last item in the dictionary. I tried

bool isLast = dictionary[ item.Key ].Equals( dictionary.Last() ) ? true : false;

but that did not work...

Body:
First, there is no ForEach extension method for a Dictionary or even an IEnumerable. So you will have to fix that problem first.

Second, the Last extension method will be painfully slow since it has to enumerate the entire collection.

Third, I am not sure it makes a whole lot of sense to do something special on the last item from a collection with an unpredictable order, but that is mostly tangential to your specific question.

Here is how I would approach the problem. Create two new extensions methods that operate on IEnumerable<T> instances. ForEach will be the equivalent of the List<T>.ForEach method and WithIndex will return another enumerator that contains the sequential index and an IsLast flag. This is a variation of another one of my answers to a similiar problem.

dictionary.WithIndex().ForEach(
  (item) =>
  {
    var kvp = item.Value; // This extracts the KeyValuePair
    if (item.IsLast)
    {
      Console.WriteLine("Key=" + kvp.Key.ToString() + "; Value=" + kvp.Value.ToString());
    }
  });

Here are the new extension methods.

public static class ForEachHelperExtensions
{
    public sealed class Item<T>
    {
        public int Index { get; set; }
        public T Value { get; set; }
        public bool IsLast { get; set; }
    }

    public static void ForEach<T>(this IEnumerable<T> enumerable, Action<T> action)
    {
        foreach (T item in enumerable)
        {
            action(item);
        }
    }

    public static IEnumerable<Item<T>> WithIndex<T>(this IEnumerable<T> enumerable)
    {
        Item<T> item = null;
        foreach (T value in enumerable)
        {
            Item<T> next = new Item<T>();
            next.Index = 0;
            next.Value = value;
            next.IsLast = false;
            if (item != null)
            {
                next.Index = item.Index + 1;
                yield return item;
            }
            item = next;
        }
        if (item != null)
        {
            item.IsLast = true;
            yield return item;
        }
    }
}


答:
Well, firstly in your isTicked function, you're not setting the state like the previous method does.

Secondly, map returns a new Array which you san set as a newState while forEach does not. In fact that's the only difference between the two.

Now when you're iterating though forEach and directly changing the state, React doesn't have a way to know that the state has changed and it has to trigger the render function. Hence, you're not seeing the changes in the other case. On the other hand, in the former case, when you're modifying the state though setState, React re-renders the component in turn and you see the effect.

It's as simple as that :)

Do Not Modify State Directly For example, this will not re-render a
  component:

```<code>// Wrong
this.state.comment = 'Hello';
// Instead, use setState():

// Correct
this.setState({comment: 'Hello'});
</code>```

You might like to read this: do-not-modify-state-directly

Title: React.js | what is different beetween this two functions?

Body:
Well, firstly in your isTicked function, you're not setting the state like the previous method does.

Secondly, map returns a new Array which you san set as a newState while forEach does not. In fact that's the only difference between the two.

Now when you're iterating though forEach and directly changing the state, React doesn't have a way to know that the state has changed and it has to trigger the render function. Hence, you're not seeing the changes in the other case. On the other hand, in the former case, when you're modifying the state though setState, React re-renders the component in turn and you see the effect.

It's as simple as that :)

Do Not Modify State Directly For example, this will not re-render a
  component:

// Wrong
this.state.comment = 'Hello';
// Instead, use setState():

// Correct
this.setState({comment: 'Hello'});

You might like to read this: do-not-modify-state-directly


问:
Android app crashes when I tap recent apps
I'm using HomeActivity which has a navigation drawer. This activity has multiple tabs which is using fragments to show different lists. On each fragment, I used FragmentDialog to show custom filter dialogs.

When I click the filter menu item, this custom dialog pops up. If I tap the recent items button when the dialog is on top then the app crashes leaving this log.

```<code>java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.myapplication.fragments.-$$Lambda$EmployeeListFragment$2gfw7BDAN9Jtbj71yfwTPA0wy_4)
    at android.os.Parcel.writeSerializable(Parcel.java:1822)
    at android.os.Parcel.writeValue(Parcel.java:1770)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:167)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:169)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.app.IActivityManager$Stub$Proxy.activityStopped(IActivityManager.java:4604)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3934)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.io.NotSerializableException: androidx.appcompat.widget.AppCompatButton
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1233)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at android.os.Parcel.writeSerializable(Parcel.java:1817)
    at android.os.Parcel.writeValue(Parcel.java:1770)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:167)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:169)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.app.IActivityManager$Stub$Proxy.activityStopped(IActivityManager.java:4604)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3934)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

答:
You are trying to serialize EmployeeListFragment, likely onPause, while it complains that:

```<code>java.io.NotSerializableException: androidx.appcompat.widget.AppCompatButton
</code>```

So there is something wrong with the way you handle the instance state; eg. it also lists:

```<code>FragmentState.writeToParcel(FragmentState.java:169)
</code>```

See Fragment & FragmentDialog life-cycle.

a) Think you could use transient key-word to exclude it from serialization:

```<code>public transient AppCompatButton mButton = null;
</code>```

b) Or add implements Serializable to whatever needs to be serialized; eg. public class MyButton implements Serializable (it might be non-sense to serialize an AppCompatButton).

Body:
I'm using HomeActivity which has a navigation drawer. This activity has multiple tabs which is using fragments to show different lists. On each fragment, I used FragmentDialog to show custom filter dialogs.

When I click the filter menu item, this custom dialog pops up. If I tap the recent items button when the dialog is on top then the app crashes leaving this log.

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.example.myapplication.fragments.-$$Lambda$EmployeeListFragment$2gfw7BDAN9Jtbj71yfwTPA0wy_4)
    at android.os.Parcel.writeSerializable(Parcel.java:1822)
    at android.os.Parcel.writeValue(Parcel.java:1770)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:167)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:169)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.app.IActivityManager$Stub$Proxy.activityStopped(IActivityManager.java:4604)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3934)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
 Caused by: java.io.NotSerializableException: androidx.appcompat.widget.AppCompatButton
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1233)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
    at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1597)
    at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1558)
    at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1481)
    at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1227)
    at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:347)
    at android.os.Parcel.writeSerializable(Parcel.java:1817)
    at android.os.Parcel.writeValue(Parcel.java:1770)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:167)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.os.Parcel.writeBundle(Parcel.java:878)
    at androidx.fragment.app.FragmentState.writeToParcel(FragmentState.java:169)
    at android.os.Parcel.writeTypedList(Parcel.java:1354)
    at androidx.fragment.app.FragmentManagerState.writeToParcel(FragmentManagerState.java:51)
    at android.os.Parcel.writeParcelable(Parcel.java:1791)
    at android.os.Parcel.writeValue(Parcel.java:1697)
    at android.os.Parcel.writeArrayMapInternal(Parcel.java:838)
    at android.os.BaseBundle.writeToParcelInner(BaseBundle.java:1542)
    at android.os.Bundle.writeToParcel(Bundle.java:1232)
    at android.app.IActivityManager$Stub$Proxy.activityStopped(IActivityManager.java:4604)
    at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3934)
    at android.os.Handler.handleCallback(Handler.java:790)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6494)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Body:
You are trying to serialize EmployeeListFragment, likely onPause, while it complains that:

java.io.NotSerializableException: androidx.appcompat.widget.AppCompatButton

So there is something wrong with the way you handle the instance state; eg. it also lists:

FragmentState.writeToParcel(FragmentState.java:169)

See Fragment & FragmentDialog life-cycle.

a) Think you could use transient key-word to exclude it from serialization:

public transient AppCompatButton mButton = null;

b) Or add implements Serializable to whatever needs to be serialized; eg. public class MyButton implements Serializable (it might be non-sense to serialize an AppCompatButton).


问:
TextFormField displaying error message even after the values are inserted (using Form Flutter)
I am experimenting with flutter and I am stucked with a silly problem. I have defined two TextInputField in a screen, and I am validating using Form. Everything is working fine, my only problem, error is not going away even after values which is inserted are fine.

Below is the screenshot before entering the value. Error is showing at the start of the screen as well.

Below is the screen after entering the value. When i click on signup button, error is still showing.

You can see, value is getting printed in logs when i click on Sign Up button.

Widget Class

```<code>class SignUpForm extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SignUpState();
  }
}
</code>```

State Class

```<code>class SignUpState extends State<SignUpForm> {
  final _fbKey = GlobalKey<FormState>();
  final UserDetails userDetails = UserDetails();
  bool _autoValidate = true;

  @override
  Widget build(BuildContext context) {
    return CustomScreenBg(
      AppString.additional_information,
      CustomCard(_getSignUpForm(context)),
    );
  }

  _getSignUpForm(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Form(
        key: _fbKey,
        autovalidate: _autoValidate,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                RichText(
                  text: TextSpan(
                    text: AppString.welcome_to,
                    style: TextStyle(
                      color: AppColor.BLACK.toColor,
                      fontSize: 18,
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: '${AppString.app_name}',
                        style: TextStyle(
                          fontSize: 24,
                          color: AppColor.PRIMARY_COLOR.toColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 4),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SubTitleText(AppString.lets_get_started),
              ],
            ),
            SizedBox(height: 16),
            Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                TextFormField(
                  decoration: InputDecoration(
                    labelText: AppString.enter_name,
                    errorText: AppString.error_name,
                  ),
                  keyboardType: TextInputType.text,
                  validator: (value) {
                    if (value.length < 4) {
                      return AppString.error_name;
                    }
                    return null;
                  },
                  onSaved: (name) {
                    userDetails.name = name;
                  },
                ),
                SizedBox(height: 16),
                TextFormField(
                  decoration: InputDecoration(
                    labelText: AppString.enter_email,
                    errorText: AppString.error_email,
                  ),
                  keyboardType: TextInputType.text,
                  validator: (value) {
                    if (value.length < 5 || !value.contains('@')) {
                      return AppString.error_email;
                    }
                    return null;
                  },
                  onSaved: (email) {
                    userDetails.email = email;
                  },
                ),
              ],
            ),
            SizedBox(height: 24),
            Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                CustomButton(
                  AppString.sign_up,
                  () {
                    _onSubmit();
                  },
                  textColor: AppColor.WHITE.toColor,
                  bgColor: AppColor.PRIMARY_COLOR.toColor,
                ),
              ],
            ),
            SizedBox(height: 12)
          ],
        ),
      ),
    );
  }

  _onSubmit() {
    if (_fbKey.currentState.validate()) {
      _fbKey.currentState.save();
      print(userDetails.name);
      print(userDetails.email);
    } else {
      setState(() {
        _autoValidate = true;
      });
    }
  }
}

</code>```

This method is getting called when clicking on Sign Up Button.

```<code>_onSubmit() {
    if (_fbKey.currentState.validate()) {
      _fbKey.currentState.save();
      print(userDetails.name);
      print(userDetails.email);
    } else {
      setState(() {
        _autoValidate = true;
      });
    }
  }

</code>```

Can someone help me in figuring it out, what i am doing wrong?

答:
In my experience it is better to control the autoValidate property yourself. So following an example from here

First set class Boolean variable :

```<code>bool _autovalidate = false;
</code>```

Then pass it to your form:

```<code>Form(
key: _fbKey,
autovalidate: _autovalidate,
...
)
</code>```

Then in your validator:

```<code>validator: (value) {
                if (value.length < 5 || !value.contains('@')) {

                  return AppString.error_email;
                  setState(() => _autoValidate = true);
                }
                return null;
              }
</code>```

Body:
I am experimenting with flutter and I am stucked with a silly problem. I have defined two TextInputField in a screen, and I am validating using Form. Everything is working fine, my only problem, error is not going away even after values which is inserted are fine.

Below is the screenshot before entering the value. Error is showing at the start of the screen as well.

Below is the screen after entering the value. When i click on signup button, error is still showing.

You can see, value is getting printed in logs when i click on Sign Up button.

Widget Class

class SignUpForm extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return SignUpState();
  }
}

State Class

class SignUpState extends State<SignUpForm> {
  final _fbKey = GlobalKey<FormState>();
  final UserDetails userDetails = UserDetails();
  bool _autoValidate = true;

  @override
  Widget build(BuildContext context) {
    return CustomScreenBg(
      AppString.additional_information,
      CustomCard(_getSignUpForm(context)),
    );
  }

  _getSignUpForm(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(12),
      child: Form(
        key: _fbKey,
        autovalidate: _autoValidate,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                RichText(
                  text: TextSpan(
                    text: AppString.welcome_to,
                    style: TextStyle(
                      color: AppColor.BLACK.toColor,
                      fontSize: 18,
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        text: '${AppString.app_name}',
                        style: TextStyle(
                          fontSize: 24,
                          color: AppColor.PRIMARY_COLOR.toColor,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 4),
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SubTitleText(AppString.lets_get_started),
              ],
            ),
            SizedBox(height: 16),
            Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                TextFormField(
                  decoration: InputDecoration(
                    labelText: AppString.enter_name,
                    errorText: AppString.error_name,
                  ),
                  keyboardType: TextInputType.text,
                  validator: (value) {
                    if (value.length < 4) {
                      return AppString.error_name;
                    }
                    return null;
                  },
                  onSaved: (name) {
                    userDetails.name = name;
                  },
                ),
                SizedBox(height: 16),
                TextFormField(
                  decoration: InputDecoration(
                    labelText: AppString.enter_email,
                    errorText: AppString.error_email,
                  ),
                  keyboardType: TextInputType.text,
                  validator: (value) {
                    if (value.length < 5 || !value.contains('@')) {
                      return AppString.error_email;
                    }
                    return null;
                  },
                  onSaved: (email) {
                    userDetails.email = email;
                  },
                ),
              ],
            ),
            SizedBox(height: 24),
            Row(
              mainAxisSize: MainAxisSize.max,
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                CustomButton(
                  AppString.sign_up,
                  () {
                    _onSubmit();
                  },
                  textColor: AppColor.WHITE.toColor,
                  bgColor: AppColor.PRIMARY_COLOR.toColor,
                ),
              ],
            ),
            SizedBox(height: 12)
          ],
        ),
      ),
    );
  }

  _onSubmit() {
    if (_fbKey.currentState.validate()) {
      _fbKey.currentState.save();
      print(userDetails.name);
      print(userDetails.email);
    } else {
      setState(() {
        _autoValidate = true;
      });
    }
  }
}

This method is getting called when clicking on Sign Up Button.

_onSubmit() {
    if (_fbKey.currentState.validate()) {
      _fbKey.currentState.save();
      print(userDetails.name);
      print(userDetails.email);
    } else {
      setState(() {
        _autoValidate = true;
      });
    }
  }

Can someone help me in figuring it out, what i am doing wrong?

Body:
In my experience it is better to control the autoValidate property yourself. So following an example from here

First set class Boolean variable :

bool _autovalidate = false;

Then pass it to your form:

Form(
key: _fbKey,
autovalidate: _autovalidate,
...
)

Then in your validator:

validator: (value) {
                if (value.length < 5 || !value.contains('@')) {

                  return AppString.error_email;
                  setState(() => _autoValidate = true);
                }
                return null;
              }


问:
How to turn on PHP error reporting for a single script?
I was given the task to upload a script on some old production server and, as expected, many things don't work.

I wanted to know if it was possible to turn on error reporting for a single script without having access to the actual php.ini file.

I've tried this: PHP production server - turn on error messages, using:

```<code>ini_set('display_errors', 'On');
ini_set('display_errors', 1);
ini_set('display_errors', '1');
</code>```

But that won't work on this server. If I trigger an error, e.g.:

```<code>public static funtion myfunc() { … }
</code>```

Or I try to use an undefined function, e.g.:

```<code>password_verify();
</code>```

I end up staring at a blank screen. I also don't have access to any (useful) logs. I've also tried this: How to get useful error messages in PHP?, but I don't have access to any .htaccess file either.

Is there another way to enable this feature? Or is it possible to catch critical errors  and display their information, programatically? The server's PHP version is 5.3 (5.3.28).

答:
An old question, but I stumbled across this problem on a client's server when the guy in charge of Apache was on a very different timezone and I didn't want to wait 8 hours. If you put your code in a try catch block, like so:

```<code>try {
   //your test code here
}
catch (Exception $e)
{
   echo $e->getMessage();
}
</code>```

That should solve a lot of your problems.

Body:
I was given the task to upload a script on some old production server and, as expected, many things don't work.

I wanted to know if it was possible to turn on error reporting for a single script without having access to the actual php.ini file.

I've tried this: PHP production server - turn on error messages, using:

ini_set('display_errors', 'On');
ini_set('display_errors', 1);
ini_set('display_errors', '1');

But that won't work on this server. If I trigger an error, e.g.:

public static funtion myfunc() { … }

Or I try to use an undefined function, e.g.:

password_verify();

I end up staring at a blank screen. I also don't have access to any (useful) logs. I've also tried this: How to get useful error messages in PHP?, but I don't have access to any .htaccess file either.

Is there another way to enable this feature? Or is it possible to catch critical errors  and display their information, programatically? The server's PHP version is 5.3 (5.3.28).

Body:
An old question, but I stumbled across this problem on a client's server when the guy in charge of Apache was on a very different timezone and I didn't want to wait 8 hours. If you put your code in a try catch block, like so:

try {
   //your test code here
}
catch (Exception $e)
{
   echo $e->getMessage();
}

That should solve a lot of your problems.


问:
Using a variable as part of a XPath selection
I'm looking to use a variable as part of an XPath expression.

My problem might be the msxsl node-set function... not sure. But don't let that cloud your judgement... read on...

I'm using a .NET function to load up the content file, which is passed in via bespoke XML content. The @file results in an XML file.

The bespoke XML the sits on the page looks like :

```<code><control name="import" file="information.xml" node="r:container/r:group[@id='set01']/r:item[1]" />
</code>```

The XSL looks like :

```<code><xsl:variable name="document">
    <xsl:copy-of select="ext:getIncludedContent(@file)" />
</xsl:variable>
</code>```

I'm then translating this to a node-set so I can query the document

```<code><xsl:variable name="preset-xml" select="msxsl:node-set($document)" />
</code>```

The source file I am loading in looks like :

```<code><container>
    <group id="set01">
        <item>value01</item>
        <item>value02</item>
        <item>value03</item>
    </group>
    <group id="set02">
        <item>value04</item>
        <item>value05</item>
    </group>
</container>
</code>```

It works up until this point. I can see the source file being brought thru and output as XML.

My problem comes in when I am trying to query the source file with an XPath expression fed in from the content.

I've tried :

```<code><xsl:value-of select="$preset-xml/@node" />
</code>```

Clearly that doesn't work as it looks for @node as a direct child of the loaded in XML.

I've tried :

```<code><xsl:variable name="node" select="@node" />
<xsl:value-of select="$preset-xml/$node" />
</code>```

But it doesn't like the second variable.

I've tried concat($preset-xml,'/',$node), but that still draws out the entire document in the result.

The only way I can get this working at the moment is to write out the full expression in the template :

```<code><xsl:value-of select="$preset-xml/r:container/r:group[@id='set01']/r:item[1]" />
</code>```

Which correctly brings thru value01

But that is then a hard coded solution.
I want to develop a solution which can be manipulated from the content to suit any sort of imported content, with the parameters declared in the content file.

p.s. I'm using XSLT 1.0 because the tech admin won't change the Microsoft parser to support later versions of XSL, so any solution would need to be written with that in mind.

答:
One possible trick is to call an parametrized xsl:template which carries out the crucial select comparison part and evaluate it's output as string.

I had a similar problem (count all nodes of an arbitrary attribute value) which I solved this way (btw: $sd = 'document($filename)' so I load a secondary xml files content):

```<code><xsl:template match="/">
  <xsl:variable name="string_cntsuccess">
    <xsl:for-each select="./Testcase">
      <xsl:variable name="tcname" select="@location"/>
      <xsl:for-each select="$sd//TestCase[@state='Passed']">
        <xsl:call-template name="producedots">
          <xsl:with-param name="name" select="$tcname"/>
        </xsl:call-template>
      </xsl:for-each>
    </xsl:for-each>
  </xsl:variable>

  <xsl:variable name="cntsuccess" select="string-length($string_cntsuccess)"/>
</xsl:template>

<xsl:template name="producedots">
  <xsl:param name="name"/>
  <xsl:variable name="ename" select="@name"/>
  <xsl:if test="$name = $ename">
    <xsl:text>.</xsl:text>
  </xsl:if>
</xsl:template>
</code>```

Body:
I'm looking to use a variable as part of an XPath expression.

My problem might be the msxsl node-set function... not sure. But don't let that cloud your judgement... read on...

I'm using a .NET function to load up the content file, which is passed in via bespoke XML content. The @file results in an XML file.

The bespoke XML the sits on the page looks like :

<control name="import" file="information.xml" node="r:container/r:group[@id='set01']/r:item[1]" />

The XSL looks like :

<xsl:variable name="document">
    <xsl:copy-of select="ext:getIncludedContent(@file)" />
</xsl:variable>

I'm then translating this to a node-set so I can query the document

<xsl:variable name="preset-xml" select="msxsl:node-set($document)" />

The source file I am loading in looks like :

<container>
    <group id="set01">
        <item>value01</item>
        <item>value02</item>
        <item>value03</item>
    </group>
    <group id="set02">
        <item>value04</item>
        <item>value05</item>
    </group>
</container>

It works up until this point. I can see the source file being brought thru and output as XML.

My problem comes in when I am trying to query the source file with an XPath expression fed in from the content.

I've tried :

<xsl:value-of select="$preset-xml/@node" />

Clearly that doesn't work as it looks for @node as a direct child of the loaded in XML.

I've tried :

<xsl:variable name="node" select="@node" />
<xsl:value-of select="$preset-xml/$node" />

But it doesn't like the second variable.

I've tried concat($preset-xml,'/',$node), but that still draws out the entire document in the result.

The only way I can get this working at the moment is to write out the full expression in the template :

<xsl:value-of select="$preset-xml/r:container/r:group[@id='set01']/r:item[1]" />

Which correctly brings thru value01

But that is then a hard coded solution.
I want to develop a solution which can be manipulated from the content to suit any sort of imported content, with the parameters declared in the content file.

p.s. I'm using XSLT 1.0 because the tech admin won't change the Microsoft parser to support later versions of XSL, so any solution would need to be written with that in mind.

Body:
One possible trick is to call an parametrized xsl:template which carries out the crucial select comparison part and evaluate it's output as string.

I had a similar problem (count all nodes of an arbitrary attribute value) which I solved this way (btw: $sd = 'document($filename)' so I load a secondary xml files content):

<xsl:template match="/">
  <xsl:variable name="string_cntsuccess">
    <xsl:for-each select="./Testcase">
      <xsl:variable name="tcname" select="@location"/>
      <xsl:for-each select="$sd//TestCase[@state='Passed']">
        <xsl:call-template name="producedots">
          <xsl:with-param name="name" select="$tcname"/>
        </xsl:call-template>
      </xsl:for-each>
    </xsl:for-each>
  </xsl:variable>

  <xsl:variable name="cntsuccess" select="string-length($string_cntsuccess)"/>
</xsl:template>

<xsl:template name="producedots">
  <xsl:param name="name"/>
  <xsl:variable name="ename" select="@name"/>
  <xsl:if test="$name = $ename">
    <xsl:text>.</xsl:text>
  </xsl:if>
</xsl:template>


问:
Why is the Entity Framework inserting when it should update?
I use the following RIA Services call to register and return a Project entity.

```<code>// On Server; inside RIA Domain Service
[Invoke]
public Project CreateNewProject(String a_strKioskNumber)
{
  Decimal dProjectID = ObjectContext.RegisterProjectNumber(a_strKioskNumber)
                       .FirstOrDefault() ?? -1m;

  // Tried this but it returned zero (0)
  //int nChanged = ObjectContext.SaveChanges();

  var project = (from qProject in ObjectContext.Projects.Include("ProjectItems")
                 where qProject.ID == dProjectID
                 select qProject)
                 .FirstOrDefault();

  if (project == null)
    return null;

  return project;
}
</code>```

As you can see, it calls a stored procedure that returns a project ID. It uses this ID to look up the Project entity itself and return it.  When the Project entity is returned to the client it is detached.  I attach it to the DomainContext and modify it.

```<code>// At Client
_activeProject = a_invokeOperation.Value; // <-- Detached
_context.Projects.Attach(_activeProject); // <-- Unmodified

if (_activeProject != null)
{
  _activeProject.AuthenticationType = "strong"; // <-- Modified
  _activeProject.OwnerID = customer.ID;
  _projectItems.Do(pi => _activeProject.ProjectItems.Add(pi));
  _activeProject.Status = "calculationrequired";
}
</code>```

At this point it has an entity state of Modified.  When I submit changes it gives me an exception regarding a UNIQUE KEY violation as if it is trying to insert it rather than update it.

```<code>// At Client
_context.SubmitChanges(OnProjectSaved, a_callback);
</code>```

I'm using the same DomainContext instance for all operations.  Why should this not work?

What's going wrong? This is rather frustrating.

Edits:

I tried this (as suggested by Jeff):

```<code>[Invoke]
public void SaveProject(Project a_project)
{
  var project = (from qProject in ObjectContext.Projects
                 where qProject.ID == a_project.ID
                 select qProject)
                 .FirstOrDefault();

  project.SubmitDate = a_project.SubmitDate;
  project.PurchaseDate = a_project.PurchaseDate;
  project.MachineDate = a_project.MachineDate;
  project.Status = a_project.Status;
  project.AuthenticationType = a_project.AuthenticationType;
  project.OwnerID = a_project.OwnerID;
  project.ProjectName = a_project.ProjectName;
  project.OwnerEmail = a_project.OwnerEmail;
  project.PricePerPart = a_project.PricePerPart;
  project.SheetQuantity = a_project.SheetQuantity;
  project.EdgeLength = a_project.EdgeLength;
  project.Price = a_project.Price;
  project.ShipToStoreID = a_project.ShipToStoreID;
  project.MachiningTime = a_project.MachiningTime;

  int nChangedItems = ObjectContext.SaveChanges();
}
</code>```

It did absolutely nothing.  It didn't save the project.

答:
As for the notion that one can't use a singleton global DomainContext, this is actually debatable.  In my project I use a singleton DomainContext with no issues.  In other projects, we have created a new DomainContext for different modules in the app where the entities are reused. There are definitely pros and cons.  See:
Strategies for Handling Your DomainContext (external blog)</p>

Body:
I use the following RIA Services call to register and return a Project entity.

// On Server; inside RIA Domain Service
[Invoke]
public Project CreateNewProject(String a_strKioskNumber)
{
  Decimal dProjectID = ObjectContext.RegisterProjectNumber(a_strKioskNumber)
                       .FirstOrDefault() ?? -1m;

  // Tried this but it returned zero (0)
  //int nChanged = ObjectContext.SaveChanges();

  var project = (from qProject in ObjectContext.Projects.Include("ProjectItems")
                 where qProject.ID == dProjectID
                 select qProject)
                 .FirstOrDefault();

  if (project == null)
    return null;

  return project;
}

As you can see, it calls a stored procedure that returns a project ID. It uses this ID to look up the Project entity itself and return it.  When the Project entity is returned to the client it is detached.  I attach it to the DomainContext and modify it.

// At Client
_activeProject = a_invokeOperation.Value; // <-- Detached
_context.Projects.Attach(_activeProject); // <-- Unmodified

if (_activeProject != null)
{
  _activeProject.AuthenticationType = "strong"; // <-- Modified
  _activeProject.OwnerID = customer.ID;
  _projectItems.Do(pi => _activeProject.ProjectItems.Add(pi));
  _activeProject.Status = "calculationrequired";
}

At this point it has an entity state of Modified.  When I submit changes it gives me an exception regarding a UNIQUE KEY violation as if it is trying to insert it rather than update it.

// At Client
_context.SubmitChanges(OnProjectSaved, a_callback);

I'm using the same DomainContext instance for all operations.  Why should this not work?

What's going wrong? This is rather frustrating.

Edits:

I tried this (as suggested by Jeff):

[Invoke]
public void SaveProject(Project a_project)
{
  var project = (from qProject in ObjectContext.Projects
                 where qProject.ID == a_project.ID
                 select qProject)
                 .FirstOrDefault();

  project.SubmitDate = a_project.SubmitDate;
  project.PurchaseDate = a_project.PurchaseDate;
  project.MachineDate = a_project.MachineDate;
  project.Status = a_project.Status;
  project.AuthenticationType = a_project.AuthenticationType;
  project.OwnerID = a_project.OwnerID;
  project.ProjectName = a_project.ProjectName;
  project.OwnerEmail = a_project.OwnerEmail;
  project.PricePerPart = a_project.PricePerPart;
  project.SheetQuantity = a_project.SheetQuantity;
  project.EdgeLength = a_project.EdgeLength;
  project.Price = a_project.Price;
  project.ShipToStoreID = a_project.ShipToStoreID;
  project.MachiningTime = a_project.MachiningTime;

  int nChangedItems = ObjectContext.SaveChanges();
}

It did absolutely nothing.  It didn't save the project.


问:
javascript Cannot pass variables between 2 functions
I am wondering how to pass a variable between 2 functions.

I have looked on Stackoverflow but all examples I tried did not work for me.

I have function, which calculates an array: arrR.

Now, I would like to call this variable somewhere else:

```<code>function my_function(arrR) {
    return(arrR[1]);
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}
</code>```

But y: myfunction(arrR) gives notting. I have checked that if I put some number say y: 1 this works.

Any clue ?

Many thanks

答:
Thanks everyone. This works now like:
I just had to declare the variable outside functions.</p>

```<code>
var arrR = [];

</code>```

Body:
I am wondering how to pass a variable between 2 functions.

I have looked on Stackoverflow but all examples I tried did not work for me.

I have function, which calculates an array: arrR.

Now, I would like to call this variable somewhere else:

function my_function(arrR) {
    return(arrR[1]);
}

function onRefresh(chart) {
    chart.config.data.datasets.forEach(function(dataset) {
        dataset.data.push({
            x: Date.now(),
            y: myfunction(arrR)
        });
    });
}

But y: myfunction(arrR) gives notting. I have checked that if I put some number say y: 1 this works.

Any clue ?

Many thanks

Body:
Thanks everyone. This works now like:
I just had to declare the variable outside functions.

var arrR = [];


问:
Mapping the column basis on certain key words and creating a new variable in R
I got a Name column in which i want to create a new column such that  if i got names containing 'Nivia' or 'india' (irrespctive of capital or small) it should be mapped as "Internal" and the rest as Others.

Below is the data and the code i tried but with no luck:

```<code>structure(list(Name = structure(c(8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 2L, 2L, 2L, 3L, 7L, 7L, 7L, 7L, 7L,
7L, 9L, 9L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 9L, 9L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 14L, 14L, 14L, 14L, 10L, 11L, 13L, 4L, 15L,
5L, 5L, 5L, 12L, 6L, 1L), .Label = c("ASIAKASTIETOOY", "CARGO PARTNER LOGISTICS INDIA PVT LTD",
"DKSH INDIA PRIVATE LIMITED", "FONECTAOY", "INTRUM JUSTITIA OY",
"LINDSTROMOY", "Nivia Cosmetics Global S.A., Luxembourg, Schaffhausen Branch",
"Nivia INDIA PVT. LTD.", "Nivia SOFTWARE S.R.O", "Posti Oy",
"Ruoholahden Hoitokeskus", "S-Business Oy", "S1 Networks Oy",
"Secto Automotive Oy", "SLP Group Oy / Ukko.fi"), class = "factor")), class = "data.frame", row.names = c(NA,
-59L))
</code>```

Below is the code i tried:

```<code>name$Name<-as.character(name$Name)

name$newname<-ifelse(name$Name=='Nivia',"Internal","Others")
name$newname<-ifelse(name$Name=='india',"Internal","Others")
</code>```

答:
== is used for exact match, use grepl for pattern matching :

```<code>name$newname <- ifelse(grepl('nivia|india', name$Name,
                        ignore.case = TRUE), 'Internal', 'Others')
</code>```

You may also use tolower on Name column to bring it in lower case and drop ignore.case.

```<code>name$newname <- ifelse(grepl('nivia|india',
                       tolower(name$Name)), 'Internal', 'Others')
</code>```

You can also do this without ifelse :

```<code>name$newname <- c('Others','Internal')[(grepl('nivia|india',tolower(name$Name))+1)]
</code>```

Body:
I got a Name column in which i want to create a new column such that  if i got names containing 'Nivia' or 'india' (irrespctive of capital or small) it should be mapped as "Internal" and the rest as Others.

Below is the data and the code i tried but with no luck:

structure(list(Name = structure(c(8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 2L, 2L, 2L, 3L, 7L, 7L, 7L, 7L, 7L,
7L, 9L, 9L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 9L, 9L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 14L, 14L, 14L, 14L, 10L, 11L, 13L, 4L, 15L,
5L, 5L, 5L, 12L, 6L, 1L), .Label = c("ASIAKASTIETOOY", "CARGO PARTNER LOGISTICS INDIA PVT LTD",
"DKSH INDIA PRIVATE LIMITED", "FONECTAOY", "INTRUM JUSTITIA OY",
"LINDSTROMOY", "Nivia Cosmetics Global S.A., Luxembourg, Schaffhausen Branch",
"Nivia INDIA PVT. LTD.", "Nivia SOFTWARE S.R.O", "Posti Oy",
"Ruoholahden Hoitokeskus", "S-Business Oy", "S1 Networks Oy",
"Secto Automotive Oy", "SLP Group Oy / Ukko.fi"), class = "factor")), class = "data.frame", row.names = c(NA,
-59L))

Below is the code i tried:

name$Name<-as.character(name$Name)

name$newname<-ifelse(name$Name=='Nivia',"Internal","Others")
name$newname<-ifelse(name$Name=='india',"Internal","Others")

Body:
== is used for exact match, use grepl for pattern matching :

name$newname <- ifelse(grepl('nivia|india', name$Name,
                        ignore.case = TRUE), 'Internal', 'Others')

You may also use tolower on Name column to bring it in lower case and drop ignore.case.

name$newname <- ifelse(grepl('nivia|india',
                       tolower(name$Name)), 'Internal', 'Others')

You can also do this without ifelse :

name$newname <- c('Others','Internal')[(grepl('nivia|india',tolower(name$Name))+1)]


问:
Creating XML file with a specific order or attributes using Python
I am trying to create a xml file using lxml, I am well aware that the order of attributes in xml doesn't matter but still I am searching for a method to prevent the attributes in a specific order.

I also tried minidom and that didn't workout too.

In lxml I have the following code:

```<code>from lxml import etree as ET
from collections import OrderedDict
root = ET.Element("Root", OrderedDict([("id","0"),("start","0"),("end","200")]))
ET.tostring(root)
</code>```

This part gives the following ouput with the attributes in the order I wanted since I used OrderedDict here:

```<code><Root id="0" start="0" end="200"/>
</code>```

Then I created a Child using the same method:

```<code>child1 = ET.Element("sentence", OrderedDict([("id","0"),("start","0"),("end","255")]))
root.append(child1)
xml_str = ET.tostring(root, pretty_print=True)
print(xml_str)
</code>```

Printing the xml_str gives output as I expect:

```<code><Root id="0" start="0" end="200">\n  <sentence id="0" start="0" end="255"/>\n</Root>
</code>```

But when it comes to writing it down to a xml file:

```<code>with open('op.xml', 'wb') as f:
  f.write(xml_str)
</code>```

The ouput isn't same when written to op.xml file:

```<code><?xml version="1.0"?>

<Root end="200" start="0" id="0">
       <sentence end="255" start="0" id="0"/>
</Root>
</code>```

Clearly seen that the attributes order have changed, is there any way I can get the ouput as I expect i.e attribute orders being maintained.

I have tried using minidom too, but there also it didn't work even after referring to:
Preserve order of attributes when modifying with minidom

答:
Using lxml.etree makes it work:

```<code>import lxml.etree
from collections import OrderedDict

root = lxml.etree.Element("Root", OrderedDict([("id","0"),("start","0"),("end","200")]))
isVal = lxml.etree.SubElement(root, 'sentence', OrderedDict([("id","0"),("start","0"),("end","255")]))

with open("xyz2.xml", 'wb') as f:
    f.write(lxml.etree.tostring(root, xml_declaration=True, encoding="utf-8"))

print(open("xyz2.xml", 'r').read())
</code>```

Output:

```<code><?xml version='1.0' encoding='utf-8'?>
<Root id="0" start="0" end="200"><sentence id="0" start="0" end="255"/></Root>
</code>```

Body:
I am trying to create a xml file using lxml, I am well aware that the order of attributes in xml doesn't matter but still I am searching for a method to prevent the attributes in a specific order.

I also tried minidom and that didn't workout too.

In lxml I have the following code:

from lxml import etree as ET
from collections import OrderedDict
root = ET.Element("Root", OrderedDict([("id","0"),("start","0"),("end","200")]))
ET.tostring(root)

This part gives the following ouput with the attributes in the order I wanted since I used OrderedDict here:

<Root id="0" start="0" end="200"/>

Then I created a Child using the same method:

child1 = ET.Element("sentence", OrderedDict([("id","0"),("start","0"),("end","255")]))
root.append(child1)
xml_str = ET.tostring(root, pretty_print=True)
print(xml_str)

Printing the xml_str gives output as I expect:

<Root id="0" start="0" end="200">\n  <sentence id="0" start="0" end="255"/>\n</Root>

But when it comes to writing it down to a xml file:

with open('op.xml', 'wb') as f:
  f.write(xml_str)

The ouput isn't same when written to op.xml file:

<?xml version="1.0"?>

<Root end="200" start="0" id="0">
       <sentence end="255" start="0" id="0"/>
</Root>

Clearly seen that the attributes order have changed, is there any way I can get the ouput as I expect i.e attribute orders being maintained.

I have tried using minidom too, but there also it didn't work even after referring to:
Preserve order of attributes when modifying with minidom

Body:
Using lxml.etree makes it work:

import lxml.etree
from collections import OrderedDict

root = lxml.etree.Element("Root", OrderedDict([("id","0"),("start","0"),("end","200")]))
isVal = lxml.etree.SubElement(root, 'sentence', OrderedDict([("id","0"),("start","0"),("end","255")]))

with open("xyz2.xml", 'wb') as f:
    f.write(lxml.etree.tostring(root, xml_declaration=True, encoding="utf-8"))

print(open("xyz2.xml", 'r').read())

Output:

<?xml version='1.0' encoding='utf-8'?>
<Root id="0" start="0" end="200"><sentence id="0" start="0" end="255"/></Root>


问:
pytorch to Onnx(OCR model)
I am trying to convert pytorch model in the given repo https://github.com/clovaai/deep-text-recognition-benchmark
to onnx.

I am facing the issue while doing so.

```<code>Failed to export an ONNX attribute 'onnx::Gather', since it's not constant, please try to make things (e.g., kernel size) static if possible
</code>```

Link to the git issue https://github.com/clovaai/deep-text-recognition-benchmark/issues/76

Any suggestion?

Thanks.

答: adaptive_avg_pool2d  is not supported in my case and this  nn.AdaptiveAvgPool2d((None,1)) also have have issue.</p>

Title: pytorch to Onnx(OCR model)

Body:
I am trying to convert pytorch model in the given repo https://github.com/clovaai/deep-text-recognition-benchmark
to onnx.

I am facing the issue while doing so.

Failed to export an ONNX attribute 'onnx::Gather', since it's not constant, please try to make things (e.g., kernel size) static if possible

Link to the git issue https://github.com/clovaai/deep-text-recognition-benchmark/issues/76

Any suggestion?

Thanks.


问:
Need some advice to choose the proper container
I'm trying to design a task scheduler to a game engine. A task could be an animation, a trigger controller, etc.

My problem is what container to choose. The idea is: when you insert a new task, the container must reorder and put the task in the proper place. Once executed, task could change and be scheduled again or deleted. This is mainly push and pop.

But, if possible, it would be nice if I could have random access to an element, but not vital. No matter if the container supports one or more elements with the same key.

I think that priority queue fits my needs but I saw that is based on vector implementation, and I think that this container must be somehow  optimized to push and pop.

Opinions?

答:
Depends on how often you're going to be adding tasks and pulling tasks off (and presumably executing them) and how many there are.

If you're going to have tons of little tasks, then prefer priority queue because the cost of node allocation will probably not hurt you as much as the asymptotic growth of n log n for the sort.

If you're going to have a small number of tasks that constantly keep changing priority, then sorting a vector might be reasonable, but you want to use an sorting algorithm that works well when the list is almost sorted.

Scheduling is an art though and you're going to have to profile it once you build it.  There's probably too little information at this point so say.  I'd lean towards a priority queue, but keep other options in mind if performance isn't adequate.


问:
Is it possible to consume positional arguments in pairs with argparse?
Is it possible to consume positional arguments in pairs with argparse?

Example:

```<code>myscript.py [options] NAME URL [NAME URL] [...]
</code>```

I know this can be easily done with optional arguments (using action='append', nargs=2), but I still want to do it with positional arguments. (I don't want to change an existing interface.)

答:
Okay, it seems that argparse doesn't support this usecase directly.
What I did is that I parsed the optional arguments as usually and then added a special args.name_url_pairs positional argument and checked the correct number of items (more than two, an even count) manually.

Body:
Is it possible to consume positional arguments in pairs with argparse?

Example:

myscript.py [options] NAME URL [NAME URL] [...]

I know this can be easily done with optional arguments (using action='append', nargs=2), but I still want to do it with positional arguments. (I don't want to change an existing interface.)


问:
React Navigation 5 , Moving screen to different navigator
still try to understand about multiple navigator here.

Basically i have 2 navigator, one rootnavigator for login page, and the appnavigator for any screen after login, below is the app.js

import * as React from 'react';
import { Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import LoginScreen from './src/pages/auth/Login';
import HomeScreen from './src/pages/auth/Home';
import MemoryScreen from './src/pages/games/Memory';

const AppStack = createStackNavigator();
const RootStack = createStackNavigator();

function HomeNavigator() {
  return (
    <AppStack.Navigator mode="modal" initialRouteName="Login" screenOptions={({ route, navigation }) => ({
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerRight: () => (
        <Button
          onPress={() => navigation.navigate('Login')}
          title="Logout"
          color="#fff"
        />
      ),
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    })}>
      <AppStack.Screen
        name="Home"
        component={HomeScreen}
        options={{
          title: 'Simple Scorecard',
        }}
      />
      <AppStack.Screen
        name="Memory"
        component={MemoryScreen}
        options={{
          title: 'Memory Games',
        }} />
    </AppStack.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <RootStack.Navigator initialRouteName="Login">
        <RootStack.Screen
          name="Login"
          component={LoginScreen}
          options={{
            title: 'Simple Scorecard',
          }} />
        <RootStack.Screen name="App" component={HomeNavigator} />
      </RootStack.Navigator>
    </NavigationContainer>
  );
}```
</div>
</div>
</p>

<p>From login page i try to move to home screen like below . (Login.js)</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import React, { Component } from 'react';
import { Button, TextInput, View, StyleSheet } from 'react-native';

export default class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
        };
    }

    onLogin({ navigation }) {
        const { username, password } = this.state;
        // navigation.navigate('HomeNavigator', {
        //     screen: 'Home',
        //   })
        this.props.navigation.navigate('HomeNavigator', {
            screen: 'Home',
          })
    }

    render() {
        return (
            <View style={styles.container}>
                <TextInput
                    value={this.state.username}
                    onChangeText={(username) => this.setState({ username })}
                    placeholder={'Username'}
                    style={styles.input}
                />
                <TextInput
                    value={this.state.password}
                    onChangeText={(password) => this.setState({ password })}
                    placeholder={'Password'}
                    secureTextEntry={true}
                    style={styles.input}
                />

                <Button
                    title={'Login'}
                    style={styles.input}
                    onPress={this.onLogin.bind(this)}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ecf0f1',
    },
    input: {
        width: 200,
        height: 44,
        padding: 10,
        borderWidth: 1,
        borderColor: 'black',
        marginBottom: 10,
    },
});</code>```

Problem is, i can't navigate to home page, error notice below :

The action 'NAVIGATE' with payload {"name":"HomeNavigator","params":{"screen":"Home"}} was not handled by any navigator.

Do you have a screen named 'HomeNavigator'?

May i know how to solve this?
Thanks

答:
Yes I think you understand Nesting navigators but A litter bit mistake is call wrong name of HomeNavigator
I think right must be

```<code>       this.props.navigation.navigate('App', {
            screen: 'Home',
          })
</code>```

Because "App" is name of screen you assign in container

```<code>export default function App() {
  return (
    <NavigationContainer>
      <RootStack.Navigator initialRouteName="Login">
        <RootStack.Screen
          name="Login"
          component={LoginScreen}
          options={{
            title: 'Simple Scorecard',
          }} />
        <RootStack.Screen name="App" component={HomeNavigator} />
      </RootStack.Navigator>
    </NavigationContainer>
  );
}
</code>```

Understand more in here https://reactnavigation.org/docs/nesting-navigators/

Body:
still try to understand about multiple navigator here.

Basically i have 2 navigator, one rootnavigator for login page, and the appnavigator for any screen after login, below is the app.js

import * as React from 'react';
import { Button } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

import LoginScreen from './src/pages/auth/Login';
import HomeScreen from './src/pages/auth/Home';
import MemoryScreen from './src/pages/games/Memory';

const AppStack = createStackNavigator();
const RootStack = createStackNavigator();

function HomeNavigator() {
  return (
    <AppStack.Navigator mode="modal" initialRouteName="Login" screenOptions={({ route, navigation }) => ({
      headerStyle: {
        backgroundColor: '#f4511e',
      },
      headerRight: () => (
        <Button
          onPress={() => navigation.navigate('Login')}
          title="Logout"
          color="#fff"
        />
      ),
      headerTintColor: '#fff',
      headerTitleStyle: {
        fontWeight: 'bold',
      },
    })}>
      <AppStack.Screen
        name="Home"
        component={HomeScreen}
        options={{
          title: 'Simple Scorecard',
        }}
      />
      <AppStack.Screen
        name="Memory"
        component={MemoryScreen}
        options={{
          title: 'Memory Games',
        }} />
    </AppStack.Navigator>
  );
}

export default function App() {
  return (
    <NavigationContainer>
      <RootStack.Navigator initialRouteName="Login">
        <RootStack.Screen
          name="Login"
          component={LoginScreen}
          options={{
            title: 'Simple Scorecard',
          }} />
        <RootStack.Screen name="App" component={HomeNavigator} />
      </RootStack.Navigator>
    </NavigationContainer>
  );
}

From login page i try to move to home screen like below . (Login.js)

import React, { Component } from 'react';
import { Button, TextInput, View, StyleSheet } from 'react-native';

export default class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
        };
    }

    onLogin({ navigation }) {
        const { username, password } = this.state;
        // navigation.navigate('HomeNavigator', {
        //     screen: 'Home',
        //   })
        this.props.navigation.navigate('HomeNavigator', {
            screen: 'Home',
          })
    }

    render() {
        return (
            <View style={styles.container}>
                <TextInput
                    value={this.state.username}
                    onChangeText={(username) => this.setState({ username })}
                    placeholder={'Username'}
                    style={styles.input}
                />
                <TextInput
                    value={this.state.password}
                    onChangeText={(password) => this.setState({ password })}
                    placeholder={'Password'}
                    secureTextEntry={true}
                    style={styles.input}
                />

                <Button
                    title={'Login'}
                    style={styles.input}
                    onPress={this.onLogin.bind(this)}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ecf0f1',
    },
    input: {
        width: 200,
        height: 44,
        padding: 10,
        borderWidth: 1,
        borderColor: 'black',
        marginBottom: 10,
    },
});

Problem is, i can't navigate to home page, error notice below :

The action 'NAVIGATE' with payload {"name":"HomeNavigator","params":{"screen":"Home"}} was not handled by any navigator.

Do you have a screen named 'HomeNavigator'?

May i know how to solve this?
Thanks

Body:
Yes I think you understand Nesting navigators but A litter bit mistake is call wrong name of HomeNavigator
I think right must be

       this.props.navigation.navigate('App', {
            screen: 'Home',
          })

Because "App" is name of screen you assign in container

export default function App() {
  return (
    <NavigationContainer>
      <RootStack.Navigator initialRouteName="Login">
        <RootStack.Screen
          name="Login"
          component={LoginScreen}
          options={{
            title: 'Simple Scorecard',
          }} />
        <RootStack.Screen name="App" component={HomeNavigator} />
      </RootStack.Navigator>
    </NavigationContainer>
  );
}

Understand more in here https://reactnavigation.org/docs/nesting-navigators/


问:
Naming keys in resource files best practice
Does anyone have any recommendations on naming keys in resource files? For instance, do you base the name of your key on the text that needs to be localized or on the control that uses the text?

Say you have an edit button in several screens (one to edit a user, one to edit a group). You could use the following keys:

editUserButton.label=Edit User...

editGroupButton.label=Edit Group...

or

editUser=Edit User...

editGroup=Edit Group...

or

user.edit=Edit User...

group.edit=Edit Group...

What scheme do you prefer and why?

答:
Base it on the English text, but prefix with the window/dialogue/what have you in which the word or phrase appears. At least when layout space is limited, you may want to avoid falling in the trap of having exactly the same string everywhere: this prevents you from abbreviating to get decent layouts, especially in polysyllabic languages like Finnish.

Of course, you should still strive to be consistent in naming stuff. Increasing the number of strings will also increase translation costs if you're doing this commercially.

And don't ignore the danger of homonyms. Providing context helps prevent that. Don't be afraid make the resource name longer than the actual English term, this can help translators substantially.

OwnerDisplayName: Christophe Herreman

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Pontus Gagge