问:
The ADO.NET provider with invariant name 'Oracle.DataAccess.Client' Not Registered
I have this Entity Framework based web service code developed in VS2015 that has been working fine - until my system got replaced with a new one. On a fresh new system, I am unable to compile the code in the same version of Visual Studio even though I have all the dependencies installed - including the Oracle 11.2 Client Runtime (which says it, "installs tools for developing applications, networking services and basic client software").

When I build the solution in VS2015, the error thrown is: Error 175: The ADO.NET provider with invariant name 'Oracle.DataAccess.Client' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details.

Double-clicking the error takes me to the EDMX File pointing to and the EDMX file tag StorageModels > Schema:

<Schema Namespace="Model.Store" Alias="Self" Provider="Oracle.DataAccess.Client" ProviderManifestToken="11.2" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">

Interestingly, the DLL file gets created (ins spite of the above error) but when I replace the existing DLL on the server with this new one it seems to have issues extracting data from the database with something like:

```<code>System.ArgumentException: The specified store provider cannot be found in the configuration, or is not valid. ---> System.ArgumentException: Unable to find the requested .Net Framework Data Provider.  It may not be installed.
   at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)
   at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
   --- End of inner exception stack trace ---
   at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
   at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
   at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
   at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)
   at System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config)
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
   at MyCo.MyDept.MyIntegration.MyService.DataAccess.DAL.GetLocation() in C:\Users\xxxx\MyCo.MyDept.MyIntegration.MyService\DataAccess\DAL.cs:line 17
   at MyCo.MyDept.MyIntegration.MyService.Utility.Helpers.GetLocations() in C:\Users\xxxx\MyCo.MyDept.MyIntegration.MyService\Utility\Helpers.cs:line 303
   at MyCo.MyDept.MyIntegration.MyService.KService.GetLocations() in C:\Users\xxxx\MyCo.MyDept.MyIntegration.MyService\KService.svc.cs:line 71
</code>```

I have tried the solutions provided in other similar threads but none of them seem to work. Any help is appreciated. Thanks.

答:
Check whether you have following in the config file. If not add them accordingly.

Have manageddataaccess <configSection>

```<code>    <configSections><section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /></<configSections>
</code>```

Provider under <entityFramework>

```<code><entityFramework>
<providers>
  <provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers></entityFramework>
</code>```

Provide factory details under <system.data>

```<code><system.data>
<DbProviderFactories>
  <remove invariant="Oracle.ManagedDataAccess.Client"/>
  <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</DbProviderFactories>
</code>```

Body:
I have this Entity Framework based web service code developed in VS2015 that has been working fine - until my system got replaced with a new one. On a fresh new system, I am unable to compile the code in the same version of Visual Studio even though I have all the dependencies installed - including the Oracle 11.2 Client Runtime (which says it, "installs tools for developing applications, networking services and basic client software").

When I build the solution in VS2015, the error thrown is: Error 175: The ADO.NET provider with invariant name 'Oracle.DataAccess.Client' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details.

Double-clicking the error takes me to the EDMX File pointing to and the EDMX file tag StorageModels > Schema:

<Schema Namespace="Model.Store" Alias="Self" Provider="Oracle.DataAccess.Client" ProviderManifestToken="11.2" xmlns:store="http://schemas.microsoft.com/ado/2007/12/edm/EntityStoreSchemaGenerator" xmlns="http://schemas.microsoft.com/ado/2009/11/edm/ssdl">

Interestingly, the DLL file gets created (ins spite of the above error) but when I replace the existing DLL on the server with this new one it seems to have issues extracting data from the database with something like:

System.ArgumentException: The specified store provider cannot be found in the configuration, or is not valid. ---> System.ArgumentException: Unable to find the requested .Net Framework Data Provider.  It may not be installed.
   at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)
   at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
   --- End of inner exception stack trace ---
   at System.Data.EntityClient.EntityConnection.GetFactory(String providerString)
   at System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)
   at System.Data.EntityClient.EntityConnection..ctor(String connectionString)
   at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)
   at System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config)
   at System.Data.Entity.Internal.LazyInternalConnection.Initialize()
   at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider()
   at System.Linq.Queryable.Where[TSource](IQueryable`1 source, Expression`1 predicate)
   at MyCo.MyDept.MyIntegration.MyService.DataAccess.DAL.GetLocation() in C:\Users\xxxx\MyCo.MyDept.MyIntegration.MyService\DataAccess\DAL.cs:line 17
   at MyCo.MyDept.MyIntegration.MyService.Utility.Helpers.GetLocations() in C:\Users\xxxx\MyCo.MyDept.MyIntegration.MyService\Utility\Helpers.cs:line 303
   at MyCo.MyDept.MyIntegration.MyService.KService.GetLocations() in C:\Users\xxxx\MyCo.MyDept.MyIntegration.MyService\KService.svc.cs:line 71

I have tried the solutions provided in other similar threads but none of them seem to work. Any help is appreciated. Thanks.

Body:
Check whether you have following in the config file. If not add them accordingly.

Have manageddataaccess <configSection>

    <configSections><section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" /></<configSections>

Provider under <entityFramework>

<entityFramework>
<providers>
  <provider invariantName="Oracle.ManagedDataAccess.Client" type="Oracle.ManagedDataAccess.EntityFramework.EFOracleProviderServices, Oracle.ManagedDataAccess.EntityFramework, Version=6.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342" />
</providers></entityFramework>

Provide factory details under <system.data>

<system.data>
<DbProviderFactories>
  <remove invariant="Oracle.ManagedDataAccess.Client"/>
  <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342"/>
</DbProviderFactories>


来源: stackexchange

问:
How to update data in mongodb
I tried to array inside to update using mongodb but its throwing error how to solve it.

```<code>[
    {
        "_id": "5b4efd6fd53be829188070c8",
        "id": 1,
        "name": "All Categories",
        "hasSubCategory": "false",
        "parentId": "0"
    }
]

</code>```

I tried this way of code

