问:
How to do create IP address range
Is there any way to create IP address range? like 192.168.0.1/24.
It's too annoy to create a data each time.
I find a Rubygems' ipaddress.
http://rubygems.org/gems/ipaddress.
I would like to take this to created IP range.

in new.heml.erb

```<code><%= f.lable :iprange %>
<%= f.text.field :iprange %>
</code>```

I don't how do used it in the rails' models

```<code>ip = IPAddress("192.168.0.1/24")
ip.each do |i|
 p i.to_s
end
</code>```

Somebody can give me some guide.

答:
Is this what you are looking for? (Warning: untested):

Model: subnet.rb

```<code>require 'ipaddress'
class Subnet < ActiveRecord::Base
  has_many :addresses

  after_create :populate_addresses

  def populate_addresses
    range     = IPAddress(self.iprange)
    subnet_id = self.id

    range.each do |ip|
      Address.create(:ipv4 => ip, :subnet_id => subnet_id)
    end
  end
end
</code>```

Model: address.rb

```<code>class Address < ActiveRecord::Base
  # ipv4: string
  # subnet_id: integer
  belongs_to :subnet
end
</code>```

This probably isn't the ideal way of handling this - a bit more logic is probably necessary to handle updates to the Subnet model & cascade those changes to the Address model.

Anyway, I hope this helps a bit.

Title: How to do create IP address range

Body:
Is there any way to create IP address range? like 192.168.0.1/24.
It's too annoy to create a data each time.
I find a Rubygems' ipaddress.
http://rubygems.org/gems/ipaddress.
I would like to take this to created IP range.

in new.heml.erb

<%= f.lable :iprange %>
<%= f.text.field :iprange %>

I don't how do used it in the rails' models

ip = IPAddress("192.168.0.1/24")
ip.each do |i|
 p i.to_s
end

Somebody can give me some guide.

Body:
Is this what you are looking for? (Warning: untested):

Model: subnet.rb

require 'ipaddress'
class Subnet < ActiveRecord::Base
  has_many :addresses

  after_create :populate_addresses

  def populate_addresses
    range     = IPAddress(self.iprange)
    subnet_id = self.id

    range.each do |ip|
      Address.create(:ipv4 => ip, :subnet_id => subnet_id)
    end
  end
end

Model: address.rb

class Address < ActiveRecord::Base
  # ipv4: string
  # subnet_id: integer
  belongs_to :subnet
end

This probably isn't the ideal way of handling this - a bit more logic is probably necessary to handle updates to the Subnet model & cascade those changes to the Address model.

Anyway, I hope this helps a bit.


来源: stackexchange

问:
Documentation on REST interface ActiveMQ
Currently I'm working on an interface to send and receive messages from an ActiveMQ instance on the network using the built-in REST interface (jolokia). Using the sparse documentation at hand I found out that we have one url named http://(server-ip):8161/api/message to both GET and POST messages on a predefined queue.

Sending works like a charm thus far, but receiving seems a bit more problematic. It creates a consumer per request which is not what I would like to have.