db_connection.collection('ecomm_prod_db_product').update({_id:product_data[i]['_id']},{$set :{product[i]['name']:"hari}})

but its throwing error

答:
You are trying to use the value of your product as the object key here.

That will put whatever value lives in your product[i].name as the key like this:

```<code>{$set :{ "Old Name For Example": "hari" }
</code>```

This would try to set a property called Old Name For Example on the document, instead of name **

Instead, you should provide the property name as key, "name"in this case:

```<code>{$set :{ name: "hari" }
</code>```

** (not your usecase but might be noteworthy here)

Should be noted, that this will more likely throw due to the syntax. As the actual usage for a value as a key would be using [myKeyValue] (computed properties).

ContentLicense: CC BY-SA 4.0

Title: How to update data in mongodb

Body:
I tried to array inside to update using mongodb but its throwing error how to solve it.

[
    {
        "_id": "5b4efd6fd53be829188070c8",
        "id": 1,
        "name": "All Categories",
        "hasSubCategory": "false",
        "parentId": "0"
    }
]

I tried this way of code

db_connection.collection('ecomm_prod_db_product').update({_id:product_data[i]['_id']},{$set :{product[i]['name']:"hari}})

but its throwing error

Body:
You are trying to use the value of your product as the object key here.

That will put whatever value lives in your product[i].name as the key like this:

{$set :{ "Old Name For Example": "hari" }

This would try to set a property called Old Name For Example on the document, instead of name **

Instead, you should provide the property name as key, "name"in this case:

{$set :{ name: "hari" }

** (not your usecase but might be noteworthy here)

Should be noted, that this will more likely throw due to the syntax. As the actual usage for a value as a key would be using [myKeyValue] (computed properties).


问:
Eclipse freezing at startup - before loading workspace
First thing on a morning, just after I switch on my PC (Windows XP) and start my Eclipse it simply shows the splash screen and then freezes. After about 20 minutes it will then ask me which workspace to load.

The problem was happening with 3.5 and 3.6 Eclipse. With the 3.6 Eclipse installation I only have the standard PDE install + Google plugin (for GWT development) + Subclipse.

Because I have it configured to ask me for the workspace I can see its not workspace or project related.

I suspect the Google plugin as I have not had any problems before installing this but I have searched and have not come across anybody reporting similar problems.

It only does this once - straight after I switch my machine on in the morning. After this it starts fine - typically in a few seconds.

What is it likely to be doing? How can I find out what it is doing?

答:
In my case it was freezing in the splash screen, while loading 'view.ui', after having selected the workspace.
The fix was running it with:
eclipse -clean -clearPersistedState</p>

ContentLicense: CC BY-SA 2.5


问:
(ArgumentError) could not generate inputs for <association>
Having some issues with rendering changeset errors on a nested form.

Form rendering:

```<code>def new(conn, _) do
  changeset = Organizations.Organization.create_organization_changeset(%Organization{workspace: %Workspace{}})
  render(conn, "new.html", changeset: changeset)
end
</code>```

The form renders fine initially:

```<code><%= form_for @changeset, signup_path(@conn, :create), fn f -> %>

  <%= text_input f, :name, class: "form-control", required: true, autofocus: true %>
  <%= label f, :organization_name %>
  <%= error_tag f, :name %>

  <%= inputs_for f, :workspace, fn w -> %>
    <%= text_input w, :subdomain, required: true %>
    <%= error_tag w, :subdomain %>
  <% end %>

<% end %>
</code>```

Submitting this form calls create_organization/1:

```<code>def create_organization(attrs) do
  Ecto.Multi.new()
  |> Ecto.Multi.run(:organization, fn(_repo, _result) ->
    changeset = Organization.create_organization_changeset(%Organization{}, attrs)
    tenant = Ecto.Changeset.get_field(changeset, :slug)
    Repo.insert(changeset, prefix: TenantActions.build_prefix(tenant))
  end)
  |> Ecto.Multi.run(:workspace, fn(_repo, %{organization: organization}) ->
    attrs = %{subdomain: attrs["workspace"]["subdomain"}, organization_id: organization.id}

    %Workspace{}
    |> Workspace.changeset(attrs)
    |> put_assoc(:organization, organization)
    |> Repo.insert()
  end)
  |> Repo.transaction()
end
</code>```

The "happy path" works fine. However, if there is a changeset error for workspace, for example:

```<code>#Ecto.Changeset<
  action: :insert,
  changes: %{
    name: "test",
    organization: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Organizations.Organization<>, valid?: true>,
    organization_id: 1,
    subdomain: "democompany",
    tenant: "test"
  },
  errors: [
    unique_subdomains: {"That workspace URL is not available.",
     [constraint: :unique, constraint_name: "unique_subdomains"]}
  ],
  data: #Workspaces.Workspace<>,
  valid?: false
>
</code>```

This results in:

```<code>(ArgumentError) could not generate inputs for :workspace from Workspaces.Workspace. Check the field exists and it is one of embeds_one, embeds_many, has_one, has_many, belongs_to or many_to_many
</code>```

Workspace schema:

```<code>schema "workspaces" do
  field :subdomain, :string
  belongs_to :organization, Pricetable.Organizations.Organization

  timestamps(type: :utc_datetime_usec)
end
</code>```

Organization schema:

```<code>schema "organizations" do
  ...
  field :workspace_id, :integer
  has_one :workspace, Workspaces.Workspace
end
</code>```

答:
The error message says:

```<code>** (ArgumentError) could not generate inputs for :workspace from Workspaces.Workspace
</code>```

So I assume that you are passing a workspace in @changeset and not an organization. Then inputs_for tries to get a workspace from a workspace. So I would make sure @changeset is actually an organization.

Also, it is a bit awkward use to both multi and inputs_for. inputs_for is typically used with cast_assoc/cast_embed, which sets up the multi internally for you so you don't have to do it manually. More info here: http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/

Alternatively, you drop the inputs_for and work with both changesets separately.

Body:
Having some issues with rendering changeset errors on a nested form.

Form rendering:

def new(conn, _) do
  changeset = Organizations.Organization.create_organization_changeset(%Organization{workspace: %Workspace{}})
  render(conn, "new.html", changeset: changeset)
end

The form renders fine initially:

<%= form_for @changeset, signup_path(@conn, :create), fn f -> %>

  <%= text_input f, :name, class: "form-control", required: true, autofocus: true %>
  <%= label f, :organization_name %>
  <%= error_tag f, :name %>

  <%= inputs_for f, :workspace, fn w -> %>
    <%= text_input w, :subdomain, required: true %>
    <%= error_tag w, :subdomain %>
  <% end %>

<% end %>

Submitting this form calls create_organization/1:

def create_organization(attrs) do
  Ecto.Multi.new()
  |> Ecto.Multi.run(:organization, fn(_repo, _result) ->
    changeset = Organization.create_organization_changeset(%Organization{}, attrs)
    tenant = Ecto.Changeset.get_field(changeset, :slug)
    Repo.insert(changeset, prefix: TenantActions.build_prefix(tenant))
  end)
  |> Ecto.Multi.run(:workspace, fn(_repo, %{organization: organization}) ->
    attrs = %{subdomain: attrs["workspace"]["subdomain"}, organization_id: organization.id}

    %Workspace{}
    |> Workspace.changeset(attrs)
    |> put_assoc(:organization, organization)
    |> Repo.insert()
  end)
  |> Repo.transaction()
end

The "happy path" works fine. However, if there is a changeset error for workspace, for example:

#Ecto.Changeset<
  action: :insert,
  changes: %{
    name: "test",
    organization: #Ecto.Changeset<action: :update, changes: %{}, errors: [],
     data: #Organizations.Organization<>, valid?: true>,
    organization_id: 1,
    subdomain: "democompany",
    tenant: "test"
  },
  errors: [
    unique_subdomains: {"That workspace URL is not available.",
     [constraint: :unique, constraint_name: "unique_subdomains"]}
  ],
  data: #Workspaces.Workspace<>,
  valid?: false
>

This results in:

(ArgumentError) could not generate inputs for :workspace from Workspaces.Workspace. Check the field exists and it is one of embeds_one, embeds_many, has_one, has_many, belongs_to or many_to_many

Workspace schema:

schema "workspaces" do
  field :subdomain, :string
  belongs_to :organization, Pricetable.Organizations.Organization

  timestamps(type: :utc_datetime_usec)
end

Organization schema:

schema "organizations" do
  ...
  field :workspace_id, :integer
  has_one :workspace, Workspaces.Workspace
end

Body:
The error message says:

** (ArgumentError) could not generate inputs for :workspace from Workspaces.Workspace

So I assume that you are passing a workspace in @changeset and not an organization. Then inputs_for tries to get a workspace from a workspace. So I would make sure @changeset is actually an organization.

Also, it is a bit awkward use to both multi and inputs_for. inputs_for is typically used with cast_assoc/cast_embed, which sets up the multi internally for you so you don't have to do it manually. More info here: http://blog.plataformatec.com.br/2015/08/working-with-ecto-associations-and-embeds/

Alternatively, you drop the inputs_for and work with both changesets separately.


问:
PSQL select either a or b in order but not both a and b if both a and b exists
I have a PSQL table

```<code>+--------+------+------+------+
|  Col1  | Col2 | Col3 | Col4 |
+--------+------+------+------+
|    001 | 00A  | 00B  | 001  |
| 001001 | 00A  | 00B  | 001  |
|    002 | 00X  | 00Y  | 002  |
| 002002 | 00X  | 00Y  | 002  |
+--------+------+------+------+
</code>```

I have the following PSQL query:

```<code>select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
order by Col3 asc;
</code>```

I get the first two rows.

Here what happens is that it matches both conditions for OR condition. I need to match only one of the or conditions. That is if first condition (Col1='001001') is true then do not evaluate the next condition.
I need to select only the 2nd row (| 001001 | 00A  | 00B  | 001  |)

I have build another query using EXCEPT

```<code>select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
    except (select *
            from my_table
            where Col1 != '001'
              and Col2 = '00A')
order by Col3 asc
limit 1;
</code>```

I would like to know if there is any other elegant queries for this job?

答:
Does this give you what you want?</p>

```<code>select *
from my_table
where (Col1 = '001' and Col2 != '00A')
    or ((Col1 is null or Col1 = '') and Col4 = '001' and Col2 = '00A')
order by Col3 asc;
</code>```

Body:
I have a PSQL table

+--------+------+------+------+
|  Col1  | Col2 | Col3 | Col4 |
+--------+------+------+------+
|    001 | 00A  | 00B  | 001  |
| 001001 | 00A  | 00B  | 001  |
|    002 | 00X  | 00Y  | 002  |
| 002002 | 00X  | 00Y  | 002  |
+--------+------+------+------+

I have the following PSQL query:

select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
order by Col3 asc;

I get the first two rows.

Here what happens is that it matches both conditions for OR condition. I need to match only one of the or conditions. That is if first condition (Col1='001001') is true then do not evaluate the next condition.
I need to select only the 2nd row (| 001001 | 00A  | 00B  | 001  |)

I have build another query using EXCEPT

select *
from my_table
where (Col1 = '001' or Col4 = '001')
  and Col2 = '00A'
    except (select *
            from my_table
            where Col1 != '001'
              and Col2 = '00A')
order by Col3 asc
limit 1;

I would like to know if there is any other elegant queries for this job?

Body:
Does this give you what you want?

select *
from my_table
where (Col1 = '001' and Col2 != '00A')
    or ((Col1 is null or Col1 = '') and Col4 = '001' and Col2 = '00A')
order by Col3 asc;


问:
How do I create a superuser account in Django 1.9.6
I am reading a book ("Learning Django Web Development" by Sanjeev Jaiswal and Ratan Kumar) on Django, but the book is based on an earlier version of Django (prior to version 1.9).  In order to populate the database with tables, the book uses the syncdb command:

```<code>$ python manage.py syncdb
</code>```

Then the book says that terminal will prompt you to create a superuser account.

the syncdb command is no longer used in Django version 1.9 and up.  After some research, it seems as if the migrate command populates the databse with tables, but it does not prompt the creation of a superuser account. How can I do this in Django 1.9.6?

答:
First we’ll need to create a user who can login to the admin site. Run
 the following command:

```<code>$ python manage.py createsuperuser
</code>```

Enter your desired username and press enter. Username: admin

You will then be prompted for your desired email address:

```<code>Email address: admin@example.com
</code>```

The final step is to enter your password. You will be asked to enter
 your password twice, the second time as a confirmation of the first.

```<code>Password: **********
Password (again): *********
Superuser created successfully.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am reading a book ("Learning Django Web Development" by Sanjeev Jaiswal and Ratan Kumar) on Django, but the book is based on an earlier version of Django (prior to version 1.9).  In order to populate the database with tables, the book uses the syncdb command:

$ python manage.py syncdb

Then the book says that terminal will prompt you to create a superuser account.

the syncdb command is no longer used in Django version 1.9 and up.  After some research, it seems as if the migrate command populates the databse with tables, but it does not prompt the creation of a superuser account. How can I do this in Django 1.9.6?

Body:
First we’ll need to create a user who can login to the admin site. Run
 the following command:

$ python manage.py createsuperuser

Enter your desired username and press enter. Username: admin

You will then be prompted for your desired email address:

Email address: admin@example.com

The final step is to enter your password. You will be asked to enter
 your password twice, the second time as a confirmation of the first.

Password: **********
Password (again): *********
Superuser created successfully.


问:
How to analyze only a part of an image?
I want to analyse a specific part of an image, as an example I'd like to focus on the bottom right 200x200 section and count all the black pixels, so far I have:</p>

```<code>im1 = Image.open(path)
rgb_im1 = im1.convert('RGB')
for pixel in rgb_im1.getdata():
</code>```

答:
You can try cropping the Image to the specific part that you want:-

```<code>img = Image.open(r"Image_location")
x,y = img.size
img = img.crop((x-200, y-200, x, y))
</code>```

The above code takes an input image, and crops it to its bottom right 200x200 pixels. (make sure the image dimensions are more then 200x200, otherwise an error will occur)

Original Image:-

Image after Cropping:-

You can then use this cropped image, to count the number of black pixels, where it depends on your use case what you consider as a BLACK pixel (a discrete value like (0, 0, 0) or a range/threshold (0-15, 0-15, 0-15)).

P.S.:- The final Image will always have a dimension of 200x200 pixels.

Title: How to analyze only a part of an image?

Body:
I want to analyse a specific part of an image, as an example I'd like to focus on the bottom right 200x200 section and count all the black pixels, so far I have:

im1 = Image.open(path)
rgb_im1 = im1.convert('RGB')
for pixel in rgb_im1.getdata():

Body:
You can try cropping the Image to the specific part that you want:-

img = Image.open(r"Image_location")
x,y = img.size
img = img.crop((x-200, y-200, x, y))

The above code takes an input image, and crops it to its bottom right 200x200 pixels. (make sure the image dimensions are more then 200x200, otherwise an error will occur)

Original Image:-

Image after Cropping:-

You can then use this cropped image, to count the number of black pixels, where it depends on your use case what you consider as a BLACK pixel (a discrete value like (0, 0, 0) or a range/threshold (0-15, 0-15, 0-15)).

P.S.:- The final Image will always have a dimension of 200x200 pixels.


问:
You can find all the cities using the expression - arrayName[“cityName”], since its an object
Given below is the list of cities in the states of India. You are supposed to complete
the function is given after this list which takes input as state name and sends the output as
a csv of the first letter of all the cities in that particular state

input - findCityFunction("Manipur")

output - "I,L,M,T"

explanation - "Imphal*","Lilong","Mayang Imphal","Thoubal" have their first letters as I, L, M and T.

答:
Given an object containing states and cities, it's fairly simple:

const statesAndCities = {
  "Manipur": ["Imphal","Lilong","Mayang Imphal","Thoubal"]
};

const findCityFunction = name => statesAndCities[name].map(([c]) => c).join(",");

console.log(findCityFunction("Manipur"));```


问:
Why does my website looks different on mozilla firefox and chrome?
I've been doing my html and i always open it using Mozilla Firefox. It seems okay but when I open it with my localhost using Chrome, it looks different.

Firefox

Chrome

This is the part that it went different:

```<code><div class ="label">
  <li><a href="html/profiles.html"> Profiles</a></li>
  <li><a href="html/expertise.html"> Expertise</a></li>
  <li><a href="html/location.html"> Location</a></li>
</div>
</code>```

This is the css part:

.label
{
  display: inline-flex;

}

.label li a
{
  margin-right: -433px;
  margin-left: 490px;
  text-decoration: none;
  font-size: 20px;
  list-style: none;
  font-family:"Arial", Serif;
  font-weight: bold;
  color: #3b5998;
}
.label li{
  list-style: none;
}
```

答:
The Problem is, that you are using
 Elements without its enclosing
 elements.
That it gets displayed correctly on firefox, is only a matter of luck.

try using the
 elements, too, or remove your
 tags.

For more informations take a look at this
  question.
  Here is the documentation of using
 or
 including

Body:
I've been doing my html and i always open it using Mozilla Firefox. It seems okay but when I open it with my localhost using Chrome, it looks different.

Firefox

Chrome

This is the part that it went different:

 Profiles

 Expertise

 Location

This is the css part:

.label
{
  display: inline-flex;

}

.label li a
{
  margin-right: -433px;
  margin-left: 490px;
  text-decoration: none;
  font-size: 20px;
  list-style: none;
  font-family:"Arial", Serif;
  font-weight: bold;
  color: #3b5998;
}
.label li{
  list-style: none;
}

Body:
The Problem is, that you are using <li> Elements without its enclosing <ul> elements.
That it gets displayed correctly on firefox, is only a matter of luck.

try using the <ul> elements, too, or remove your <li> tags.

For more informations take a look at this
  question.
  Here is the documentation of using <ul> or <ol> including <li>


问:
argparse multiple optional arguments
I'm writing a script which searches for a regex in one or more input files. If no input file is provided (or there is an "-" instead of a file), it should search in stdin.

Example: myscript.py [-h] [-u | -c | -m] [infile [infile ...]] regex

What I don't understand is - how does it differentiate filename from regex?
Let's say I type in myscript.py file1 file2 regex. How does it know that regex is a regular expression and not another file?

My code is as below:

```<code>def init_parser():
  parser = argparse.ArgumentParser(
    description="The script searches one or more named input files for lines\
     containing a match to a regular expression pattern."
  )
  parser.add_argument(
    '-f','--infile', nargs='*', type=argparse.FileType('r'), default='-',
    help='the name of the file(s) to search.'
  )
  parser.add_argument('regex', help='the regular expression.')
  group = parser.add_mutually_exclusive_group()
  group.add_argument(
    '-u', '--underscore', action='store_true',
    help='prints "^" under the matching text.'
  )
  group.add_argument(
    '-c', '--color', action='store_true',
    help='highlights matching text.'
  )
  group.add_argument(
    '-m', '--machine', action='store_true',
    help='generates machine readable output.'
  )

  return parser
</code>```

Since there are no flags to specify  the regex, the script can't differentiate between files and regex. If I don't specify a file (because I want it to read from stdin) it thinks that my regex is a file and it fails.

答:
Assuming you will always have a regex on the commandline, if you put the regex argument first, then infile, this will take the other positional arguments you specify:</p>

```<code>parser.add_argument('regex', help='the regular expression.')
parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), help='the name of the file(s) to search.')
</code>```

Title: argparse multiple optional arguments

Body:
I'm writing a script which searches for a regex in one or more input files. If no input file is provided (or there is an "-" instead of a file), it should search in stdin.

Example: myscript.py [-h] [-u | -c | -m] [infile [infile ...]] regex

What I don't understand is - how does it differentiate filename from regex?
Let's say I type in myscript.py file1 file2 regex. How does it know that regex is a regular expression and not another file?

My code is as below:

def init_parser():
  parser = argparse.ArgumentParser(
    description="The script searches one or more named input files for lines\
     containing a match to a regular expression pattern."
  )
  parser.add_argument(
    '-f','--infile', nargs='*', type=argparse.FileType('r'), default='-',
    help='the name of the file(s) to search.'
  )
  parser.add_argument('regex', help='the regular expression.')
  group = parser.add_mutually_exclusive_group()
  group.add_argument(
    '-u', '--underscore', action='store_true',
    help='prints "^" under the matching text.'
  )
  group.add_argument(
    '-c', '--color', action='store_true',
    help='highlights matching text.'
  )
  group.add_argument(
    '-m', '--machine', action='store_true',
    help='generates machine readable output.'
  )

  return parser

Since there are no flags to specify  the regex, the script can't differentiate between files and regex. If I don't specify a file (because I want it to read from stdin) it thinks that my regex is a file and it fails.

Body:
Assuming you will always have a regex on the commandline, if you put the regex argument first, then infile, this will take the other positional arguments you specify:

parser.add_argument('regex', help='the regular expression.')
parser.add_argument('infile', nargs='*', type=argparse.FileType('r'), help='the name of the file(s) to search.')


问:
How to pass multiple instances of models to controller in form
I'm setting up an asp.net form which collects reading from 5 power generators.

This is the model for each generator

```<code> public class GeneratorModel
{
    public int Id { get; set; }
    public String Name { get; set; }
    public float Belasting { get; set; }
    public float MaxBelasting { get; set; }
    public float KoudeReserve { get; set; }
}
</code>```

This is my view currently

```<code>@model XX.Models.GeneratorModel
@{
ViewBag.Title = "Data Entry";
}

@using (Html.BeginForm("Index", "DataEntry", FormMethod.Post))
{
<table>
    <tr>Generator 1</tr>
    <tr>
        <td>Enter Belasting: </td>
        <td>@Html.TextBoxFor(m => m.Belasting)</td>
    </tr>
    <tr>
        <td>Enter Max Belasting: </td>
        <td>@Html.TextBoxFor(m => m.MaxBelasting)</td>
    </tr>
    <tr>
        <td>Koude Reserve: </td>
        <td>@Html.TextBoxFor(m => m.KoudeReserve)</td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit" value="Submit Form" /></td>
    </tr>
</table>
}
</code>```

and my Controller is

```<code>[HttpPost]
public ActionResult Index(GeneratorModel generatorModel)
{
   return Content("Hello");
}
</code>```

Currently I can only enter values of 1 generator, but I need to take reading from 5 generators.

Is there a way that I can get an Array of GeneratorModel object as parameter in controller action result?

答:
you can try like this:

```<code>    <table class="col-md-offset-2 table table-bordered">
        <thead>
            <tr>
               <th>Name</th>
               <th>Belasting</th>
               <th>Max Belasting</th>
               <th>Koude Reserve</th>
               <th></th>
            </tr>
        </thead>
        <tbody id="GenaratorList">
            <tr>
               <td>@Html.TextBoxFor(m => m.Name)</td>
               <td>@Html.TextBoxFor(m => m.Belasting)</td>
               <td>@Html.TextBoxFor(m => m.MaxBelasting)</td>
               <td>@Html.TextBoxFor(m => m.KoudeReserve)</td>
               <td><input type="button" value="Add" onclick="addGenarator()"/></td>
            </tr>
         </tbody>
    </table>
    <input type="submit" value="Submit Form" />
</code>```

Then add some javascript to append new rows each time you click add and click submit only after you have added required no. of rows of genrator.
Change your controller to this:

```<code>[HttpPost]
public ActionResult Index(List<GeneratorModel> generatorModels)
{
   return Content("Hello");
}
</code>```

And the JS for appending new table rows:

```<code><script>
count=0;
function addGenarator() {
    var name = $('#Manifest_Quantity').val();
    var belasting= $('#Belasting').val();
    var mxBelasting= $('#MaxBelasting').val()
    var reserve= $('#KoudeReserve').val();

    var generator= "generatorModels[" + count + "]";
            $('#GenaratorList').append('<tr><td><input id="' + generator + '.Name" name="' + generator + '.Name" type="text" class="form-control" readonly value="' + name + '"></td><td><input id="' + generator + '.Belasting" name="' + generator + '.Belasting" type="text" class="form-control" readonly value="' + belasting + '"></td><td><input id="' + generator + '.MaxBelasting" name="' + generator + '.MaxBelasting" type="text" class="form-control" readonly value="' + mxBelasting + '"></td><td><input id="' + generator + '.KoudeReserve" name="' + generator + '.KoudeReserve" type="text" class="form-control" readonly value="' + reserve + '"></td></tr>');
            $('#Name,#Belasting,#MaxBelasting,#KoudeReserve').val('');
            count++;
        }
</script>
</code>```

Body:
I'm setting up an asp.net form which collects reading from 5 power generators.

This is the model for each generator

 public class GeneratorModel
{
    public int Id { get; set; }
    public String Name { get; set; }
    public float Belasting { get; set; }
    public float MaxBelasting { get; set; }
    public float KoudeReserve { get; set; }
}

This is my view currently

@model XX.Models.GeneratorModel
@{
ViewBag.Title = "Data Entry";
}

@using (Html.BeginForm("Index", "DataEntry", FormMethod.Post))
{

Generator 1

        Enter Belasting:
        @Html.TextBoxFor(m => m.Belasting)

        Enter Max Belasting:
        @Html.TextBoxFor(m => m.MaxBelasting)

        Koude Reserve:
        @Html.TextBoxFor(m => m.KoudeReserve)

        <input type="submit" value="Submit Form" />

}

and my Controller is

[HttpPost]
public ActionResult Index(GeneratorModel generatorModel)
{
   return Content("Hello");
}

Currently I can only enter values of 1 generator, but I need to take reading from 5 generators.

Is there a way that I can get an Array of GeneratorModel object as parameter in controller action result?

Body:
you can try like this:

    <table class="col-md-offset-2 table table-bordered">
        <thead>
            <tr>
               <th>Name</th>
               <th>Belasting</th>
               <th>Max Belasting</th>
               <th>Koude Reserve</th>
               <th></th>
            </tr>
        </thead>
        <tbody id="GenaratorList">
            <tr>
               <td>@Html.TextBoxFor(m => m.Name)</td>
               <td>@Html.TextBoxFor(m => m.Belasting)</td>
               <td>@Html.TextBoxFor(m => m.MaxBelasting)</td>
               <td>@Html.TextBoxFor(m => m.KoudeReserve)</td>
               <td><input type="button" value="Add" onclick="addGenarator()"/></td>
            </tr>
         </tbody>
    </table>
    <input type="submit" value="Submit Form" />

Then add some javascript to append new rows each time you click add and click submit only after you have added required no. of rows of genrator.
Change your controller to this:

[HttpPost]
public ActionResult Index(List<GeneratorModel> generatorModels)
{
   return Content("Hello");
}

And the JS for appending new table rows:

<script>
count=0;
function addGenarator() {
    var name = $('#Manifest_Quantity').val();
    var belasting= $('#Belasting').val();
    var mxBelasting= $('#MaxBelasting').val()
    var reserve= $('#KoudeReserve').val();

    var generator= "generatorModels[" + count + "]";
            $('#GenaratorList').append('<tr><td><input id="' + generator + '.Name" name="' + generator + '.Name" type="text" class="form-control" readonly value="' + name + '"></td><td><input id="' + generator + '.Belasting" name="' + generator + '.Belasting" type="text" class="form-control" readonly value="' + belasting + '"></td><td><input id="' + generator + '.MaxBelasting" name="' + generator + '.MaxBelasting" type="text" class="form-control" readonly value="' + mxBelasting + '"></td><td><input id="' + generator + '.KoudeReserve" name="' + generator + '.KoudeReserve" type="text" class="form-control" readonly value="' + reserve + '"></td></tr>');
            $('#Name,#Belasting,#MaxBelasting,#KoudeReserve').val('');
            count++;
        }
</script>


问:
Background process in web application in java
I have list of invoices which has pdfs in it. Users can select n number of invoices and click download button. Immediately we will show the new window showing status as pending but in background all the pdf should be merged and if the merging is over, the status should be changed to Available.

How to achieve background process in web application after sending response and send again response after background process completes

答:
Your Web UI could send the request to the WebServer which immediately spawns an internal Thread and returns status pending. While the WebServer's thread is processing, your UI could be usable (unlocked) again.

Alternative 1: The Web UI could poll every 5 seconds or so (see HTML5 web worker) to check on the status of this processing by a request/replay and retrieve the final result when done.

Alternative 2: You could establish some form of 'push notification' from WebServer to WebUI to make it known to the UI once the processing is done. There are a couple of Push APIs out there (choose it depending on your backend/frontend language). Some simply implement a polling status check as described above for you..  Other's like WebSocket are more generic. Unfortunately there's no standard yet, but it's coming, I hope: https://www.w3.org/TR/push-api/


问:
How to compare the temporary variables in the form of string?
I want to know why the two results are different?

the code is：

```<code>string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;
</code>```

the output is:

1 0

答:
You can use strcmp(), that returns a positive or negative value depending on a comparaison of the strings.

Check out the manual here : strcmp()

Be careful, it takes const char* and not strings as arguments.

Body:
I want to know why the two results are different?

the code is：

string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;

the output is:

1 0


问:
how to read csv file and extract specific coulmn?
This is my csv file :

```<code>CommitId                                RefactoringType      RefactoringDetail
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Pla
</code>```

I need to extract this:

```<code>RefactoringDetail
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
</code>```

I tried this code:

```<code>import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep='delimiter', header=None)
df.iloc[:,-1]
</code>```

it return all the data

Any help please!

答:
Pandas is spectacular for dealing with csv files, and the following code would be all you need to read a csv and save an entire column into a variable:

```<code>import pandas as pd
df = pd.read_csv('test.csv', sep=';')
refactoring_details = df['RefactoringDetail']
print(refactoring_details)
</code>```

Edit: separator in provided file is ; instead of the default ,.

Body:
This is my csv file :

CommitId                                RefactoringType      RefactoringDetail
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
d38f7b334856ed4007fb3ec0f8a5f7499ee2f2b8    Pull Up Attribute   "Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Pla

I need to extract this:

RefactoringDetail
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"
"Pull Up Attribute  protected steps : int from class blokusgame.mi.android.hazi.blokus.GameLogic.PlayerAlgorithm to class blokusgame.mi.android.hazi.blokus.GameLogic.Player"

I tried this code:

import pandas as pd
df = pd.read_csv('result_refactorings.csv', sep='delimiter', header=None)
df.iloc[:,-1]

it return all the data

Any help please!

Body:
Pandas is spectacular for dealing with csv files, and the following code would be all you need to read a csv and save an entire column into a variable:

import pandas as pd
df = pd.read_csv('test.csv', sep=';')
refactoring_details = df['RefactoringDetail']
print(refactoring_details)

Edit: separator in provided file is ; instead of the default ,.


问:
How do I step out of a loop with Ruby Pry?
I'm using Pry with my Rails application. I set binding.pry inside a loop in my model to try and debug a problem. For example:

```<code>(1..100).each do |i|
  binding.pry
  puts i
end
</code>```

When I type quit, it goes to the next iteration and stops again. Is there a way to step out of the loop so I don't have to type quit 100 times?

Currently the only way I know how to get out of it is to use CTRL+C and restart the application.

答:
press 'q' and you will see just like this

```<code>[1] pry(#<AlbumsController>)>
</code>```

type

```<code>exit
</code>```

this one word will do, if not:

```<code>control + c
</code>```

Body:
I'm using Pry with my Rails application. I set binding.pry inside a loop in my model to try and debug a problem. For example:

(1..100).each do |i|
  binding.pry
  puts i
end

When I type quit, it goes to the next iteration and stops again. Is there a way to step out of the loop so I don't have to type quit 100 times?

Currently the only way I know how to get out of it is to use CTRL+C and restart the application.

Body:
press 'q' and you will see just like this

[1] pry(#<AlbumsController>)>

type

exit

this one word will do, if not:

control + c


问:
MVP in windows forms
I want to implement MVPO pattern in my windows forms application. As you know there is 1:1 means there is one presenter for one view.

So basicly we can have:

```<code>public class MainPresenter
{
       IMainView _mainView;
       public MainPresenter(IMainView mainView)
       {
             _myView = myView;
       }
}
</code>```

My question is can one presenter use other presenter so for instance:

```<code>public class MainPresenter
{
       IMainView _mainView;
       ISomeOtherPresenter _otherPresenter;
       public MainPresenter(IMainView mainView, IOtherPresenter otherPresenter)
       {
             _mainView = myView;
             _otherPresenter = otherPresenter;
       }
}
</code>```

As a reference i went through video tutorial by Robert Marquez. At his 10 video serie at 10th one he used one rpesenter inside other one

Reference link

at 35:39 you will see his MainPresenter has dependency to IHelpAboutPresenter.

To me it's logical because if HelpAboutView (form) can be opened by button from MainView it's logical MainPresenter has to have access to HelpAboutPresenter which was presented on the video. If not that way how to do so because all the people saying 1:1 and here we have 1 presenter uses other presenter.

答:
It is a bit of a code small to has a cross dependency like that. If you need functionality from another presenter, it is likely the presenters have something in common. So perhaps they should derive from the same base class. Then they can easily share logic without complicating your dependency graph.</p>

```<code>public class BasePresenter
{
    protected void SharedMethod()
    {
        //Code that you need to call from both presenters
    }
}

public class MainPresenter : BasePresenter
{
    IMyView _myView;

    public MainPresenter(IMyView myView)
    {
        _myView = myView;
    }

    private Foo()
    {
        SharedFunction();
    }
}

public class OtherPresenter : BasePresenter
{

    public OtherPresenter(IMyView myView) : base()
    {
        _myView = myView;
    }

    private Bar()
    {
        SharedMethod();
    }
}
</code>```

Title: MVP in windows forms

Body:
I want to implement MVPO pattern in my windows forms application. As you know there is 1:1 means there is one presenter for one view.

So basicly we can have:

public class MainPresenter
{
       IMainView _mainView;
       public MainPresenter(IMainView mainView)
       {
             _myView = myView;
       }
}

My question is can one presenter use other presenter so for instance:

public class MainPresenter
{
       IMainView _mainView;
       ISomeOtherPresenter _otherPresenter;
       public MainPresenter(IMainView mainView, IOtherPresenter otherPresenter)
       {
             _mainView = myView;
             _otherPresenter = otherPresenter;
       }
}

As a reference i went through video tutorial by Robert Marquez. At his 10 video serie at 10th one he used one rpesenter inside other one

Reference link

at 35:39 you will see his MainPresenter has dependency to IHelpAboutPresenter.

To me it's logical because if HelpAboutView (form) can be opened by button from MainView it's logical MainPresenter has to have access to HelpAboutPresenter which was presented on the video. If not that way how to do so because all the people saying 1:1 and here we have 1 presenter uses other presenter.

Body:
It is a bit of a code small to has a cross dependency like that. If you need functionality from another presenter, it is likely the presenters have something in common. So perhaps they should derive from the same base class. Then they can easily share logic without complicating your dependency graph.

public class BasePresenter
{
    protected void SharedMethod()
    {
        //Code that you need to call from both presenters
    }
}

public class MainPresenter : BasePresenter
{
    IMyView _myView;

    public MainPresenter(IMyView myView)
    {
        _myView = myView;
    }

    private Foo()
    {
        SharedFunction();
    }
}

public class OtherPresenter : BasePresenter
{

    public OtherPresenter(IMyView myView) : base()
    {
        _myView = myView;
    }

    private Bar()
    {
        SharedMethod();
    }
}


问:
Convert a double to NSNumber in Swift
How do I convert a double to NSNumber in Swift?

I tried

```<code>let myDouble = 7.12
NSNumber(myDouble)
</code>```

But got the error:

Argument labels '(_:)' do not match any available overloads

答:
Use init(value:)

```<code>let nsNumber = NSNumber(value: myDouble)
</code>```

or simply a cast

```<code>let nsNumber = myDouble as NSNumber
</code>```

Title: Convert a double to NSNumber in Swift

Body:
How do I convert a double to NSNumber in Swift?

I tried

let myDouble = 7.12
NSNumber(myDouble)

But got the error:

Argument labels '(_:)' do not match any available overloads

Body:
Use init(value:)

let nsNumber = NSNumber(value: myDouble)

or simply a cast

let nsNumber = myDouble as NSNumber


问:
python regular expression to pick up first instance of " target = x"
I have a line "blabla somehing something target = 4, hjieei, target = 8, abcd ef", I want to have a python regular expression to give me the output of 4, which is the number after the 1st "target = ".

I have tried re.search('.*target = ([0-9.]+)’, line), it always give me value of 8 (Not 4).
I have tried below code, and it doss not work either.
Would you pls help.

```<code>line = "target = 4, hjieei, target = 8, abcd ef"
while line:
    target_1 = re.search('/[^target = ([0-9.]+)]*/)', line)
    if target_1 and target_1.groups():
        print("found: ", target_1.group(1))'
    break
</code>```

答:
Currently the .* is matching everything greedily and ends up giving you the last match found, which is 8.

So you would want to change your regex to start matching from the beginning by making it non-greedy by using .*?, abd then it will return the first match for you.

```<code>import re
line = "blabla somehing something target = 4, hjieei, target = 8, abcd ef"

target_1 = re.match(r'.*?target = ([0-9.]+)', line)
print(target_1.group(1))
</code>```

The output will be 4

Body:
I have a line "blabla somehing something target = 4, hjieei, target = 8, abcd ef", I want to have a python regular expression to give me the output of 4, which is the number after the 1st "target = ".

I have tried re.search('.*target = ([0-9.]+)’, line), it always give me value of 8 (Not 4).
I have tried below code, and it doss not work either.
Would you pls help.

line = "target = 4, hjieei, target = 8, abcd ef"
while line:
    target_1 = re.search('/[^target = ([0-9.]+)]*/)', line)
    if target_1 and target_1.groups():
        print("found: ", target_1.group(1))'
    break

Body:
Currently the .* is matching everything greedily and ends up giving you the last match found, which is 8.

So you would want to change your regex to start matching from the beginning by making it non-greedy by using .*?, abd then it will return the first match for you.

import re
line = "blabla somehing something target = 4, hjieei, target = 8, abcd ef"

target_1 = re.match(r'.*?target = ([0-9.]+)', line)
print(target_1.group(1))

The output will be 4


问:
How to add RadioButton and CheckBox on iPhone using MonoTouch?
I checked with Interface Builder and UI components. But there is no RadioButton and CheckBox. Is there some other way to add these components? Im using MonoTouch for developing iPhone application. </p>

答:
yes friend for this you have to add a image
in  .h file

```<code>int editCount;
int check;

in viewdidload{

editCount = 0;
    check = 0;
}

if( check == 0 )
    {
        UIButton *selectedButton = (UIButton *)sender;

        if (editCount%2 == 0) {
            [(UIButton *)[self.view viewWithTag:160] setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"TICKIMAGE",[selectedButton tag]] ofType:@"png"]] forState:UIControlStateNormal];

}
else {

            [(UIButton *)[self.view viewWithTag:160] setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"PLAINBUTTON",[selectedButton tag]] ofType:@"png"]] forState:UIControlStateNormal];

}

editcount++;
}
</code>```

this work similar to radio button u have to use tickimage and plainbutton image there ..ok friend

Body:
yes friend for this you have to add a image
in  .h file

int editCount;
int check;

in viewdidload{

editCount = 0;
    check = 0;
}

if( check == 0 )
    {
        UIButton *selectedButton = (UIButton *)sender;

        if (editCount%2 == 0) {
            [(UIButton *)[self.view viewWithTag:160] setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"TICKIMAGE",[selectedButton tag]] ofType:@"png"]] forState:UIControlStateNormal];

}
else {

            [(UIButton *)[self.view viewWithTag:160] setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"PLAINBUTTON",[selectedButton tag]] ofType:@"png"]] forState:UIControlStateNormal];

}

editcount++;
}

this work similar to radio button u have to use tickimage and plainbutton image there ..ok friend


问:
Angular material datepiker configure time
I want to use Angular material’s datepiker.

I would like to know how to make it start on Monday and not on Sunday.

Also for the date, when I select it, I have for example 24/05/2018 00:00 gmt+2:00. How to have the exact time without +2. 'Cause if I don’t, I’m going backend 23/05/2018 22:00

答:
You can write your own DateAdapter class, and provide this class in app.module.

You can find similar answer here.


问:
Adding days to a date in Python
I have a date "10/10/11(m-d-y)" and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.

I am using following code:

```<code>import re
from datetime import datetime