The documentation (http://activemq.apache.org/rest.html) tells me to keep the session alive and such, but I have no clue on how to do this. Furthermore, I cannot seem to find which parameters I can use to optimize these calls, nor what interfaces are available to connect to at all (apart of course from the api/message).

Is there any form of documentation or swagger-alike interface available at all for this? Any pointer in the right direction is appreciated.

[edit]
I know of this answer:
How does one enable or verify the REST interface of ActiveMQ?

Doug Dawson's question on the only answer is exactly what I was wondering as well.

答:
Consider the HTTP interface to ActiveMQ as a last resort, or a nice utility to read/write messages when performance or reliability is of no concern. It will not support many of the messaging semantics implemented in real message queueing protocols and won't be nearly as efficient.

If you have trouble using the AMQP or OpenWire/JMS apis because you have some JavaScript or mobile app code, then consider using WebSocket (MQTT or STOMP) instead of HTTP/"REST".

If you really want to find out the details of the "REST" interface - simply look at the code. It's not that much to read.

ContentLicense: CC BY-SA 3.0


问:
Do tracking pixels need to have alt attributes for accessibility (WCAG 2.0)?
We are running a website and have 3rd party tracking pixels, but we're receiving alt attribute errors when doing a webaim/WCAG 2.0 scan on our site.

I'm not sure if in this situation the tracking pixels actually need to still have a blank alt attribute or would some screen readers still read the src?

答:
I actually had the opportunity to meet with some of the Authors of the WCAG 2.0 rules and regs. Great group of people.

When I asked them the question re: pixels, they replied as others above re: the alt="". However, they stated that the preferred way to do this is doing the following:

change role="presentation"

and

aria=hidden

These are their 'default' recommendations, however they stated that also updating the alt="" would be added protection to help screen readers acknowledge that the pixel/URL is strictly decorative and not to be read by screen readers.


问:
System design: whether to normalize the departments or not
I'm working with two consultants in one project. The thing is we reached a point where both of them cannot get into an agreement and each offer a different approach.

The thing is we have a store with four departments and we want to find the best approach for working with all of them in the same database.

Each department sell different products: Cars, Boats, Jetskies and Motorbikes.

When the data is inserted or updated in each department there are some triggers to be fires so different workflows will begin, when adding a new car there are certain requirements that needs to be checked as well as the details of the car that are completely different than a boat. Also, regarding the data there are not many fields there are in common, I would say so far only the brand, color, model and year, everything else is specific for each deparment due to the different products and how they work with them..

Consultant one says:

Create one table for all the departments and use a column to identify what department the row belongs to, this way you will have only one trigger and inside the trigger you will then call the function/mehod you need for each record type.

Reason: you only have one table (with over 200 fields) and one trigger, is easier to maintain. Also if you need to report you just need to query one table and filter based on the record type. If you need to report for all the items you don't need to have multiple joins.

Consultant two says:

Create one table for each deparment and a trigger for each table.

Reason: you will have smaller tables (aprox 50 fields each) and is more flexible and you have it all separated. If you want to report you need to join the tables as you want to include data from different places.

I see the advantages of having everything in one place but if I want to expand or change anything I have the feeling I will bre creating a beast table as the data grows.

On the other side keep it separated look more appealing but will need to setup everything for each different table.

What would you say is the best approach?

答:
Option 2 for me.

You've said that there is little common data and the trigger logic is completely different. Here are some additional technical considerations.

Option 1 Warnings

The trigger would be a single point of failure and errors will be trickier to debug. I have worked with large triggers where broken logic near the top has stopped logic near the bottom from running, sometimes silently! You also have to maintain conditional guards to control the flow of logic based on the data which is another opportunity for error.

I'm not red hot on indexes but I believe performance will suffer due to no natural order of the multi-purpose data. More specific tables will yield better indexing strategies. Also, large rows can lead to fragmented indexes.

https://blogs.msdn.microsoft.com/pamitt/2010/12/23/notes-sql-server-index-fragmentation-types-and-solutions/

You would need extra consideration when setting nullable/default constraints on each surplus field not relevant to the product in question. These subtleties can introduce bugs and might make it harder if/when you decide to work with a data layer technology such as Entity Framework. E.g. the logical difference between NULL, 0 and 'None', especially on shared columns.


问:
Double versus float
I have a constant for pi in my code:

const float PI = acos(-1);

Would it be better to declare it as a double?  An answer to another question on this site said floating point operations aren't exactly precise, and I'd like the constant to be accurate.

答:
The question boils down to: how much accuracy do you need?

Let's quote wikipedia:

For example, the decimal
  representation of π truncated to 11
  decimal places is good enough to
  estimate the circumference of any
  circle that fits inside the Earth with
  an error of less than one millimetre,
  and the decimal representation of π
  truncated to 39 decimal places is
  sufficient to estimate the
  circumference of any circle that fits
  in the observable universe with
  precision comparable to the radius of
  a hydrogen atom.

I've written a small java program, here's its output:

```
As string: 3.14159265358979323846264338327950288419716939937510
As double: 3.141592653589793
As float:  3.1415927
```

Remember, that if you want to have the double precision of a double, all your numbers you're calculating with need also to be doubles. (That is not entierly true, but is close enough.)

ContentLicense: CC BY-SA 2.5

Title: Double versus float

Body:
The question boils down to: how much accuracy do you need?

Let's quote wikipedia:

For example, the decimal
  representation of π truncated to 11
  decimal places is good enough to
  estimate the circumference of any
  circle that fits inside the Earth with
  an error of less than one millimetre,
  and the decimal representation of π
  truncated to 39 decimal places is
  sufficient to estimate the
  circumference of any circle that fits
  in the observable universe with
  precision comparable to the radius of
  a hydrogen atom.

I've written a small java program, here's its output:

As string: 3.14159265358979323846264338327950288419716939937510
As double: 3.141592653589793
As float:  3.1415927

Remember, that if you want to have the double precision of a double, all your numbers you're calculating with need also to be doubles. (That is not entierly true, but is close enough.)


问:
Rails: ActiveRecord::AssociationTypeMismatch error
Is it possible to have the following two columns on an table and save them with active_record:

user_name_id (which is an association)

user_name (just text)

To demonstrate an attempt to save the association field user_name_id and the text field user_name

Here are the models:

```<code>#app/models/blog.rb
class Blog < ApplicationRecord
  belongs_to :user_name
end

#app/models/user_name.rb
class UserName < ApplicationRecord
  has_many :blogs
end
</code>```

The form:

```<code><%= form_for(blog) do |f| %>
  <% if blog.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(blog.errors.count, "error") %> prohibited this blog from being saved:</h2>

      <ul>
      <% blog.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :user_name %>
    <%= f.text_field :user_name %>
  </div>

  <div class="field">
    <%= f.label :user_name_id %>
    <%= f.collection_select :user_name_id, UserName.all, :id, :name %>
  </div>

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

The strong params:

```<code>def blog_params
  params.require(:blog).permit(:user_name, :user_name_id)
end
</code>```

When I submit the form in order to create a new blog, it errors out. The params hash looks ok:

```<code>“blog”=>{“user_name_id"=>"1", “user_name"=>”foo”}
</code>```

However I am getting the following error:

ActiveRecord::AssociationTypeMismatch
  UserName(#70119900697480) expected, got String(#70119800086640)

Update: I understand that, ideally: the column name of one of these attributes should change.  Nonetheless: is it possible to do this with rails?  What would it take?

答:
The issue is obvious from the answers above - change user_name attribute to be called something else.

As a very last resort, this might be a bad suggestion, but you could even try to declare which attribute you're using like:

```<code>class Blog < ApplicationRecord
  belongs_to :user_name, through: :user_name_id
end
</code>```

But again, the reason you're associating the records, is so that you can call user_name at any point, through the association, and get all the information stored there. Meaning, you don't need to store the user_name with the blog... because you already are through the user_name association.

Body:
Is it possible to have the following two columns on an table and save them with active_record:

user_name_id (which is an association)

user_name (just text)

To demonstrate an attempt to save the association field user_name_id and the text field user_name

Here are the models:

#app/models/blog.rb
class Blog < ApplicationRecord
  belongs_to :user_name
end

#app/models/user_name.rb
class UserName < ApplicationRecord
  has_many :blogs
end

The form:

<%= form_for(blog) do |f| %>
  <% if blog.errors.any? %>

<%= pluralize(blog.errors.count, "error") %> prohibited this blog from being saved:

      <% blog.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :user_name %>
    <%= f.text_field :user_name %>

    <%= f.label :user_name_id %>
    <%= f.collection_select :user_name_id, UserName.all, :id, :name %>

    <%= f.submit %>

<% end %>

The strong params:

def blog_params
  params.require(:blog).permit(:user_name, :user_name_id)
end

When I submit the form in order to create a new blog, it errors out. The params hash looks ok:

“blog”=>{“user_name_id"=>"1", “user_name"=>”foo”}

However I am getting the following error:

ActiveRecord::AssociationTypeMismatch
  UserName(#70119900697480) expected, got String(#70119800086640)

Update: I understand that, ideally: the column name of one of these attributes should change.  Nonetheless: is it possible to do this with rails?  What would it take?

Body:
The issue is obvious from the answers above - change user_name attribute to be called something else.

As a very last resort, this might be a bad suggestion, but you could even try to declare which attribute you're using like:

class Blog < ApplicationRecord
  belongs_to :user_name, through: :user_name_id
end

But again, the reason you're associating the records, is so that you can call user_name at any point, through the association, and get all the information stored there. Meaning, you don't need to store the user_name with the blog... because you already are through the user_name association.


问:
OpenShift-Ansible with MS Active Directory
Environment:

```<code>NAME="Red Hat Enterprise Linux Atomic Host"
VERSION="7.3"
ID="rhel"
ID_LIKE="fedora"
VARIANT="Atomic Host"
VARIANT_ID=atomic.host
VERSION_ID="7.3"
PRETTY_NAME="Red Hat Enterprise Linux Atomic Host 7.3"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:7.3:GA:atomic-host"
HOME_URL="https://www.redhat.com/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 7"
REDHAT_BUGZILLA_PRODUCT_VERSION=7.3
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION=7.3
</code>```

OpenShift-Ansible Version:

```<code>3.6.11-1
</code>```

This is openshift-ansible setup with Atomic hosts, so OpenShift itself is containerized.

Question:

Has anyone configured OpenShift using OpenShift-Ansible for MS Active Directory? I found this reference, but it implies that OpenShift master node service runs under systemd:

http://www.greenreedtech.com/openshift-origin-active-directory-integration/

Any suggestions?

答:
(Unfortunately, I don't have ability to test it but) OpenShift documentation says that

The installation process creates relevant systemd units which can be used to start, stop, and poll services using normal systemctl commands.

So, I'd expect that command systemctl restart origin-master should work (except, in your case it will be atomic-openshift-master)

It also says that

configuration files are placed in the same locations during containerized installation as RPM based installations

so I'd expect that this instruction would work.

Body:
Environment:

NAME="Red Hat Enterprise Linux Atomic Host"
VERSION="7.3"
ID="rhel"
ID_LIKE="fedora"
VARIANT="Atomic Host"
VARIANT_ID=atomic.host
VERSION_ID="7.3"
PRETTY_NAME="Red Hat Enterprise Linux Atomic Host 7.3"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:redhat:enterprise_linux:7.3:GA:atomic-host"
HOME_URL="https://www.redhat.com/"
BUG_REPORT_URL="https://bugzilla.redhat.com/"

REDHAT_BUGZILLA_PRODUCT="Red Hat Enterprise Linux 7"
REDHAT_BUGZILLA_PRODUCT_VERSION=7.3
REDHAT_SUPPORT_PRODUCT="Red Hat Enterprise Linux"
REDHAT_SUPPORT_PRODUCT_VERSION=7.3

OpenShift-Ansible Version:

3.6.11-1

This is openshift-ansible setup with Atomic hosts, so OpenShift itself is containerized.

Question:

Has anyone configured OpenShift using OpenShift-Ansible for MS Active Directory? I found this reference, but it implies that OpenShift master node service runs under systemd:

http://www.greenreedtech.com/openshift-origin-active-directory-integration/

Any suggestions?


问:
Count Days in SQL SERVER in Case When Clause
I have Table

```<code>1        2013-10-01 08:21        Null               Null        Null
1        2013-10-01 14:30        Null               Null        Null
2        2013-10-01 08:31        Null                Lt         Null
2        2013-10-01 14:31         EO                Null        Null
3        2013-10-01 14:30         EO                Null       Ab here
</code>```

this Table is Result from this query

```<code> SELECT m.ID,L.Log_D,W.Sat,L.C,
   (CASE WHEN convert(time,L.Log_D)>'08:31:00' and convert(time,L.Log_D)<'10:30:00' and L.C =1  then 'Lt'end )as Late,
     (CASE WHEN convert(time,L.Log_D)<'13:30:00'  and L.C =2  then 'Ab'end )as EarlyOut,
     (CASE WHEN DATENAME(DAY, day( L.Log_D)) =2 THEN 'Ab'  END) as Counte
   from WorkPeriod W,LogT L,MinimumInfoT m  where  day(L.Log_D) =1
   and month(L.Log_D) =10
   and year(L.Log_D) =2013
   and W.id=54
   and m.Branch_ID=35
   and L.C in(1,2)
   and M.ID =L.EmpId
   and W.id =m.W_Period
   group by m.ID,L.Log_D,W.Sat,L.C
   order by m.ID
</code>```

I need the Absent Column Display as 'Ab' when the count Of the Day is less then  2 for each Id is that possible any help will be appreciated

答:
You can use a Window Function to do this:

```<code>CASE WHEN COUNT(*) OVER (PARTITION BY m.ID) < 2 THEN 'ab' ELSE NULL END as Counte
</code>```

This will get a count of records for each distinct m.ID. If the count for the current m.ID is less than 2, then it spits out ab.

Body:
I have Table

1        2013-10-01 08:21        Null               Null        Null
1        2013-10-01 14:30        Null               Null        Null
2        2013-10-01 08:31        Null                Lt         Null
2        2013-10-01 14:31         EO                Null        Null
3        2013-10-01 14:30         EO                Null       Ab here

this Table is Result from this query

 SELECT m.ID,L.Log_D,W.Sat,L.C,
   (CASE WHEN convert(time,L.Log_D)>'08:31:00' and convert(time,L.Log_D)<'10:30:00' and L.C =1  then 'Lt'end )as Late,
     (CASE WHEN convert(time,L.Log_D)<'13:30:00'  and L.C =2  then 'Ab'end )as EarlyOut,
     (CASE WHEN DATENAME(DAY, day( L.Log_D)) =2 THEN 'Ab'  END) as Counte
   from WorkPeriod W,LogT L,MinimumInfoT m  where  day(L.Log_D) =1
   and month(L.Log_D) =10
   and year(L.Log_D) =2013
   and W.id=54
   and m.Branch_ID=35
   and L.C in(1,2)
   and M.ID =L.EmpId
   and W.id =m.W_Period
   group by m.ID,L.Log_D,W.Sat,L.C
   order by m.ID

I need the Absent Column Display as 'Ab' when the count Of the Day is less then  2 for each Id is that possible any help will be appreciated

Body:
You can use a Window Function to do this:

CASE WHEN COUNT(*) OVER (PARTITION BY m.ID) < 2 THEN 'ab' ELSE NULL END as Counte

This will get a count of records for each distinct m.ID. If the count for the current m.ID is less than 2, then it spits out ab.


问:
Replace the ascii apostrophe with a real apostrophe in a sql database
I am converting my classic asp to .Net using parameterized queries. My     problem is that in my classic apps I would replace the apostrophe with the ascii equivelent '

Now I would like to replace that value in the database with a real apostrophe.  I am not sure how the syntax should be to do this.  I can find the ' but I am not sure how to replace.  The following is the simple update I am trying to run that errors out.

update tblCustomer set
Name = replace(Name, ''', ''')

答:
Double up the apostrophe to escape it in a string literal

```<code>update tblCustomer set Name = replace(Name, ''', '''')
</code>```

Or use the char function

```<code>update tblCustomer set Name = replace(Name, ''', CHAR(39))
</code>```

Body:
Double up the apostrophe to escape it in a string literal

update tblCustomer set Name = replace(Name, '&#39;', '''')

Or use the char function

update tblCustomer set Name = replace(Name, '&#39;', CHAR(39))


问:
extend scope of pass by ref object for std::thread
To demonstrate the problem, let me present a short code -

```<code>void someMethod() {

  // CustomType obj;
  const auto obj = getCustomTypeObj();

  std::thread([](customType &obj) {
    // some delay
    obj.doSomething();
    obj.close();
    // can now be destructed
  }).detach();

  // similarly for std::async
  std::async(std::launch::async, [](customType &obj){
    obj.doSomething();
    obj.close();
  }

  // there might not be any use of obj here

  // should not be destructed here because std::thread might not get it.

}
</code>```

In above code, an CustomType type object is constructed for which copy constructor is deleted. So I must pass it by reference everywhere, or create it from scratch in relevant scope. However for 1 scenario I'm currently dealing with, it is not quite possible to create it in relevant scope which is inside std::thread's execution method.

What I'm afraid of is obj might be destructed before std::thread even completes its job and then I've no idea what's going to happen. So how should I solve this problem of extending it's scope to std::thread's lambda.

答:
Btw your code is incorrect, you do not pass your object, so your code should be instead:

```<code>  auto obj = getCustomTypeObj();

  std::thread([](customType &obj) {
    // some delay
    obj.doSomething();
    obj.close();
    // can now be destructed
  }, std::ref( obj ) ).detach();
</code>```

To avoid issue with object lifetime pass your object to the lambda or function by value and move your object there:

```<code>  auto obj = getCustomTypeObj();

  std::thread([](customType arg) { // note by value, not reference
    // some delay
    arg.doSomething();
    arg.close();
    // arg will be destroyed here
  }, std::move( obj ) ).detach(); // object moved
</code>```

now lambda or function owns that object and it will be destroyed at the end of the function. Here is the live example, I just used std::unique_ptr there instead of customType as type that has copying disabled to validate that moving works.

Body:
To demonstrate the problem, let me present a short code -

void someMethod() {

  // CustomType obj;
  const auto obj = getCustomTypeObj();

  std::thread([](customType &obj) {
    // some delay
    obj.doSomething();
    obj.close();
    // can now be destructed
  }).detach();

  // similarly for std::async
  std::async(std::launch::async, [](customType &obj){
    obj.doSomething();
    obj.close();
  }

  // there might not be any use of obj here

  // should not be destructed here because std::thread might not get it.

}

In above code, an CustomType type object is constructed for which copy constructor is deleted. So I must pass it by reference everywhere, or create it from scratch in relevant scope. However for 1 scenario I'm currently dealing with, it is not quite possible to create it in relevant scope which is inside std::thread's execution method.

What I'm afraid of is obj might be destructed before std::thread even completes its job and then I've no idea what's going to happen. So how should I solve this problem of extending it's scope to std::thread's lambda.

Body:
Btw your code is incorrect, you do not pass your object, so your code should be instead:

  auto obj = getCustomTypeObj();

  std::thread([](customType &obj) {
    // some delay
    obj.doSomething();
    obj.close();
    // can now be destructed
  }, std::ref( obj ) ).detach();

To avoid issue with object lifetime pass your object to the lambda or function by value and move your object there:

  auto obj = getCustomTypeObj();

  std::thread([](customType arg) { // note by value, not reference
    // some delay
    arg.doSomething();
    arg.close();
    // arg will be destroyed here
  }, std::move( obj ) ).detach(); // object moved

now lambda or function owns that object and it will be destroyed at the end of the function. Here is the live example, I just used std::unique_ptr there instead of customType as type that has copying disabled to validate that moving works.


问:
C - Turn void** into char* easily?
One of my data structures is an array of type void*. It does this because it allows for any type of data to be inputted without me having to hard code types.

In this case, this data structure now contains and array of void* where each void* is actually a pointer to a character.

Is there a way I can treat this array as a char* (meaning an array of characters) or do I have to loop through it, add into a new array by retrieving values, etc?

```<code>// this is not my actual code, just demonstration
char v = 'A';

size_t size = 10;
void** myArr = malloc(sizeof(void*) * size);
for (unsigned int i = 0; i < size - 1; i++)
{
    char *ptr = malloc(sizeof(char));
    *ptr = v++;
    myArr[i] = ptr; // ptr here gets casted into a void*
}
char *end = malloc(sizeof(char));
*end = '\0';
myArr[size - 1] = end;

/*
* I now want to turn myArr into an array of characters,
meaning I could call printf and it would successfully print the array
with printf("%s", <something here>);
*/
char* arrayInStringForm = *(char**)myArr; // I don't think this can work.
// Any way to do it without looping or using more memory?
printf("%s\n", arrayInStringForm);

// Expected output:
// A B C D E F G H I J
</code>```

答:
Edit:

I don't understand yourt question either...

There is no need for optimization here, since printf will eventually call I/O functions that will span across thousands of instructions (imagine what your CPU will go through if your characters happen to trigger a window scrolling).

Whatever the origin of your mysterious characters might be, the time needed to generate a proper C-string out of them will be utterly neglectible.

So just loop over them and put them in a basic array of characters, add a \0 terminator, call a printf("%s"..., and Bob will be your happy uncle.

Title: C - Turn void** into char* easily?

Body:
One of my data structures is an array of type void*. It does this because it allows for any type of data to be inputted without me having to hard code types.

In this case, this data structure now contains and array of void* where each void* is actually a pointer to a character.

Is there a way I can treat this array as a char* (meaning an array of characters) or do I have to loop through it, add into a new array by retrieving values, etc?

// this is not my actual code, just demonstration
char v = 'A';

size_t size = 10;
void** myArr = malloc(sizeof(void*) * size);
for (unsigned int i = 0; i < size - 1; i++)
{
    char *ptr = malloc(sizeof(char));
    *ptr = v++;
    myArr[i] = ptr; // ptr here gets casted into a void*
}
char *end = malloc(sizeof(char));
*end = '\0';
myArr[size - 1] = end;

/*
* I now want to turn myArr into an array of characters,
meaning I could call printf and it would successfully print the array
with printf("%s", <something here>);
*/
char* arrayInStringForm = *(char**)myArr; // I don't think this can work.
// Any way to do it without looping or using more memory?
printf("%s\n", arrayInStringForm);

// Expected output:
// A B C D E F G H I J


问:
How to revert code one line at a time?
I was pair programming on a project with a colleague. We made great progress but we forgot to commit the work we collaborated on. Later on, my team mate went off and made some experimental changes in another part of the code base. He then committed that experimental work, and accidentally included the work we did together without realizing it.

I now have a fork of his branch and the commit with our combined work. Is there a way to go through each line of code that was add/removed in that commit and choose to keep or revert it?

答:
well it's never wise to edit git's history but if you MUST you can always use git rebase. read carefully the man page associated to it. i suppose what you need to do is something among these line:

```<code>git rebase -i <commit>
</code>```

this will launch an interactive editor with the list of commits in that revision, there the first column of each commit listed indicates what action should be performed with given commit; one of those actions is edit. when an edit is found git rebase stops so that you can edit the files or the commit message, amend the commit and then continue rebasing.

i recommend reading carefully man git rebase and try first the dynamics of the command in a test repo.

Title: How to revert code one line at a time?

Body:
well it's never wise to edit git's history but if you MUST you can always use git rebase. read carefully the man page associated to it. i suppose what you need to do is something among these line:

git rebase -i <commit>

this will launch an interactive editor with the list of commits in that revision, there the first column of each commit listed indicates what action should be performed with given commit; one of those actions is edit. when an edit is found git rebase stops so that you can edit the files or the commit message, amend the commit and then continue rebasing.

i recommend reading carefully man git rebase and try first the dynamics of the command in a test repo.


问:
com.ibm.websphere.management.exception.AdminException:
Good day,

My server keep hitting the following error when I try to start/clean my server.

```<code>[11/17/14 10:18:43:715 MYT] 00000091 InstallSchedu I   ADMA5014E: The installation of application BeansEaiApp failed.
[11/17/14 10:18:43:706 MYT] 00000091 SystemErr     R com.ibm.websphere.management.exception.AdminException: A composition unit with name BeansEaiApp already exists. Select a different application name.
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask._validateBLAInstall(ValidateBLATask.java:348)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask._performTaskAsSystem(ValidateBLATask.java:132)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask$1.run(ValidateBLATask.java:104)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5429)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.security.auth.ContextManagerImpl.runAsSpecified(ContextManagerImpl.java:5520)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask.performTask(ValidateBLATask.java:101)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.application.SchedulerImpl.run(SchedulerImpl.java:315)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at java.lang.Thread.run(Thread.java:770)
</code>```

Search google for quite a long time but no solution can apply to my environment. I have tried to restart my computer, restart VM, remove the App and add again, but still the same. Keep publishing failed. And there is no compilation error at my workspace also.

Kindly advise.

答: Goto windows Start->Type " Services " from the list search for IBM Webshpere Application Server -> Right Click on it and click Stop.</p>

Body:
Good day,

My server keep hitting the following error when I try to start/clean my server.

[11/17/14 10:18:43:715 MYT] 00000091 InstallSchedu I   ADMA5014E: The installation of application BeansEaiApp failed.
[11/17/14 10:18:43:706 MYT] 00000091 SystemErr     R com.ibm.websphere.management.exception.AdminException: A composition unit with name BeansEaiApp already exists. Select a different application name.
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask._validateBLAInstall(ValidateBLATask.java:348)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask._performTaskAsSystem(ValidateBLATask.java:132)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask$1.run(ValidateBLATask.java:104)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5429)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.security.auth.ContextManagerImpl.runAsSpecified(ContextManagerImpl.java:5520)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.bla.j2ee.ext.tasks.ValidateBLATask.performTask(ValidateBLATask.java:101)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at com.ibm.ws.management.application.SchedulerImpl.run(SchedulerImpl.java:315)
[11/17/14 10:18:43:707 MYT] 00000091 SystemErr     R    at java.lang.Thread.run(Thread.java:770)

Search google for quite a long time but no solution can apply to my environment. I have tried to restart my computer, restart VM, remove the App and add again, but still the same. Keep publishing failed. And there is no compilation error at my workspace also.

Kindly advise.


问:
How can I synchronize closures?
How can I synchronize closures?

I have this code:

```<code>    private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {

        for _ in 0...10 {

            RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
                if JSON.parse(result)["name"].string == nil {
                    failure?("Something went wrong. Please, try again later")
                } else {
                    let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
                }
            })
        }
        completion?()

    }
</code>```

In my code, completion?() will call, not when all requests will ended
And I need call completion?() when all requests will ended. Ho can I do it?

答:
An easy way to do this is just to count completed calls.

```<code>private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {
    let numCalls = 11;
    var completedCalls = 0;

    for _ in 0..<numCalls {

        RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
            if JSON.parse(result)["name"].string == nil {
                failure?("Something went wrong. Please, try again later")
            } else {
                let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
            }
            completedCalls += 1
            if completedCalls == numCalls {
                completion?()
            }
        })
    }
}
</code>```

Your completion callback runs when each request ends. Making each of your completion callbacks update a value in its enclosing scope allows you to keep track of how many requests have ended. When all the requests you expect have ended, you call completion?().

Title: How can I synchronize closures?

Body:
How can I synchronize closures?

I have this code:

    private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {

        for _ in 0...10 {

            RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
                if JSON.parse(result)["name"].string == nil {
                    failure?("Something went wrong. Please, try again later")
                } else {
                    let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
                }
            })
        }
        completion?()

    }

In my code, completion?() will call, not when all requests will ended
And I need call completion?() when all requests will ended. Ho can I do it?

Body:
An easy way to do this is just to count completed calls.

private func getWeather(parameters: [String : Any],  failure: ((String) -> Void)? = nil ,completion: (() -> Void)? = nil) {
    let numCalls = 11;
    var completedCalls = 0;

    for _ in 0..<numCalls {

        RequestManager.sharedInstance.request(url: baseURL, parameters: parameters, completion:  { (result) in
            if JSON.parse(result)["name"].string == nil {
                failure?("Something went wrong. Please, try again later")
            } else {
                let weatherModel: WeatherModel = WeatherModel(json: JSON.parse(result))
            }
            completedCalls += 1
            if completedCalls == numCalls {
                completion?()
            }
        })
    }
}

Your completion callback runs when each request ends. Making each of your completion callbacks update a value in its enclosing scope allows you to keep track of how many requests have ended. When all the requests you expect have ended, you call completion?().


问:
.Net Multiline Regex expression to restrict to integers
I am having a problem with a very simple regular expression.

I want to restrict the entry in a multi-line TextBox to just integers. The regular expression I have works fine in single line mode (for a single line TextBox, not using multiline option), but allows alpha characters to creep in when in multiline mode, but only once a new line has been entered.

My code (C#) is something like:

```<code>Regex regExpr = new Regex("^(\d*)$", RegexOptions.Multiline)
return regExpr.IsMatch(testString);
</code>```

I want the following examples to be valid:

```<code>1

1\\n

1\\n2\\n3
</code>```

I want the following to be invalid

```<code>A

A1\\n2

1\\n2\\nA3
</code>```

Thanks in advance.

答:
Do you want to destructively remove the alphas or just send it back for the user to re-enter the info?

to remove just do a search replace with with an empty result.

[^\d\n]

To check to see if there's anything other than a number and \n do the same thing only on the first occurrence error the page submit and send back to the user.

Since I don't know which .Net lang you're using I can only give general principles.

Body:
I am having a problem with a very simple regular expression.

I want to restrict the entry in a multi-line TextBox to just integers. The regular expression I have works fine in single line mode (for a single line TextBox, not using multiline option), but allows alpha characters to creep in when in multiline mode, but only once a new line has been entered.

My code (C#) is something like:

Regex regExpr = new Regex("^(\d*)$", RegexOptions.Multiline)
return regExpr.IsMatch(testString);

I want the following examples to be valid:

1

1\\n

1\\n2\\n3

I want the following to be invalid

A

A1\\n2

1\\n2\\nA3

Thanks in advance.


问:
Ruby on rails log file size too large
I stumbled to learn that my rails3.1 log file is super large, around 21mb.
Is this, in terms of size normal? What the log file would like in the production environment?
Besides, can I get rid of the log?thanks</p>

答:
A fair compromise, in an initializer:</p>

```<code>Rake::Task['log:clear'].invoke if Rails.env.development? || Rails.env.test?
</code>```

Title: Ruby on rails log file size too large

Body:
A fair compromise, in an initializer:

Rake::Task['log:clear'].invoke if Rails.env.development? || Rails.env.test?


问:
Setting ByteArrayInputStream in post method using Jersey 2.25.1
I have been trying to write the following code using jersey 2.25.1 but I am not sure what to pass in the entity. Can someone help me figure this out because there is no entity and in jersey 2.25.1 the post method takes Entity into account which entity and the media type.

Existing code using jersey 1.13

```<code>WebResource resourceGetToken = client.createResource( ESignatureSpringUtil.getMessage( KeyConstants.ALSB_DOCUSIGN_ADDRESS )
                            + ESignatureSpringUtil.getMessage( KeyConstants.REST_GET_TOKEN_ADDRESS) );

                    ClientResponse tokenResponse = resourceGetToken
                        .header( KeyConstants.REST_URI_APPENDERS, tokenSb )
                        .header( DocusignRESTContants.CONTENT_TYPE, DocusignRESTContants.APPLICATION_XML )
                        .header( DocusignRESTContants.X_DOCUSIGN_AUTHENTICATION, getDocusignAuthHeader( cu ) )
                        .accept( MediaType.APPLICATION_XML )
                        .post( ClientResponse.class, new ByteArrayInputStream( tokenStream.toString().getBytes() ) );

                    if ( tokenResponse.getStatus() == 200 ) {
                        RetrieveTokenResponse tokenResp = (RetrieveTokenResponse) tokenResponse.getEntity(RetrieveTokenResponse.class);
</code>```

Jersey 2.25.1

```<code>WebTarget resourceGetToken = client.createResource( ESignatureSpringUtil.getMessage( KeyConstants.ALSB_DOCUSIGN_ADDRESS )
                            + ESignatureSpringUtil.getMessage( KeyConstants.REST_GET_TOKEN_ADDRESS) );

                    Invocation.Builder invcocationBuilder = resourceGetToken.request()
                            .header( KeyConstants.REST_URI_APPENDERS, tokenSb )
                            .header( DocusignRESTContants.CONTENT_TYPE, DocusignRESTContants.APPLICATION_XML )
                            .header( DocusignRESTContants.X_DOCUSIGN_AUTHENTICATION, getDocusignAuthHeader( cu ) )
                            .accept( MediaType.APPLICATION_XML );

                    Response tokenResponse = invcocationBuilder.post( Entity.entity(entity, mediaType));
</code>```

I need to get the byte stream and the overloaded post methods do not allow me to do it.

Thanks

答:
This is how I am doing it. </p>

```<code>Response response = builder.put( Entity.entity( new ByteArrayInputStream( jsonObj.toString().getBytes() ), MediaType.APPLICATION_XML ), Response.class );
</code>```

Body:
I have been trying to write the following code using jersey 2.25.1 but I am not sure what to pass in the entity. Can someone help me figure this out because there is no entity and in jersey 2.25.1 the post method takes Entity into account which entity and the media type.

Existing code using jersey 1.13

WebResource resourceGetToken = client.createResource( ESignatureSpringUtil.getMessage( KeyConstants.ALSB_DOCUSIGN_ADDRESS )
                            + ESignatureSpringUtil.getMessage( KeyConstants.REST_GET_TOKEN_ADDRESS) );

                    ClientResponse tokenResponse = resourceGetToken
                        .header( KeyConstants.REST_URI_APPENDERS, tokenSb )
                        .header( DocusignRESTContants.CONTENT_TYPE, DocusignRESTContants.APPLICATION_XML )
                        .header( DocusignRESTContants.X_DOCUSIGN_AUTHENTICATION, getDocusignAuthHeader( cu ) )
                        .accept( MediaType.APPLICATION_XML )
                        .post( ClientResponse.class, new ByteArrayInputStream( tokenStream.toString().getBytes() ) );

                    if ( tokenResponse.getStatus() == 200 ) {
                        RetrieveTokenResponse tokenResp = (RetrieveTokenResponse) tokenResponse.getEntity(RetrieveTokenResponse.class);

Jersey 2.25.1

WebTarget resourceGetToken = client.createResource( ESignatureSpringUtil.getMessage( KeyConstants.ALSB_DOCUSIGN_ADDRESS )
                            + ESignatureSpringUtil.getMessage( KeyConstants.REST_GET_TOKEN_ADDRESS) );

                    Invocation.Builder invcocationBuilder = resourceGetToken.request()
                            .header( KeyConstants.REST_URI_APPENDERS, tokenSb )
                            .header( DocusignRESTContants.CONTENT_TYPE, DocusignRESTContants.APPLICATION_XML )
                            .header( DocusignRESTContants.X_DOCUSIGN_AUTHENTICATION, getDocusignAuthHeader( cu ) )
                            .accept( MediaType.APPLICATION_XML );

                    Response tokenResponse = invcocationBuilder.post( Entity.entity(entity, mediaType));

I need to get the byte stream and the overloaded post methods do not allow me to do it.

Thanks

Body:
This is how I am doing it.

Response response = builder.put( Entity.entity( new ByteArrayInputStream( jsonObj.toString().getBytes() ), MediaType.APPLICATION_XML ), Response.class );


问:
Paypal sandbox pending payment
I want to use Paypal with Moodle to sell courses. Moodle comes with a IPN file so it's quite easy to do.

Problem comes when testing the payment process in the sandbox. Everything works fine from the user side (buying the course). Trouble comes from the seller side.

Connecting to the Paypal sandbox as a seller, I'm seeing my pending payments. I want to accept a pending payment to continue the process. That's when the problem happend. When clicking the accept button, Paypal tell me they have to verify my account and I need to add a bank account. And when I enter random numbers, Paypal just says "You cannot add a bank at this time".

So I can't accept the payment and I can't test the payment process.

答:
So now it's working. I asked Paypal support by email 2 days ago (support@paypal-techsupport.com). Today they just made my sandbox account as "verified". Sandbox transactions are now working.

As suggested, it works well on Stripe.

Title: Paypal sandbox pending payment


问:
Converting 3 seperate arrays of dictionaries into 1 struct array?
I am currently using 3 separate arrays to populate a sectioned UITableView and I'd like to use just a single array for filtering purposes but still maintain the sections within my table.

The data is fed by a single JSON string which I then iterate through to create a dictionary of a single 'Event' and then based on the value of 'Event Status', it is added to one of three arrays (open, closed and deferred). These arrays are then uses to populate each section of a UITableView.

```<code>let myDictionary: [String: String] = [
      "EventID" : item["EventID"] as! String,
      "EventTitle" : item["EventTitle"] as! String,
      "EventSummary" : item["EventSummary"] as! String,
      "EventStatus" : item["Status"] as! String
      ]

 if (item["Status"] as! String == "Open") {
     self.openEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "Closed") {
     self.closedEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "") {
     self.deferredEvents.append(myDictionary as AnyObject)
 }
</code>```

Then in cellForRowAt:

```<code>var tmpDict: [String: String] = ["":""]

if sectionHeaders[indexPath.section] == "Open" {
    tmpDict = openEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Closed" {
    tmpDict = closedEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Deferred" {
    tmpDict = deferredEvents[indexPath.row] as! [String : String]
}
</code>```

Problem is that in order to allow filtering of this data, I'd have to run the filter against three different arrays which means three different 'filtered data' arrays. Which is far from ideal.

What I'd like to achieve is to have a single array of structured data (as opposed to dictionaries) that the user can filter through and the result returned to a single 'filtered data' array. I am doing this elsewhere with good effect, however, that is for a single list, not sectioned.

I have a struct setup and adding items to it as follows:

```<code>let data = EventItem(EventID: item["EventID"] as! String, EventTitle: item["EventTitle"] as! String, EventSummary: item["EventSummary"] as! String, EventStatus: item["Status"] as! String)

self.eventList.append(data)
</code>```

and filtering using:

```<code>filteredData = eventList.filter() {
   ($0.EventTitle.lowercased() as NSString).contains(searchText.lowercased()) || ($0.EventSummary.lowercased() as NSString).contains(searchText.lowercased())
}

eventsTable.reloadData()
</code>```

Is it possible to split this single array over different sections in a TableView? if so, how?

答:
You can just use an extension of the approach you already have for filteredData

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    switch section {
    case 0:
        let sortedList = newItems.sorted { $0.eventStatus == "Open"}
        return sortedList.count
    case 1:
        let sortedList = newItems.sorted { $0.eventStatus == "Closed"}
        return sortedList.count
    case 2:
        let sortedList = newItems.sorted { $0.eventStatus == ""}
        return sortedList.count
    default:
        return 0 // shouldn't happen
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    var tmpDict: [String: String] = ["":""]

    switch section {
    case 0:
        tmpDict = newItems.sorted { $0.eventStatus == "Open"}
    case 1:
        tmpDict = newItems.sorted { $0.eventStatus == "Closed"}
    case 2:
        tmpDict = newItems.sorted { $0.eventStatus == ""}
    default:
        return 0 // shouldn't happen

    // setup cell
}
</code>```

Body:
I am currently using 3 separate arrays to populate a sectioned UITableView and I'd like to use just a single array for filtering purposes but still maintain the sections within my table.

The data is fed by a single JSON string which I then iterate through to create a dictionary of a single 'Event' and then based on the value of 'Event Status', it is added to one of three arrays (open, closed and deferred). These arrays are then uses to populate each section of a UITableView.

let myDictionary: [String: String] = [
      "EventID" : item["EventID"] as! String,
      "EventTitle" : item["EventTitle"] as! String,
      "EventSummary" : item["EventSummary"] as! String,
      "EventStatus" : item["Status"] as! String
      ]

 if (item["Status"] as! String == "Open") {
     self.openEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "Closed") {
     self.closedEvents.append(myDictionary as AnyObject)
 }
 if (item["Status"] as! String == "") {
     self.deferredEvents.append(myDictionary as AnyObject)
 }

Then in cellForRowAt:

var tmpDict: [String: String] = ["":""]

if sectionHeaders[indexPath.section] == "Open" {
    tmpDict = openEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Closed" {
    tmpDict = closedEvents[indexPath.row] as! [String : String]
}

if sectionHeaders[indexPath.section] == "Deferred" {
    tmpDict = deferredEvents[indexPath.row] as! [String : String]
}

Problem is that in order to allow filtering of this data, I'd have to run the filter against three different arrays which means three different 'filtered data' arrays. Which is far from ideal.

What I'd like to achieve is to have a single array of structured data (as opposed to dictionaries) that the user can filter through and the result returned to a single 'filtered data' array. I am doing this elsewhere with good effect, however, that is for a single list, not sectioned.

I have a struct setup and adding items to it as follows:

let data = EventItem(EventID: item["EventID"] as! String, EventTitle: item["EventTitle"] as! String, EventSummary: item["EventSummary"] as! String, EventStatus: item["Status"] as! String)

self.eventList.append(data)

and filtering using:

filteredData = eventList.filter() {
   ($0.EventTitle.lowercased() as NSString).contains(searchText.lowercased()) || ($0.EventSummary.lowercased() as NSString).contains(searchText.lowercased())
}

eventsTable.reloadData()

Is it possible to split this single array over different sections in a TableView? if so, how?

Body:
You can just use an extension of the approach you already have for filteredData

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    switch section {
    case 0:
        let sortedList = newItems.sorted { $0.eventStatus == "Open"}
        return sortedList.count
    case 1:
        let sortedList = newItems.sorted { $0.eventStatus == "Closed"}
        return sortedList.count
    case 2:
        let sortedList = newItems.sorted { $0.eventStatus == ""}
        return sortedList.count
    default:
        return 0 // shouldn't happen
    }
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    var tmpDict: [String: String] = ["":""]

    switch section {
    case 0:
        tmpDict = newItems.sorted { $0.eventStatus == "Open"}
    case 1:
        tmpDict = newItems.sorted { $0.eventStatus == "Closed"}
    case 2:
        tmpDict = newItems.sorted { $0.eventStatus == ""}
    default:
        return 0 // shouldn't happen

    // setup cell
}


问:
TCL Thread: Tracking that a child Tcl Thread is still running
I am facing a problem with determining whether a Tcl thread is still running or not.  I have code that looks like this:

```<code>package require Thread
proc p1 {} {
    set tid [thread::create {
        #Child Thread
        proc executeCommand {} {
            #Run several command line commands
            return 1
        }
        thread::wait
    }]
    set currentProcessID [twapi::get_current_process_id]
    set var ::p1results($tid)
    set $var ""

    #Get all threads before ::thread::send
    set beforeThreads [twapi::get_process_thread_ids $currentProcessID]

    ::thread::send -async $tid [list executeCommand {}] $var

    #Get all threads after ::thread::send
    set afterThreads [twapi::get_process_thread_ids $currentProcessID]

    #set processThreadId to be the difference between before and after twapi calls
    set processThreadId {}
    foreach threadId $afterThreads {
        if {[lsearch -exact $beforeThreads $threadId] == -1} {
            set processThreadId $threadId
        }
    }

    while {[lsearch -exact [twapi::get_process_thread_ids $currentProcessID] $processThreadId] > -1} {
        #Notify a database that child thread is still running
        after 3000
    }

    vwait $var
    set result [set $var]
    unset $var
    ::thread::release $tid
    return $result
}

p1
</code>```

As you can see, I am currently tracking the child thread, that I started with ::thread::send, with the TCL twapi package.  I do not want to block the parent thread with 'vwait' or else I will not be able to notify the DB that the child thread is still running.  This has proven to be unreliable, as occasionally the thread id that I have stored 'processThreadId' will exit before my thread 'proc executeCommand {}' finishes.

So my question is this - is there a reliable way for the parent thread (main thread) to track if a child thread is still running, without blocking the parent thread with 'vwait'?

答:
I solved this problem using the thread::mutex locks, which are much more reliable than the twapi package I was using before.

Essentially, I create a thread::mutex and grab the lock in the parent thread.  I then thread::send to my worker thread the mutex handle.  The parent thread then loops, attempting to re-lock the mutex and catching/ignoring the "locking the same exclusive mutex twice from the same thread" error message.  The parent thread will break out of the while loop when "thread::mutex lock" does not throw an error.

The worker thread goes through its list of command and calls "thread::mutex unlock" just before the return statement.  I also needed to wrap the "executeCommand" in a catch statement so I could unlock the mutex in case the worker thread gets an unexpected error.

So the mutex being locked represents the worker thread running, once it becomes unlocked it has no more commands to run.

```<code>package require Thread
proc p1 {} {
    set mutexHand [::thread::mutex create]
    set tid [thread::create {
        proc wrapCommad {mutHand} {
            if {[catch {set data [executeCommand]} err]} {
                thread::mutex unlock $mutHand
                return -code error $err
            }
            thread::mutex unlock $mutHand
            return $data
        }
        proc executeCommand {} {
            #Run several command line commands
            return 1
        }
        thread::wait
    }]
    set var ::p1results($tid)
    set $var ""
    thread::mutex lock $mutexHand
    ::thread::send -async $tid [list wrapCommand $mutexHand] $var

    while {1} {
        if {[catch {thread::mutex lock $mutexHand} err] } {
            puts "WORKER STILL RUNNING"
        } else {
            puts "WORKER NOT RUNNING"
            break;
        }
        after 3000
    }

    vwait $var
    thread::mutex unlock $mutexHand
    thread::mutex destroy $mutexHand
    set result [set $var]
    unset $var
    ::thread::release $tid
    return $result
}

p1
</code>```

Body:
I am facing a problem with determining whether a Tcl thread is still running or not.  I have code that looks like this:

package require Thread
proc p1 {} {
    set tid [thread::create {
        #Child Thread
        proc executeCommand {} {
            #Run several command line commands
            return 1
        }
        thread::wait
    }]
    set currentProcessID [twapi::get_current_process_id]
    set var ::p1results($tid)
    set $var ""

    #Get all threads before ::thread::send
    set beforeThreads [twapi::get_process_thread_ids $currentProcessID]

    ::thread::send -async $tid [list executeCommand {}] $var

    #Get all threads after ::thread::send
    set afterThreads [twapi::get_process_thread_ids $currentProcessID]

    #set processThreadId to be the difference between before and after twapi calls
    set processThreadId {}
    foreach threadId $afterThreads {
        if {[lsearch -exact $beforeThreads $threadId] == -1} {
            set processThreadId $threadId
        }
    }

    while {[lsearch -exact [twapi::get_process_thread_ids $currentProcessID] $processThreadId] > -1} {
        #Notify a database that child thread is still running
        after 3000
    }

    vwait $var
    set result [set $var]
    unset $var
    ::thread::release $tid
    return $result
}

p1

As you can see, I am currently tracking the child thread, that I started with ::thread::send, with the TCL twapi package.  I do not want to block the parent thread with 'vwait' or else I will not be able to notify the DB that the child thread is still running.  This has proven to be unreliable, as occasionally the thread id that I have stored 'processThreadId' will exit before my thread 'proc executeCommand {}' finishes.

So my question is this - is there a reliable way for the parent thread (main thread) to track if a child thread is still running, without blocking the parent thread with 'vwait'?

Body:
I solved this problem using the thread::mutex locks, which are much more reliable than the twapi package I was using before.

Essentially, I create a thread::mutex and grab the lock in the parent thread.  I then thread::send to my worker thread the mutex handle.  The parent thread then loops, attempting to re-lock the mutex and catching/ignoring the "locking the same exclusive mutex twice from the same thread" error message.  The parent thread will break out of the while loop when "thread::mutex lock" does not throw an error.

The worker thread goes through its list of command and calls "thread::mutex unlock" just before the return statement.  I also needed to wrap the "executeCommand" in a catch statement so I could unlock the mutex in case the worker thread gets an unexpected error.

So the mutex being locked represents the worker thread running, once it becomes unlocked it has no more commands to run.

package require Thread
proc p1 {} {
    set mutexHand [::thread::mutex create]
    set tid [thread::create {
        proc wrapCommad {mutHand} {
            if {[catch {set data [executeCommand]} err]} {
                thread::mutex unlock $mutHand
                return -code error $err
            }
            thread::mutex unlock $mutHand
            return $data
        }
        proc executeCommand {} {
            #Run several command line commands
            return 1
        }
        thread::wait
    }]
    set var ::p1results($tid)
    set $var ""
    thread::mutex lock $mutexHand
    ::thread::send -async $tid [list wrapCommand $mutexHand] $var

    while {1} {
        if {[catch {thread::mutex lock $mutexHand} err] } {
            puts "WORKER STILL RUNNING"
        } else {
            puts "WORKER NOT RUNNING"
            break;
        }
        after 3000
    }

    vwait $var
    thread::mutex unlock $mutexHand
    thread::mutex destroy $mutexHand
    set result [set $var]
    unset $var
    ::thread::release $tid
    return $result
}

p1


问:
Client side Data Annotation validation on a button click using Jquery
I have a model which has Required attributes in it. Is it possible to do data validation on a button click which is not of type submit. I did refer to this article and this one but it did not solve the issue.

Here's my model code.

```<code> [Required]
 [Display(Name = "Number of beds")]
 public int Beds { get; set; }
 [Required]
 [Display(Name = "Number of Inpatient Beds")]
 public int InpatientBeds { get; set; }
</code>```

My View

```<code>@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
{

<div class="divPanel">
    <div class="row">
        <div class="col-md-3">
                @Html.LabelFor(m => m.Beds)
                @Html.TextBoxFor(m => m.Beds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.Beds)

        </div>
        <div class="col-md-3">

                @Html.LabelFor(m => m.InpatientBeds)
                @Html.TextBoxFor(m => m.InpatientBeds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.InpatientBeds)
        </div>
<div class="col-md-3">
            <button type=button  class="btn btn-primary" id="btnCalculateScore" > Calculate Score</button>
        </div>
 </div>
<div class="col-md-3">
        <button type="submit" class="btn btn-primary" id="btnSaveChanges" data-toggle="modal"><i class="fa fa-share-square-o"></i> Update Status</button>
    </div>
</div>
}
</code>```

And my script

```<code>$('#btnCalculateScore').on('click', function (evt) {

evt.preventDefault();

if ($('#form1').valid()) {
    //Do Something.
}
}
</code>```

The validations do not work and the control enters the if loop even though the fields are empty? Is there something I am missing? Also does this approach also give out the validation messages which normally happen on a submit button event?

EDIT :

I added a normal Update Status button with type submit and the validations work there fine.

I added the id to my form to ensure it does not matter if the View contains another forms.

答:
I had the same issue and this seemed to resolve it for me.

```<code>@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
</code>```

On seeing the page source, this code does not attach the id Form1 to your form. Hence your validation will not happen as the form with id form1 is not found.

Instead,assuming your operation is a post and you are saving the data in say Action Method Save and controller Bed you can edit the form to

```<code>@using (Html.BeginForm("Save", "Bed", FormMethod.Post, new { id = "form1",@class = "form-horizontal"}))
</code>```

This will attach the id parameter to your form(you can check using ViewPageSource) and it should work. There might be a better solution to this, but this worked properly for me without issues.

Body:
I have a model which has Required attributes in it. Is it possible to do data validation on a button click which is not of type submit. I did refer to this article and this one but it did not solve the issue.

Here's my model code.

 [Required]
 [Display(Name = "Number of beds")]
 public int Beds { get; set; }
 [Required]
 [Display(Name = "Number of Inpatient Beds")]
 public int InpatientBeds { get; set; }

My View

@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))
{

                @Html.LabelFor(m => m.Beds)
                @Html.TextBoxFor(m => m.Beds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.Beds)

                @Html.LabelFor(m => m.InpatientBeds)
                @Html.TextBoxFor(m => m.InpatientBeds, new { @class = "form-control", @type = "number"})
                @Html.ValidationMessageFor(m => m.InpatientBeds)

            <button type=button  class="btn btn-primary" id="btnCalculateScore" > Calculate Score</button>

        <button type="submit" class="btn btn-primary" id="btnSaveChanges" data-toggle="modal"> Update Status</button>

}

And my script

$('#btnCalculateScore').on('click', function (evt) {

evt.preventDefault();

if ($('#form1').valid()) {
    //Do Something.
}
}

The validations do not work and the control enters the if loop even though the fields are empty? Is there something I am missing? Also does this approach also give out the validation messages which normally happen on a submit button event?

EDIT :

I added a normal Update Status button with type submit and the validations work there fine.

I added the id to my form to ensure it does not matter if the View contains another forms.

Body:
I had the same issue and this seemed to resolve it for me.

@using (Html.BeginForm(new {id = "form1", @class = "form-horizontal" }))

On seeing the page source, this code does not attach the id Form1 to your form. Hence your validation will not happen as the form with id form1 is not found.

Instead,assuming your operation is a post and you are saving the data in say Action Method Save and controller Bed you can edit the form to

@using (Html.BeginForm("Save", "Bed", FormMethod.Post, new { id = "form1",@class = "form-horizontal"}))

This will attach the id parameter to your form(you can check using ViewPageSource) and it should work. There might be a better solution to this, but this worked properly for me without issues.


问:
How to work on this particular situation in django admin?
```<code>class Foo(models.Model):
    bar_protected = models.BooleanField(default=False)
    bar = models.CharField(max_length=50
</code>```

Here I am customizing django admin. Now I have two field in the model. By Default I want that 'bar' remains disabled. (Not Hide). And bar_protected unchecked. When some one checked bar_protected , bar enabled.

```<code>    Django have disabled facilities But when I do, It hides the bar Field.
</code>```

Thanks in advance.

答: You should either use editable = False in the model for that field or put it in readonly_fields while registering the model in the admin.py file. This should work.

Body:
class Foo(models.Model):
    bar_protected = models.BooleanField(default=False)
    bar = models.CharField(max_length=50

Here I am customizing django admin. Now I have two field in the model. By Default I want that 'bar' remains disabled. (Not Hide). And bar_protected unchecked. When some one checked bar_protected , bar enabled.

    Django have disabled facilities But when I do, It hides the bar Field.

Thanks in advance.


问:
What's the default value of char?
```<code>char c = '\u0000';
</code>```

When I print c, it shows 'a' in the command line window.

So what's the default value of a char type field?

Someone said '\u0000' means null in Unicode; is that right?

答:
The default value of char is null which is '\u0000' as per Unicode chart. Let us see how it works while printing out.

```<code>public class Test_Class {
     char c;
     void printAll() {
       System.out.println("c = " + c);
    }
    public static void main(String[] args) {
    Test_Class f = new Test_Class();
    f.printAll();
    } }
</code>```

Note: The output is blank.

ContentLicense: CC BY-SA 4.0

Title: What's the default value of char?

Body:
char c = '\u0000';

When I print c, it shows 'a' in the command line window.

So what's the default value of a char type field?

Someone said '\u0000' means null in Unicode; is that right?

Body:
The default value of char is null which is '\u0000' as per Unicode chart. Let us see how it works while printing out.

public class Test_Class {
     char c;
     void printAll() {
       System.out.println("c = " + c);
    }
    public static void main(String[] args) {
    Test_Class f = new Test_Class();
    f.printAll();
    } }

Note: The output is blank.


问:
Rendering react component in html page
So I just got comfortable with ReactJS within a few and want to actually start creating things with it. Before starting to really get into coding it, I made a basic test to see if React is doing what it is supposed to, and it's not. It's not rendering at all, and I don't see any Syntax errors in the code.

```

答:
Follow these steps it will work:

1. Remove these lines:

```<code>var React = require('react');
var ReactDOM = require('react-dom');
</code>```

2. include the script after the div where you defined the id, like this:

```<code><body>
   <div id="app"></div>
   <script src="app.js"></script>
</body>
</code>```

3. Include the reference of babel, it required to transpile the JSX code into plain js code, include this reference in header:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
</code>```

4. Define the type of the script, like this:

```<code><script src="app.js" type='text/jsx'></script>
</code>```

Check the working example:

<!DOCTYPE html>

      <meta charset = "UTF-8">
      <title>React App</title>

```

Title: Rendering react component in html page

Body:
Follow these steps it will work:

1. Remove these lines:

var React = require('react');
var ReactDOM = require('react-dom');

2. include the script after the div where you defined the id, like this:

<body>
   <div id="app"></div>
   <script src="app.js"></script>
</body>

3. Include the reference of babel, it required to transpile the JSX code into plain js code, include this reference in header:

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>

4. Define the type of the script, like this:

<script src="app.js" type='text/jsx'></script>

Check the working example:

<!DOCTYPE html>
<html lang = "en">
   <head>
      <meta charset = "UTF-8">
      <title>React App</title>
       <script src="https://unpkg.com/react@15/dist/react.min.js"></script>
       <script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
       <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
       <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  </head>
  <body>
      <div id="app"></div>
      <script type='text/jsx'>
         var Box = React.createClass({
             render: function () {
                 return (
                    <div>
                       <h1>React</h1>
                       <h1>React2</h1>
                    </div>
                 );
             }
         });

         ReactDOM.render(<Box />, document.getElementById('app'));
      </script>
   </body>
</html>


问:
Overflow hidden not working for "vertical aligned bottom" - divs in an absolute positioned outer div
I have a problem regarding my divs, which are vertical aligned to the bottom of a div.

My goal is to create a "log window", where I can display messages from bottom to the top. If there is not enough space, the top messages should fade away (overflow hidden).

Problems:

First, the height is not considered, if I put more divs inside, the container will grow and overtop 100px, as you can see in the example on jsfiddle (currently 116px).
Second, If I force it to 100px, it will cut the bottom div's instead of the top ones. I want to see the newest messages on the bottom (7, 6, 5, ...),

The outer div with position absolute needs to stay.

I've created a jsfiddle for better understanding:

https://jsfiddle.net/vbdo9xun/4/

#notifications {
  position: absolute;
  left: 4px;
  top: 4px;
  z-index: 100000000;
  overflow: hidden;
}

#notifications .content {
  width: 350px;
  height: 100px;
  padding: 2px 4px 2px 4px;
  background-color: #321d12;
  box-sizing: border-box;
  display: table-cell;
  vertical-align: bottom;
}

#notifications .content div {
  font-size: 10px;
  color: #efb718;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="notifications">
  <div class="content">
    <div>1. Lorem ipsum dolor sit amet, consetetur!</div>
    <div>2. tempor invidunt ut labore et dolore magna!</div>
    <div>3. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy invidunt ut!</div>
    <div>4. sit amet, consetetur!</div>
    <div>5. invidunt ut labore et dolore magna!</div>
    <div>6. Lorem tempor invidunt ut labore et dolore!</div>
    <div>7. Amet Lorem ipsum dolor sit amet, consetetur!</div>
  </div>
</div></code>```

答:
You could like this, using position: absolute on the content as well, starting out from the bottom

#notifications {
  position: absolute;
  width: 100%;
  top: 1px;
  top: 4px;
  height: 100px;          /* set height here instead */
  overflow: hidden;
}

#notifications .content {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 350px;
  padding: 2px 4px 2px 4px;
  background-color: #404040;
  color: white;
  font-family: Arial;
  box-sizing: border-box;
}

#notifications .content div {
  font-size: 12px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="notifications">
  <div class="content">
    <div>1. Lorem ipsum dolor sit amet, consetetur!</div>
    <div>2. tempor invidunt ut labore et dolore magna!</div>
    <div>3. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy invidunt ut!</div>
    <div>4. sit amet, consetetur!</div>
    <div>5. invidunt ut labore et dolore magna!</div>
    <div>6. Lorem tempor invidunt ut labore et dolore!</div>
    <div>7. Amet Lorem ipsum dolor sit amet, consetetur!</div>
  </div>
</div></code>```

Body:
I have a problem regarding my divs, which are vertical aligned to the bottom of a div.

My goal is to create a "log window", where I can display messages from bottom to the top. If there is not enough space, the top messages should fade away (overflow hidden).

Problems:

First, the height is not considered, if I put more divs inside, the container will grow and overtop 100px, as you can see in the example on jsfiddle (currently 116px).
Second, If I force it to 100px, it will cut the bottom div's instead of the top ones. I want to see the newest messages on the bottom (7, 6, 5, ...),

The outer div with position absolute needs to stay.

I've created a jsfiddle for better understanding:

https://jsfiddle.net/vbdo9xun/4/

#notifications {
  position: absolute;
  left: 4px;
  top: 4px;
  z-index: 100000000;
  overflow: hidden;
}

#notifications .content {
  width: 350px;
  height: 100px;
  padding: 2px 4px 2px 4px;
  background-color: #321d12;
  box-sizing: border-box;
  display: table-cell;
  vertical-align: bottom;
}

#notifications .content div {
  font-size: 10px;
  color: #efb718;
}

1. Lorem ipsum dolor sit amet, consetetur!

2. tempor invidunt ut labore et dolore magna!

3. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy invidunt ut!

4. sit amet, consetetur!

5. invidunt ut labore et dolore magna!

6. Lorem tempor invidunt ut labore et dolore!

7. Amet Lorem ipsum dolor sit amet, consetetur!

Body:
You could like this, using position: absolute on the content as well, starting out from the bottom

#notifications {
  position: absolute;
  width: 100%;
  top: 1px;
  top: 4px;
  height: 100px;          /* set height here instead */
  overflow: hidden;
}

#notifications .content {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 350px;
  padding: 2px 4px 2px 4px;
  background-color: #404040;
  color: white;
  font-family: Arial;
  box-sizing: border-box;
}

#notifications .content div {
  font-size: 12px;
}