StartDate = "10/10/11"

Date = datetime.strptime(StartDate, "%m/%d/%y")
</code>```

print Date -> is printing '2011-10-10 00:00:00'

Now I want to add 5 days to this date. I used the following code:

```<code>EndDate = Date.today()+timedelta(days=10)
</code>```

Which returned this error:

```<code>name 'timedelta' is not defined
</code>```

答:
using timedeltas you can do:

```<code>import datetime
today=datetime.date.today()

time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00

# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)

# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output -
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03
</code>```

Title: Adding days to a date in Python

Body:
I have a date "10/10/11(m-d-y)" and I want to add 5 days to it using a Python script. Please consider a general solution that works on the month ends also.

I am using following code:

import re
from datetime import datetime

StartDate = "10/10/11"

Date = datetime.strptime(StartDate, "%m/%d/%y")

print Date -> is printing '2011-10-10 00:00:00'

Now I want to add 5 days to this date. I used the following code:

EndDate = Date.today()+timedelta(days=10)

Which returned this error:

name 'timedelta' is not defined

Body:
using timedeltas you can do:

import datetime
today=datetime.date.today()

time=datetime.time()
print("today :",today)

# One day different .
five_day=datetime.timedelta(days=5)
print("one day :",five_day)
#output - 1 day , 00:00:00

# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)

# five day extend .
fitfthday=today+five_day
print("fitfthday",fitfthday)
#output -
today : 2019-05-29
one day : 5 days, 0:00:00
fitfthday 2019-06-03


问:
How to implement rest login by using Spring security
Here's my code for login controller.java and AccessToken.java that is returned after login process

```<code>@RestController
@RequestMapping("/user")
public class Controller {