<div id="notifications">
  <div class="content">
    <div>1. Lorem ipsum dolor sit amet, consetetur!</div>
    <div>2. tempor invidunt ut labore et dolore magna!</div>
    <div>3. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy invidunt ut!</div>
    <div>4. sit amet, consetetur!</div>
    <div>5. invidunt ut labore et dolore magna!</div>
    <div>6. Lorem tempor invidunt ut labore et dolore!</div>
    <div>7. Amet Lorem ipsum dolor sit amet, consetetur!</div>
  </div>
</div>


问:
How to capture packets with netfilter?
I am using libpcap to capture GRE packets and forward now, I think the efficiency is not very good.

so I decide to do forwarding with netfilter, but I am new for this. Could someone gives me one

simple example to capture IP or GRE packets with netfilter? thanks!

答:
It's not clear what you're trying to accomplish.  Are you trying to capture the packets for analysis (like wireshark or tcpdump), or forward traffic through a GRE tunnel?

If you're trying to capture traffic for analysis, using netfilter doesn't make much sense.  It's probably possible, using something like the QUEUE target to pass packets to userspace, but I doubt you'd get better performance than using libpcap with suitable BPF rules.

If you're trying to forward traffic through a GRE tunnel, the normal way to do that is to set up a gre tunnel interface; do man ip and look at the "tunnel" section.  The tunnel interface (e.g. gre0)  is a normal network interface that the system's routing table can send packets to.