 @Autowired AuthenticationManager authenticationManager;
 @Autowired UserService userService;

 @RequestMapping(value="/login", method=RequestMethod.POST)
 public AccessToken logsin(
         @RequestBody AuthenticationRequest request,  HttpSession session
         ) {

     UsernamePasswordAuthenticationToken  token = new UsernamePasswordAuthenticationToken (request.getId(), request.getPassword());
     Authentication authentication = authenticationManager.authenticate(token);
     SecurityContextHolder.getContext().setAuthentication(authentication);
     session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
               SecurityContextHolder.getContext());

     AccessToken token1 = new AccessToken();
     token1.setUsername(authentication.getName());
     token1.setAuthorities(authentication.getAuthorities());
     token1.setToken(session.getId());

     Authentication a = SecurityContextHolder.getContext().getAuthentication();

     System.out.println("a.isAuthenticated : "+ a.isAuthenticated());

     return token1;
 }
</code>```

,

```<code>public class AccessToken {

private String username;
private Collection authorities;
private String token;
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public Collection getAuthorities() {
    return authorities;
}
public void setAuthorities(Collection authorities) {
    this.authorities = authorities;
}
public String getToken() {
    return token;
}
public void setToken(String token) {
    this.token = token;
}
</code>```

}

if I send a request to '/user/login' the login process, the value of  System.out.println("a.isAuthenticated : "+ a.isAuthenticated()); is 'true'

and I get back AccessToken
for example,

```<code>{
    "username": "myid1",
    "authorities": [
        {
            "authority": "user"
        }
    ],
    "token": "3D31F32383859DB145320941122CA189"
}
</code>```

And I set a filter class and HttpSessionStrategy bean for token authentication

```<code>@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    System.out.println("filter!");
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Expose-Headers", "x-auth-token");
    response.setHeader("Access-Control-Allow-Credentials", "x-auth-token");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}