Title: How to capture packets with netfilter?


问:
Test Average and Grade - Python
I am trying to create a python program which when you enter 5 test scores it displays the corresponding letter grade and then gets the average of those five grade and displays the letter grade for the average.

Here's my program:

```<code>#Test Average and Grade

#Enter 5 test scores
test1 = int(input('Enter score 1: '))
test2 = int(input('Enter score 2: '))
test3 = int(input('Enter score 3: '))
test4 = int(input('Enter score 4: '))
test5 = int(input('Enter score 5: '))

total =(test1 + test2 + test3 + test4 + test5)

#Calculate average
def calc_average(total):
    return total / 5

#Grading scale
def determine_score(grade):
    if 90 <= grade <= 100:
        return 'A'
    elif 80 <= grade <= 89:
        return 'B'
    elif 70 <= grade <= 79:
        return 'C'
    elif 60 <= grade <= 69:
        return 'D'
    else:
        return 'F'

grade = total
avg = calc_average(total)
abc_grade = determine_score(grade)

print("That's a(n): " + str(abc_grade))
print('Average grade is: ' + str(avg))
</code>```

The problem I'm having is that I can't get the grade to display after each score that is entered and I am having trouble trying to figure out how to get the letter grade to display along with the average in the last statement.  Any help would be greatly appreciated.