</code>```

,

```<code>@EnableWebSecurity
public class WebSecurityConfig extends  WebSecurityConfigurerAdapter  {

@Autowired UserService userService;
@Autowired AuthenticationProvider provider;
@Autowired BCryptPasswordEncoder encoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
     http
        .csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
         .authorizeRequests()
               .antMatchers("/user/login").permitAll()
               .antMatchers("/main").authenticated()
               .antMatchers("main").authenticated()
               .antMatchers("/**").authenticated()

               .anyRequest().authenticated()
               .and()

          .logout()
          ;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     auth.userDetailsService(userService)
          .passwordEncoder(encoder);

}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
     return super.authenticationManagerBean();
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}
@Bean
public HttpSessionStrategy httpSessionStrategy() {
          return new HeaderHttpSessionStrategy();
}
</code>```

After that I sent a request to another url that needs authentication with header

'x-auth-token = 3D31F32383859DB145320941122CA189'

However the server responded with 403 forbidden error

How can I fix this problem?

答:
You need enable the springHttpSession and inmemory session Repository.

Please see here for the example code

Get token by username & password

curl -u user:password -v http://localhost:8080/api/token

Get me by token

curl -H "x-auth-token: $token" -v http://localhost:8080/me

Body:
Here's my code for login controller.java and AccessToken.java that is returned after login process

@RestController
@RequestMapping("/user")
public class Controller {

 @Autowired AuthenticationManager authenticationManager;
 @Autowired UserService userService;

 @RequestMapping(value="/login", method=RequestMethod.POST)
 public AccessToken logsin(
         @RequestBody AuthenticationRequest request,  HttpSession session
         ) {

     UsernamePasswordAuthenticationToken  token = new UsernamePasswordAuthenticationToken (request.getId(), request.getPassword());
     Authentication authentication = authenticationManager.authenticate(token);
     SecurityContextHolder.getContext().setAuthentication(authentication);
     session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,
               SecurityContextHolder.getContext());

     AccessToken token1 = new AccessToken();
     token1.setUsername(authentication.getName());
     token1.setAuthorities(authentication.getAuthorities());
     token1.setToken(session.getId());

     Authentication a = SecurityContextHolder.getContext().getAuthentication();

     System.out.println("a.isAuthenticated : "+ a.isAuthenticated());

     return token1;
 }

,

public class AccessToken {

private String username;
private Collection authorities;
private String token;
public String getUsername() {
    return username;
}
public void setUsername(String username) {
    this.username = username;
}
public Collection getAuthorities() {
    return authorities;
}
public void setAuthorities(Collection authorities) {
    this.authorities = authorities;
}
public String getToken() {
    return token;
}
public void setToken(String token) {
    this.token = token;
}

}

if I send a request to '/user/login' the login process, the value of  System.out.println("a.isAuthenticated : "+ a.isAuthenticated()); is 'true'

and I get back AccessToken
for example,

{
    "username": "myid1",
    "authorities": [
        {
            "authority": "user"
        }
    ],
    "token": "3D31F32383859DB145320941122CA189"
}

And I set a filter class and HttpSessionStrategy bean for token authentication

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    System.out.println("filter!");
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Expose-Headers", "x-auth-token");
    response.setHeader("Access-Control-Allow-Credentials", "x-auth-token");
    chain.doFilter(req, res);
}

public void init(FilterConfig filterConfig) {}

public void destroy() {}

}

,

@EnableWebSecurity
public class WebSecurityConfig extends  WebSecurityConfigurerAdapter  {

@Autowired UserService userService;
@Autowired AuthenticationProvider provider;
@Autowired BCryptPasswordEncoder encoder;
@Override
protected void configure(HttpSecurity http) throws Exception {
     http
        .csrf().disable()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
         .authorizeRequests()
               .antMatchers("/user/login").permitAll()
               .antMatchers("/main").authenticated()
               .antMatchers("main").authenticated()
               .antMatchers("/**").authenticated()

               .anyRequest().authenticated()
               .and()

          .logout()
          ;
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
     auth.userDetailsService(userService)
          .passwordEncoder(encoder);

}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
     return super.authenticationManagerBean();
}

@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}
@Bean
public HttpSessionStrategy httpSessionStrategy() {
          return new HeaderHttpSessionStrategy();
}

After that I sent a request to another url that needs authentication with header

'x-auth-token = 3D31F32383859DB145320941122CA189'

However the server responded with 403 forbidden error

How can I fix this problem?


问:
Error while installing flutter
```<code>$ flutter doctor
</code>```

Downloading Dart SDK 2.0.0-dev.16.0...
Unknown operating system. Cannot install Dart SDK.

error got shown up,why it occurs.

答:
go to

windows power shell->
right click->run as administrator->type flutter doctor

Title: Error while installing flutter

Body:
$ flutter doctor

Downloading Dart SDK 2.0.0-dev.16.0...
Unknown operating system. Cannot install Dart SDK.

error got shown up,why it occurs.


问:
How to set a readwrite internal, readonly external property in protocol
I have some classes have same behaviors, they all have

properties > savedPath: String, items: [String], currentItem: [String]

functions > archive(with items: [String]), unarchive()

So I create a protocol.swift and let those classes conform this protocol to implement these common behavior.But, in my case, i want:

items is a readonly external, readwrite internal

archive/unarchive are private func

i tried to use private(set) before items, private before archive/unarchive and some errors showed up.
Is there any flexible solutions to fix that?

before without protocol

class SampleClass {
    private(set) var items: [SampleModel] {
        set {
            archive(with: newValue)
        } get {
            return unarchive()
        }
    }

    func archive(with addresses: [SampleModel]) { ... }
    func unarchive() -> [SampleModel] { ... }
}
```