Changed program to this:

```<code> #Test Average and Grade

#Enter 5 test scores
test1 = int(input('Enter score 1: '))
test2 = int(input('Enter score 2: '))
test3 = int(input('Enter score 3: '))
test4 = int(input('Enter score 4: '))
test5 = int(input('Enter score 5: '))

total =(test1 + test2 + test3 + test4 + test5)

    #Calculate average
    def calc_average(total):
        return total / 5

    #Grading scale
    def determine_score(grade):
        if 90 <= grade <= 100:
            return 'A'
        elif 80 <= grade <= 89:
            return 'B'
        elif 70 <= grade <= 79:
            return 'C'
        elif 60 <= grade <= 69:
            return 'D'
        else:
            return 'F'

    grade = total
    avg = calc_average(total)
    abc_grade = determine_score(grade)

    print("Score 1:", determine_score(test1))
    print("Score 2:", determine_score(test2))
    print("Score 3:", determine_score(test3))
    print("Score 4:", determine_score(test4))
    print("Score 5:", determine_score(test5))
    print("The average grade is: %s which is a(n): %s " % (str(avg), abc_grade))
</code>```

Results look this this:

Enter score 1: 75
Enter score 2: 80
Enter score 3: 33
Enter score 4: 90
Enter score 5: 52
Score 1: C
Score 2: B
Score 3: F
Score 4: A
Score 5: F
The average grade is: 66.0 which is a(n): F

Trying to get the results like this:
Enter score 1: 75
That's a(n): C
Enter score 2: 80
That's a(n): B
Enter score 3: 33
That's a(n): C
Enter score 4: 90
That's a(n): A
Enter score 5: 52
That's a(n): F
The average grade is: 66.0 which is a(n): F

答:
```<code>def main():
    score1 = 0.0
    score2 = 0.0
    score3 = 0.0
    score4 = 0.0
    score5 = 0.0
    avg = 0.0

    score1 = getScore1()
    score2 = getScore2()
    score3 = getScore3()
    score4 = getScore4()
    score5 = getScore5()

    findAvg = calc_average(score1, score2, score3, score4, score5)
    letterGrade = determine_grade(findAvg)

    print('Score\t\t Numeric Grade   Letter Grade')
    print('------------------------------------------------')
    print('Score 1:\t', score1, '\t\t', determine_grade(score1))
    print('Score 2:\t', score2, '\t\t', determine_grade(score2))
    print('Score 3:\t', score3, '\t\t', determine_grade(score3))
    print('Score 4:\t', score4, '\t\t', determine_grade(score4))
    print('Score 5:\t', score5, '\t\t', determine_grade(score5))

    print('Your final average is: ', findAvg, ',', 'This is your letter   grade: ', letterGrade)

def getScore1():
    score1 = float(input('Enter score 1: '))
    return score1
def getScore2():
    score2 = float(input('Enter score 2: '))
    return score2
def getScore3():
    score3 = float(input('Enter score 3: '))
    return score3
def getScore4():
    score4 = float(input('Enter score 4: '))
    return score4
def getScore5():
    score5 = float(input('Enter score 5: '))
    return score5

def calc_average(score1, score2, score3, score4, score5):
    total = score1 + score2 + score3 + score4 + score5
    avg = total / 5
    return avg

def determine_grade(findAvg):
    if findAvg >= 90 and findAvg <= 100:
        grade = 'A'
        return grade
    elif findAvg >= 80 and findAvg <= 89:
        grade = 'B'
        return grade
    elif findAvg >= 70 and findAvg <= 79:
        grade = 'C'
        return grade
    elif findAvg >= 60 and findAvg <= 69:
        grade = 'D'
        return grade
    else:
        grade = 'F'
        return grade
main()
</code>```