<p>after try to use protocol to satisfy</p>

<pre class="lang-swift prettyprint-override"><code>protocol SampleProtocol {
    associatedtype Item: Switchable

    var savedPath: String { get }
    var items: [Item] { get }
    var currentItem: Item? { get }

    func archive(with items: [Item])
    func unarchive() -> [Item]
}
</code>```

答:
You must remove any private function from protocol (Since it's meaningless). Nothing is private inside a protocol( setter or function or etc. )

```<code>protocol SampleProtocol {
    associatedtype Item: Switchable

    var savedPath: String { get }
    var items: [Item] { get }
    var currentItem: Item? { get }
}
</code>```

And you should then implement the class access controls like this:

```<code>class SampleClass {
    private(set) var items: [SampleModel] {
        set {
            archive(with: newValue)
        } get {
            return unarchive()
        }
    }

    private func archive(with addresses: [SampleModel]) { /* ... */ }
    private func unarchive() -> [SampleModel] { /* ... */ }
}
</code>```

Body:
I have some classes have same behaviors, they all have

properties > savedPath: String, items: [String], currentItem: [String]

functions > archive(with items: [String]), unarchive()

So I create a protocol.swift and let those classes conform this protocol to implement these common behavior.But, in my case, i want:

items is a readonly external, readwrite internal

archive/unarchive are private func

i tried to use private(set) before items, private before archive/unarchive and some errors showed up.
Is there any flexible solutions to fix that?

before without protocol

class SampleClass {
    private(set) var items: [SampleModel] {
        set {
            archive(with: newValue)
        } get {
            return unarchive()
        }
    }

    func archive(with addresses: [SampleModel]) { ... }
    func unarchive() -> [SampleModel] { ... }
}

after try to use protocol to satisfy

protocol SampleProtocol {
    associatedtype Item: Switchable

    var savedPath: String { get }
    var items: [Item] { get }
    var currentItem: Item? { get }

    func archive(with items: [Item])
    func unarchive() -> [Item]
}

Body:
You must remove any private function from protocol (Since it's meaningless). Nothing is private inside a protocol( setter or function or etc. )

protocol SampleProtocol {
    associatedtype Item: Switchable

    var savedPath: String { get }
    var items: [Item] { get }
    var currentItem: Item? { get }
}

And you should then implement the class access controls like this:

class SampleClass {
    private(set) var items: [SampleModel] {
        set {
            archive(with: newValue)
        } get {
            return unarchive()
        }
    }

    private func archive(with addresses: [SampleModel]) { /* ... */ }
    private func unarchive() -> [SampleModel] { /* ... */ }
}


问:
Why can't MySQL update a table and select from the same table in a subquery
At the bottom of the MySQL v5.6 documentation page for the UPDATE command it says:

You cannot update a table and select from the same table in a subquery.

For example, this will fail:

```<code>UPDATE actor
SET last_name = 'foo'
WHERE actor_id IN (
    SELECT actor_id
    FROM actor
    WHERE last_name = 'bar');
</code>```

Note: Please assume the column last_name is not a part of an index.

Why is this not allowed and is there a stable workaround for it?

P.S. - Thanks for the workaround! Can you please also explain why the example above is not allowed?

答:
This is a simple trick:

```<code>UPDATE actor
SET last_name = 'foo'
WHERE last_name = 'bar'
</code>```

Whatever you are doing is same as the above query.

Explanation: You can't just update something you are selecting.

If you want to go with your flow still then give an alias to sub-query by using temporary table,

```<code>UPDATE actor a1
SET a1.last_name = 'foo'
WHERE a1.actor_id IN (
    SELECT a2.actor_id
    FROM actor a2
    WHERE a2.last_name = 'bar');
</code>```

OR

```<code>UPDATE actor a1 SET a1.last_name='foo'
WHERE a1.actor_id IN (SELECT a2.actor_id
                    from (SELECT * FROM actor) a2
                    WHERE a2.last_name = 'bar');
</code>```

In other words in MySQL, you can’t modify the same table which you use in the SELECT part. This behavior is documented here.

And on stackoverflow link1 and link2.

Note:This is because your update could be cyclical… what if updating that record causes something to happen which made the
  WHERE condition FALSE? You know that isn’t the case, but the engine
  doesn’t. There also could be opposing locks on the table in the
  operation.

Body:
At the bottom of the MySQL v5.6 documentation page for the UPDATE command it says:

You cannot update a table and select from the same table in a subquery.

For example, this will fail:

UPDATE actor
SET last_name = 'foo'
WHERE actor_id IN (
    SELECT actor_id
    FROM actor
    WHERE last_name = 'bar');

Note: Please assume the column last_name is not a part of an index.

Why is this not allowed and is there a stable workaround for it?

P.S. - Thanks for the workaround! Can you please also explain why the example above is not allowed?

Body:
This is a simple trick:

UPDATE actor
SET last_name = 'foo'
WHERE last_name = 'bar'

Whatever you are doing is same as the above query.

Explanation: You can't just update something you are selecting.

If you want to go with your flow still then give an alias to sub-query by using temporary table,

UPDATE actor a1
SET a1.last_name = 'foo'
WHERE a1.actor_id IN (
    SELECT a2.actor_id
    FROM actor a2
    WHERE a2.last_name = 'bar');

OR

UPDATE actor a1 SET a1.last_name='foo'
WHERE a1.actor_id IN (SELECT a2.actor_id
                    from (SELECT * FROM actor) a2
                    WHERE a2.last_name = 'bar');

In other words in MySQL, you can’t modify the same table which you use in the SELECT part. This behavior is documented here.

And on stackoverflow link1 and link2.

Note:This is because your update could be cyclical… what if updating that record causes something to happen which made the
  WHERE condition FALSE? You know that isn’t the case, but the engine
  doesn’t. There also could be opposing locks on the table in the
  operation.


问:
Shadow for custom mouse cursor (2)
After reading the answer to the Shadow for custom mouse cursor question, I did some testing.

From my Delphi application I loaded both 32bit and 24bit versions of my cursor. Never a shadow. I did the same with the standard Windows arrow pointer. No shadow either.

Also I tried the opposite and assigned my custom cursors to the "Normal select" pointer in the Windows mouse settings. Both the 24bit and 32bit pointer were given a shadow.

So, it appears having an alpha channel in a cursor doesn't influence the shadow behaviour. But what am I doing wrong in my application?

First step is adding the cursor to the application's resources via an .rc file with

```<code>CUR_EDGE_R Cursor DISCARDABLE "edge_r.cur"
</code>```

And in the application it is loaded with:

```<code>const
  crEdgeR = TCursor(135);
 .
 .
  Screen.Cursors[crEdgeR] := LoadCursor(HInstance, 'CUR_EDGE_R');
</code>```

So, what is the way to have Windows add a shadow to a custom cursor?

Note: I have seen posts on the internet suggesting to create two version of the mouse cursor, one with and one without shadow, and load the appropriate cursor, depending on the user's settings. This is not the solution I'm looking for.

答:
In order to place a shadow under your custom cursor, you simply design the cursor with an Alpha channel (which enables semi transparency) and draw your shadow in place. You can even use Photoshop/GIMP (or any other capable graphics editor) to produce your cursor with a "Drop Shadow" effect, save it as a PNG, then use an Icon Editor (such as Microangello) to convert the PNG to a cursor.

As I understand it, none of the cursors shipped with Windows Vista/7 are designed as "flat", using some system effect to generate their shadows.

Title: Shadow for custom mouse cursor (2)

Body:
After reading the answer to the Shadow for custom mouse cursor question, I did some testing.

From my Delphi application I loaded both 32bit and 24bit versions of my cursor. Never a shadow. I did the same with the standard Windows arrow pointer. No shadow either.

Also I tried the opposite and assigned my custom cursors to the "Normal select" pointer in the Windows mouse settings. Both the 24bit and 32bit pointer were given a shadow.

So, it appears having an alpha channel in a cursor doesn't influence the shadow behaviour. But what am I doing wrong in my application?

First step is adding the cursor to the application's resources via an .rc file with

CUR_EDGE_R Cursor DISCARDABLE "edge_r.cur"

And in the application it is loaded with:

const
  crEdgeR = TCursor(135);
 .
 .
  Screen.Cursors[crEdgeR] := LoadCursor(HInstance, 'CUR_EDGE_R');

So, what is the way to have Windows add a shadow to a custom cursor?

Note: I have seen posts on the internet suggesting to create two version of the mouse cursor, one with and one without shadow, and load the appropriate cursor, depending on the user's settings. This is not the solution I'm looking for.


问:
Why are my title´s and image´s changing all the time I click on my project?
Every time I click on my button, a new controller is shown with a navigation bar. But unfortunately the images and titles change their order and duplicate themselves..

The order should be firm.

答:
Create a struct with the your table, icon and controller name as properties and store that struct in an array

```<code>struct Action {
    let label: String
    let control: String
    let icon: String
}

let actions = [Action(label: "Pläne", control: "PlansViewController2", icon: "plancorrection"),
               Action(label: "Dokumentationen", control: "DocumentationListViewCtrl", icon: "list"), ...]
</code>```

and then get all values needed from the same array

```<code>cell.titelLabel.text = actions[row].label
cell.imageView.image = UIImage(named: actions[row].icon)
cell.imageView.tintColor = UIColor.darkGray
</code>```

To get the correct identifier for the view controller

```<code>if let action = actions.first(where: {$0.label == pnc}) {
    let newController = storyBoard.instantiateViewController(withIdentifier: action.control)
} else {
    //some error handling here
}
</code>```

Body:
Create a struct with the your table, icon and controller name as properties and store that struct in an array

struct Action {
    let label: String
    let control: String
    let icon: String
}

let actions = [Action(label: "Pläne", control: "PlansViewController2", icon: "plancorrection"),
               Action(label: "Dokumentationen", control: "DocumentationListViewCtrl", icon: "list"), ...]

and then get all values needed from the same array

cell.titelLabel.text = actions[row].label
cell.imageView.image = UIImage(named: actions[row].icon)
cell.imageView.tintColor = UIColor.darkGray

To get the correct identifier for the view controller

if let action = actions.first(where: {$0.label == pnc}) {
    let newController = storyBoard.instantiateViewController(withIdentifier: action.control)
} else {
    //some error handling here
}


答:
Because "35" and "255" is not an std::string, it is a const char[] (that is, an array of characters). When you declare s1 and s2, the const char[] is converted into an std::string because the type of s1 and s2 is an std::string, but it won't do that automatically.

Running cout << (s1>s2) << " " << (string("35") > string("255")) << endl should work as you expect.

Title: How to compare the temporary variables in the form of string?

Body:
I want to know why the two results are different?

the code is：

string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;

the output is:

1 0


答:
Simply:

```<code>import re
data = "Batch size = 4, hjieei, Batch size = 8, abcd ef"
out = re.findall('\d', data)[0]
</code>```

Output:

```<code>4
</code>```

Title: python regular expression to pick up first instance of " target = x"

Body:
Simply:

import re
data = "Batch size = 4, hjieei, Batch size = 8, abcd ef"
out = re.findall('\d', data)[0]

Output:

4


问:
Rails Chartkick Gem Error Loading Chart No Adapter Found
I have a Rails 3.2.14 app where I'm using the chartkick and groupdate gem to try to generate some basic charts.

When I load my view I get the error:
Error Loading Chart: No adapter found

Here's what my view code looks like:

index.html.erb

<%= line_chart Call.group_by_week(:created_at).count %>

Here's my application layout including chartkick and yielding chart_js
application.html.erb (layout)

```<code> <%= javascript_include_tag "application", "chartkick" %>
 <%= yield :charts_js %>
</code>```

Can anyone tell me why I'm getting this error and how to fix it?  I'd really like to start using Chartkick to generate some simple charts.

答:
To View:
Google Charts
In your layout or views, add:

```<code><%= javascript_include_tag "https://www.gstatic.com/charts/loader.js" %>
</code>```

link: https://chartkick.com/#google-charts

Body:
I have a Rails 3.2.14 app where I'm using the chartkick and groupdate gem to try to generate some basic charts.

When I load my view I get the error:
Error Loading Chart: No adapter found

Here's what my view code looks like:

index.html.erb

<%= line_chart Call.group_by_week(:created_at).count %>

Here's my application layout including chartkick and yielding chart_js
application.html.erb (layout)

 <%= javascript_include_tag "application", "chartkick" %>
 <%= yield :charts_js %>

Can anyone tell me why I'm getting this error and how to fix it?  I'd really like to start using Chartkick to generate some simple charts.

Body:
To View:
Google Charts
In your layout or views, add:

<%= javascript_include_tag "https://www.gstatic.com/charts/loader.js" %>

link: https://chartkick.com/#google-charts


答:
Have you tried to avoid the subquery?</p>

```<code>UPDATE actor
SET last_name = 'foo'
WHERE last_name = 'bar';
</code>```

Title: Why can't MySQL update a table and select from the same table in a subquery

Body:
Have you tried to avoid the subquery?

UPDATE actor
SET last_name = 'foo'
WHERE last_name = 'bar';


问:
Need to remove unwanted symbols from value using replaceAll method
I am getting the value of a field as ["value"]
I  want to print only the  value removing the [ "from the result value.</p>

答:
That looks like a JSON array of Strings?  No idea, as you don't provide any context, but you could do:

```<code>import groovy.json.JsonSlurper

def valueField = '["value"]'
def result = new JsonSlurper().parseText(valueField).head()

println result
</code>```

Prints value

Body:
That looks like a JSON array of Strings?  No idea, as you don't provide any context, but you could do:

import groovy.json.JsonSlurper

def valueField = '["value"]'
def result = new JsonSlurper().parseText(valueField).head()

println result

Prints value


问:
Merge 64 Bit and 32 bit android APK as per new android requirement
We created 64-bit version of my app as per the android link.

Now we get two folders with 32-bit apk and 64-bit apk which is fine.

Now I want to know, how to merge both this 32/64 bit apk. Is it possible to merge them or we need to upload both 32 bit and 64-bit apk separately in google play store?

答:
It is ok to have multiple APKs for single app split by resources or NDK libs, because it reduces APKs sizes. You can upload multiple APKs as single app at Android Play Store, it will select appropriate APK for user before installation.

https://developer.android.com/studio/build/configure-apk-splits

https://stackoverflow.com/a/42336433/3858030


问:
W7P ListBox doesn't stay scrolled in the emulator
I have a ListBox in a xaml page for a Windows Phone 7 app. It starts out empty, then I populate it with some items once they are retrieved from a web service. So far that all works fine - the items show up in the list and all seems fine. The problem I have is when I try to drag the list to scroll to the bottom (in the emulator): I can scroll down, but as soon as I release the mouse button the list springs back to the top as though I hadn't scrolled it at all. Any insights into why it would behave this way?

```<code><Grid x:Name="ContentPanel" Grid.Row="2" Margin="0,0,0,0" Canvas.ZIndex="0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/> <!-- EDIT: the problem was "Auto" here should have been "*" -->
    </Grid.RowDefinitions>

    <!-- removed other element for brevity -->

    <ListBox Name="InfoBoardListBox" Grid.Row="1" SelectionChanged="InfoBoardListBox_SelectionChanged"
              Margin="0,0,0,0" FontSize="26.667" />
</Grid>
</code>```

And the method that populates the list:

```<code>    foreach (InfoBoard entry in boards.Values) {
        item = new ListBoxItem();
        item.Content = entry.Name;
        item.Name = entry.Id.ToString(); //used to tell which entry was clicked
        InfoBoardListBox.Items.Add(item);
    }