Title: Test Average and Grade - Python

Body:
I am trying to create a python program which when you enter 5 test scores it displays the corresponding letter grade and then gets the average of those five grade and displays the letter grade for the average.

Here's my program:

#Test Average and Grade

#Enter 5 test scores
test1 = int(input('Enter score 1: '))
test2 = int(input('Enter score 2: '))
test3 = int(input('Enter score 3: '))
test4 = int(input('Enter score 4: '))
test5 = int(input('Enter score 5: '))

total =(test1 + test2 + test3 + test4 + test5)

#Calculate average
def calc_average(total):
    return total / 5

#Grading scale
def determine_score(grade):
    if 90 <= grade <= 100:
        return 'A'
    elif 80 <= grade <= 89:
        return 'B'
    elif 70 <= grade <= 79:
        return 'C'
    elif 60 <= grade <= 69:
        return 'D'
    else:
        return 'F'

grade = total
avg = calc_average(total)
abc_grade = determine_score(grade)

print("That's a(n): " + str(abc_grade))
print('Average grade is: ' + str(avg))

The problem I'm having is that I can't get the grade to display after each score that is entered and I am having trouble trying to figure out how to get the letter grade to display along with the average in the last statement.  Any help would be greatly appreciated.

Changed program to this:

 #Test Average and Grade