</code>```

答: Try setting the Height of the second row to * instead of Auto; I think it's to do with the size that the ListBox thinks it is vs. the available space.

Body:
I have a ListBox in a xaml page for a Windows Phone 7 app. It starts out empty, then I populate it with some items once they are retrieved from a web service. So far that all works fine - the items show up in the list and all seems fine. The problem I have is when I try to drag the list to scroll to the bottom (in the emulator): I can scroll down, but as soon as I release the mouse button the list springs back to the top as though I hadn't scrolled it at all. Any insights into why it would behave this way?

<Grid x:Name="ContentPanel" Grid.Row="2" Margin="0,0,0,0" Canvas.ZIndex="0">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>

    <ListBox Name="InfoBoardListBox" Grid.Row="1" SelectionChanged="InfoBoardListBox_SelectionChanged"
              Margin="0,0,0,0" FontSize="26.667" />
</Grid>

And the method that populates the list:

    foreach (InfoBoard entry in boards.Values) {
        item = new ListBoxItem();
        item.Content = entry.Name;
        item.Name = entry.Id.ToString(); //used to tell which entry was clicked
        InfoBoardListBox.Items.Add(item);
    }


问:
How to solve this error: Matrix size-incompatible: In[0]: [1,786432], In[1]: [784,512] [[{{node MatMul}}]]>
I need to do this simple machine learning code for  my school project but after many alterations I kept getting this error of invalid array. Can someone help? I'm quite desperate now as my submission date is close...

This is my code:

```<code>import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([

  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

model.fit(x_train, y_train, epochs=1)
model.evaluate(x_test, y_test)
# Part 3 - Making new predictions
import numpy as np
from keras.preprocessing import image
import keras
test_image = image.load_img('Number 8.jpg')
test_image = image.img_to_array(test_image, data_format='channels_first',
dtype='float32')
test_image = np.expand_dims(test_image, axis=0)
result = model.predict(test_image)
print(np.argmax(result[0]))
</code>```

答:
As tomkot already pointed out, its a shape problem.

The MNIST comes in shape [60000, 28, 28] and that's also the shape you train your model with.

I did a test with a Picture of my own and the shape that was passed to the predict was [1, 3, 1728, 2304].
This might differ in size from your 'Number 8.jpg' but as you can see will every picture being send with the wrong shape.

When you bring your picture in the shape that you trained your model with, your prediction should work just fine.

one way to reshape

```<code># load your image
test_image = test_image.resize((28, 28), resample=Image.BICUBIC))
#resize your image
test_image = test_image.resize((28,28), resample=Image.BICUBIC)
#on the prediction call reshape
result = model.predict(test_image.reshape(-1,28,28))
</code>```

the '-1' is another form to tell how many data your array contains.
You can also write it like '.reshape(1,28,28)'. '-1' just leaves it to python itself to figure out the proper value.

Body:
I need to do this simple machine learning code for  my school project but after many alterations I kept getting this error of invalid array. Can someone help? I'm quite desperate now as my submission date is close...

This is my code:

import tensorflow as tf
mnist = tf.keras.datasets.mnist

(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
model = tf.keras.models.Sequential([

  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(512, activation=tf.nn.relu),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation=tf.nn.softmax)
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
             metrics=['accuracy'])

model.fit(x_train, y_train, epochs=1)
model.evaluate(x_test, y_test)
# Part 3 - Making new predictions
import numpy as np
from keras.preprocessing import image
import keras
test_image = image.load_img('Number 8.jpg')
test_image = image.img_to_array(test_image, data_format='channels_first',
dtype='float32')
test_image = np.expand_dims(test_image, axis=0)
result = model.predict(test_image)
print(np.argmax(result[0]))

Body:
As tomkot already pointed out, its a shape problem.

The MNIST comes in shape [60000, 28, 28] and that's also the shape you train your model with.

I did a test with a Picture of my own and the shape that was passed to the predict was [1, 3, 1728, 2304].
This might differ in size from your 'Number 8.jpg' but as you can see will every picture being send with the wrong shape.

When you bring your picture in the shape that you trained your model with, your prediction should work just fine.

one way to reshape

# load your image
test_image = test_image.resize((28, 28), resample=Image.BICUBIC))
#resize your image
test_image = test_image.resize((28,28), resample=Image.BICUBIC)
#on the prediction call reshape
result = model.predict(test_image.reshape(-1,28,28))

the '-1' is another form to tell how many data your array contains.
You can also write it like '.reshape(1,28,28)'. '-1' just leaves it to python itself to figure out the proper value.


问:
Do I need to create multiple database connection in a loop?
I am using sqllite3 and want to insert data into the table. My code roughly looks like:

```<code>def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = sqlite3.connect(db)
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()
</code>```

As it can be seen, the database is connected and closed for each insertion of the data record. Is there a way to only connect and close the db once for all the data to be processed?

答:
If your code works on multithreading or multiprocessing. Connection pool involved will be more efficient. Definition from wiki

In software engineering, a connection pool is a cache of database
  connections maintained so that the connections can be reused when
  future requests to the database are required. Connection pools are
  used to enhance the performance of executing commands on a database.

Below is an exmaple from sqlalchemy. The pool manage all connections automatically, and you don't need to create a new connection when you need to execute SQL.

```<code>import sqlalchemy.pool as pool

import psycopg2

def getconn():
    c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
    return c

mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)

def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = mypool.connect()
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()
</code>```

Body:
I am using sqllite3 and want to insert data into the table. My code roughly looks like:

def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = sqlite3.connect(db)
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()

As it can be seen, the database is connected and closed for each insertion of the data record. Is there a way to only connect and close the db once for all the data to be processed?

Body:
If your code works on multithreading or multiprocessing. Connection pool involved will be more efficient. Definition from wiki

In software engineering, a connection pool is a cache of database
  connections maintained so that the connections can be reused when
  future requests to the database are required. Connection pools are
  used to enhance the performance of executing commands on a database.

Below is an exmaple from sqlalchemy. The pool manage all connections automatically, and you don't need to create a new connection when you need to execute SQL.

import sqlalchemy.pool as pool

import psycopg2

def getconn():
    c = psycopg2.connect(username='ed', host='127.0.0.1', dbname='test')
    return c

mypool = pool.QueuePool(getconn, max_overflow=10, pool_size=5)

def fill_database(db):
     ...
    for record in records:
       add_to_db(db, record)
 ...

def add_to_db(db, record):
   ...
   connection = mypool.connect()
   cursor = connection.cursor()
   cursor.execute("...")
   connection.commit()
   connection.close()


问:
jquery ajax, not returning HTML
I have an ajax request that looks like this,

```<code>$("#frmProducts").submit(function(){
                var dataSet = $("#frmProducts").serialize();
                $.ajax({
                  url: "<?php echo base_url();?>products/updateBasket",
                  data: dataSet,
                  type: "POST",
                  success: function(html){
                    $('html, body').animate({scrollTop:0}, 'slow');
                    $("#bagInfo").load("/checkout/loadCartView");
                    $('body').append(html);
                    $('#basketoverview').fadeIn(2000);
                    setTimeout(function () { $('#basketoverview').fadeOut(2000).hide(); }, 8000);
                  }
                });
                return false;
            });
</code>```

This should make a request to a URL and pull back a HTML segment, the PHP code the ajax is calling, looks like this;

```<code>function updateBasket()
{
    $this->load->model('Checkout_model');
    $this->load->model('Product_model');
    $derivativeId = $this->input->post('selDerivative-1');
    $quantity = $this->input->post('selQuantity');
    $derivative = $this->Product_model->GetProducts(array('pdId' => $derivativeId), 'small');

    // Add item to shopping bag.
    $attributes = $this->Product_model->GetProductDerivatives(array('pdId' => $derivativeId));
    $this->Checkout_model->AddProduct($derivative, $attributes, $quantity);
    $this->data['message'] = 'Item added to Shopping Bag.';

    // Update Delivery Price
    $this->Checkout_model->updateDelivery(49);

    $this->data['items'] = $this->Checkout_model->GetProducts();

    $this->template
    ->build('checkout/quickbasket', $this->data);
}
</code>```

However when I run the method, the HTML is not returned as I imagine it would be, and if I alert html in my javascript I get a black dialog box.

Any reason for this, have I done something wrong?

答:
Have you tried:</p>

```<code>dataType: 'html'
</code>```

Title: jquery ajax, not returning HTML

Body:
I have an ajax request that looks like this,

$("#frmProducts").submit(function(){
                var dataSet = $("#frmProducts").serialize();
                $.ajax({
                  url: "<?php echo base_url();?>products/updateBasket",
                  data: dataSet,
                  type: "POST",
                  success: function(html){
                    $('html, body').animate({scrollTop:0}, 'slow');
                    $("#bagInfo").load("/checkout/loadCartView");
                    $('body').append(html);
                    $('#basketoverview').fadeIn(2000);
                    setTimeout(function () { $('#basketoverview').fadeOut(2000).hide(); }, 8000);
                  }
                });
                return false;
            });

This should make a request to a URL and pull back a HTML segment, the PHP code the ajax is calling, looks like this;

function updateBasket()
{
    $this->load->model('Checkout_model');
    $this->load->model('Product_model');
    $derivativeId = $this->input->post('selDerivative-1');
    $quantity = $this->input->post('selQuantity');
    $derivative = $this->Product_model->GetProducts(array('pdId' => $derivativeId), 'small');

    // Add item to shopping bag.
    $attributes = $this->Product_model->GetProductDerivatives(array('pdId' => $derivativeId));
    $this->Checkout_model->AddProduct($derivative, $attributes, $quantity);
    $this->data['message'] = 'Item added to Shopping Bag.';

    // Update Delivery Price
    $this->Checkout_model->updateDelivery(49);

    $this->data['items'] = $this->Checkout_model->GetProducts();

    $this->template
    ->build('checkout/quickbasket', $this->data);
}

However when I run the method, the HTML is not returned as I imagine it would be, and if I alert html in my javascript I get a black dialog box.

Any reason for this, have I done something wrong?

Body:
Have you tried:

dataType: 'html'