#Enter 5 test scores
test1 = int(input('Enter score 1: '))
test2 = int(input('Enter score 2: '))
test3 = int(input('Enter score 3: '))
test4 = int(input('Enter score 4: '))
test5 = int(input('Enter score 5: '))

total =(test1 + test2 + test3 + test4 + test5)

    #Calculate average
    def calc_average(total):
        return total / 5

    #Grading scale
    def determine_score(grade):
        if 90 <= grade <= 100:
            return 'A'
        elif 80 <= grade <= 89:
            return 'B'
        elif 70 <= grade <= 79:
            return 'C'
        elif 60 <= grade <= 69:
            return 'D'
        else:
            return 'F'

    grade = total
    avg = calc_average(total)
    abc_grade = determine_score(grade)

    print("Score 1:", determine_score(test1))
    print("Score 2:", determine_score(test2))
    print("Score 3:", determine_score(test3))
    print("Score 4:", determine_score(test4))
    print("Score 5:", determine_score(test5))
    print("The average grade is: %s which is a(n): %s " % (str(avg), abc_grade))

Results look this this:

Enter score 1: 75
Enter score 2: 80
Enter score 3: 33
Enter score 4: 90
Enter score 5: 52
Score 1: C
Score 2: B
Score 3: F
Score 4: A
Score 5: F
The average grade is: 66.0 which is a(n): F

Trying to get the results like this:
Enter score 1: 75
That's a(n): C
Enter score 2: 80
That's a(n): B
Enter score 3: 33
That's a(n): C
Enter score 4: 90
That's a(n): A
Enter score 5: 52
That's a(n): F
The average grade is: 66.0 which is a(n): F


问:
Cannot save today's date in mySQL column
This is a simple solution, but I cannot get it to work even after reading many similar posts on the topic.

I am able to define a php variable to hold the current date because I can echo it properly:

```<code>$_date_today = date('Y-d-m');
echo $_date_today;

2017-31-03
</code>```

But when I try to use that php variable to insert the date value into mySQL table, the value inserted is 0000-00-00. My date_order column in the table is defined as DATE.

答: While mySQL always stores the date in the database using the same format and I don't believe it can be changed, you can format the date however you want when retrieving it using the many mySQL functions available... see the following link: mySQL date manimpulation functions</p>

Body:
This is a simple solution, but I cannot get it to work even after reading many similar posts on the topic.

I am able to define a php variable to hold the current date because I can echo it properly:

$_date_today = date('Y-d-m');
echo $_date_today;

2017-31-03

But when I try to use that php variable to insert the date value into mySQL table, the value inserted is 0000-00-00. My date_order column in the table is defined as DATE.


问:
Ionic Push Notification Custom Sound Not Playing in Android
I'm having trouble getting Android to play a custom mp3 when I send it a Notification and my app is not running. I'm using Ionic v1 w/ cordovaPushV5.

I know the message is being received correctly and it's being shown in the Notifications area of my physical device.  I just don't get a sound (or any error in the log area.)

I think the problem may be that I don't know exactly where to put the sound file.  It goes in the res/raw folder, I believe.  However, where is that in the Ionic directory structure?

Anything else I should be checking?

答:
Well, I figured it out.  It's not immediately obvious, so hopefully this will help someone else.

After you generate your Android platform (With ionic platform add android), you need to manually create a folder within in called:

res/raw

So, the entire path will be:

/platforms/android/res/raw

Drop your custom notification sound files in there.  Mine was called "sound.mp3"

Now, when you send your notification from your server, be sure the message does not include the .mp3 extension.  So, my message looks like this:

{"count":"2","message":"This is a test","additionalData":{"google.message_id":"0:1490981070460603%bd04720bf9fd7ecd","foreground":true,"coldstart":false},"sound":"sound"}

Note the second "sound" is the filename without the extension.

Pretty easy, but a few little gotcha's.


问:
How to edit the size of the submit button on a form?
Hi I don't want an image for my submit button so I have gone with the default submit button but I want to edit its width and height. How do I do that?

```<code><input type="submit" id="search" value="Search"  />
</code>```

Thanks!

James

答:
Just add style="width:auto"

<input type="submit" id="search" value="Search" style="width:auto" />

This worked for me in IE, Firefox and Chrome.

Body:
Hi I don't want an image for my submit button so I have gone with the default submit button but I want to edit its width and height. How do I do that?

<input type="submit" id="search" value="Search"  />

Thanks!

James


问:
What is the right configuration for Java 8 Stream
I have the following code (just an example that i wrote for this question) which simply calculates sum of a range
I implemented it in three ways:

Serial

Parallel Stream

With ForkJoinPool

Surprisingly the Serial method was the fastest one. In fact it takes %10 of the time of the other two.

What is the right configurations for Java Stream in order to make it faster?
What wrong i am doing ?

```<code>package ned.main;

import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;

public class TestParallelStream {

    static private void testParallelStream() {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1000000");

        ForkJoinPool forkJoinPool = new ForkJoinPool(10000);

        Date start = new Date();

        long sum1 = 0;
        for (int i = 0; i < 1_000_000; ++i) {
            sum1 += i * 10;
        }

        Date start1 = new Date();

        long sum2 = IntStream.range(1, 1_000_000)
                        .parallel()
                        .map(x -> x * 10)
                        .sum();

        Date start2 = new Date();

        try {
            long sum3 = forkJoinPool.submit(() ->
                IntStream
                    .range(1, 1_000_000)
                    .parallel()
                    .map(x -> x * 10)
                    .sum())
                        .get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        long serial = start1.getTime() - start.getTime();
        long parallelstream = start2.getTime() - start1.getTime();
        long withfork = start2.getTime() - start1.getTime();

        System.out.println(serial + "," + parallelstream + "," + withfork);

    }

    public static void main(String[] args) {
        testParallelStream();
    }
}
</code>```

Thanks

答:
By my personal experiences, serial stream is the best choice for 99% task, comparing parallel stream.
Here is article about When to use parallel streams from Doug Lea. Basically, considering to use parallel stream when and only when you meet performance issue. There are some hints:

Make db/network or other IO calls in steps of the stream

CPU-heavy calculation (e.g. sum more than 10K ints. Adding tens, or hundreds of ints is not a heavy calculation).

Personally, I think parallel stream is over emphasized for daily coding.

Body:
I have the following code (just an example that i wrote for this question) which simply calculates sum of a range
I implemented it in three ways:

Serial

Parallel Stream

With ForkJoinPool

Surprisingly the Serial method was the fastest one. In fact it takes %10 of the time of the other two.

What is the right configurations for Java Stream in order to make it faster?
What wrong i am doing ?

package ned.main;

import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;

public class TestParallelStream {

    static private void testParallelStream() {
        System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1000000");

        ForkJoinPool forkJoinPool = new ForkJoinPool(10000);

        Date start = new Date();

        long sum1 = 0;
        for (int i = 0; i < 1_000_000; ++i) {
            sum1 += i * 10;
        }

        Date start1 = new Date();

        long sum2 = IntStream.range(1, 1_000_000)
                        .parallel()
                        .map(x -> x * 10)
                        .sum();

        Date start2 = new Date();

        try {
            long sum3 = forkJoinPool.submit(() ->
                IntStream
                    .range(1, 1_000_000)
                    .parallel()
                    .map(x -> x * 10)
                    .sum())
                        .get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }

        long serial = start1.getTime() - start.getTime();
        long parallelstream = start2.getTime() - start1.getTime();
        long withfork = start2.getTime() - start1.getTime();

        System.out.println(serial + "," + parallelstream + "," + withfork);

    }

    public static void main(String[] args) {
        testParallelStream();
    }
}

Thanks


问:
Clustered Index And Non Culstered Index In IBM Db2
Am little confused with clustered index and non clustered index.
is any differences in MySQL and DB2 regarding clustered Indexing ?

答:
In DB2, any single index on a table can be designated as the table's clustering index.  The index is a normal b-tree index, no different (physically) than any other index other than the fact that it's been identified as the clustering index.  The index has a series of index keys, and each index key has a list of RIDs (row IDs) that point to the physical location of the data for each row that matches the index key.

If you reorganize the table (using the REORG TABLE utility) DB2 will physically arrange the table's data (which is separate from the index's data) in the same physical order as the clustering index. DB2 will attempt to maintain the physical clustering order as new rows are inserted into the table (and you can help it by choosing an appropriate value for table's PCTFREE attribute), but over time the cluster ratio may decrease and you may need to reorganize the table again.

Compare this with MySQL, where with InnoDB, the table's data is stored in the primary key index's structure.  So, unlike DB2 where the index has the key columns and then a list of RIDs, the primary key index stores the entire row – there is no separate storage object holding the table's data.  This is why it's called a clustered index rather than a clustering index.  This massively increases the size of the physical index, making it significantly harder to ensure that it will remain cached in memory.

Secondary indexes in InnoDB store the index key and the primary key columns for the rows (rather than a RID) – this could be inefficient if the primary key is made up of many columns.

<soapbox>

Using the primary key (or any unique key) for "clustering" is ridiculous. The entire point of clustering it to maintain locality of related data. InnoDB is not alone here - Microsoft SQL Server does this as well.

Take, for example, a transaction table.  The primary key for this table may be transaction_id.  With InnoDB, this is the clustered index.  However, the likelihood that one transaction ID is related to the next transaction ID is pretty low.

account_id would make a much better clustering key precisely because it is not unique.  If I'm looking for all transactions for a particular account_id, having all of those rows on a single physical page makes a lot of sense and greatly will reduce the amount of I/O necessary to find all of those rows.

If the table's data is stored as part of the primary key's structure (i.e. on transaction_id), then you'll likely be reading pages from all over the index just to find all of the transactions for a single account.

You may argue that storing all of the data as part of the primary key is a performance benefit (i.e., 1 I/O to get any particular row), but this also means that caching the index has just become a lot harder because it will be much bigger.  "In memory" may be de rigueur, but if you need as much RAM as the size of your database to maintain performance that's useful only up to a point.

</soapbox>