问:
Cannot bundle exec rake:db:rollback due to errno: 150 - Foreign key constraint is incorrectly formed
I am fairly new to Rails, and I don't understand why I'm getting this error.

I have a teaches model in my rails app, and I want to delete this model using rails destroy model teaches. However, when I run bundle exec rake db:rollback, I keep getting this error

Mysql2::Error: Error on rename of './CrimeEducApp_development/#sql-ca1_27' to './CrimeEducApp_development/teaches' (errno: 150 - Foreign key constraint is incorrectly formed): ALTER TABLE teaches DROP PRIMARY KEY;

The teaches model doesn't have any tables that uses its attributes as foreign keys, but the teaches model does have attributes that reference from other tables.

Model File

```<code>require 'composite_primary_keys'

class Teach < ApplicationRecord
  self.primary_key = :course_id, :certification_number
  belongs_to :course, class_name: "Course", foreign_key: "course_id"
  belongs_to :worker, class_name: "Worker", foreign_key: "certification_number"
end
</code>```

Migration File

```<code>class CreateTeaches < ActiveRecord::Migration[5.0]
  def up
    create_table :teaches , {:id => false} do |t|
      t.integer :course_id
      t.integer :certification_number

      t.timestamps
    end
    execute "ALTER TABLE teaches ADD PRIMARY KEY(course_id, certification_number);"
    execute "ALTER TABLE teaches ADD CONSTRAINT teaches_references_course FOREIGN KEY (course_id) REFERENCES courses(course_id) ON DELETE CASCADE ON UPDATE CASCADE;"
    execute "ALTER TABLE teaches ADD CONSTRAINT teaches_references_worker FOREIGN KEY (certification_number) REFERENCES workers(certification_number) ON DELETE CASCADE ON UPDATE CASCADE;"
  end

  def down
    execute "ALTER TABLE teaches DROP PRIMARY KEY;"
    execute "ALTER TABLE teaches DROP FOREIGN KEY teaches_references_course;"
    execute "ALTER TABLE teaches DROP FOREIGN KEY teaches_references_worker;"
    drop_table :teaches
  end
end
</code>```

Is it possible that I am referencing my attributes wrong?

答: Apparently, dropping the primary keys have to be after, if not, the last execute statement.</p>

Body:
I am fairly new to Rails, and I don't understand why I'm getting this error.

I have a teaches model in my rails app, and I want to delete this model using rails destroy model teaches. However, when I run bundle exec rake db:rollback, I keep getting this error

Mysql2::Error: Error on rename of './CrimeEducApp_development/#sql-ca1_27' to './CrimeEducApp_development/teaches' (errno: 150 - Foreign key constraint is incorrectly formed): ALTER TABLE teaches DROP PRIMARY KEY;

The teaches model doesn't have any tables that uses its attributes as foreign keys, but the teaches model does have attributes that reference from other tables.

Model File

require 'composite_primary_keys'

class Teach < ApplicationRecord
  self.primary_key = :course_id, :certification_number
  belongs_to :course, class_name: "Course", foreign_key: "course_id"
  belongs_to :worker, class_name: "Worker", foreign_key: "certification_number"
end

Migration File

class CreateTeaches < ActiveRecord::Migration[5.0]
  def up
    create_table :teaches , {:id => false} do |t|
      t.integer :course_id
      t.integer :certification_number

      t.timestamps
    end
    execute "ALTER TABLE teaches ADD PRIMARY KEY(course_id, certification_number);"
    execute "ALTER TABLE teaches ADD CONSTRAINT teaches_references_course FOREIGN KEY (course_id) REFERENCES courses(course_id) ON DELETE CASCADE ON UPDATE CASCADE;"
    execute "ALTER TABLE teaches ADD CONSTRAINT teaches_references_worker FOREIGN KEY (certification_number) REFERENCES workers(certification_number) ON DELETE CASCADE ON UPDATE CASCADE;"
  end

  def down
    execute "ALTER TABLE teaches DROP PRIMARY KEY;"
    execute "ALTER TABLE teaches DROP FOREIGN KEY teaches_references_course;"
    execute "ALTER TABLE teaches DROP FOREIGN KEY teaches_references_worker;"
    drop_table :teaches
  end
end

Is it possible that I am referencing my attributes wrong?


来源: stackexchange

问:
Twilio Fax API - how to get the failure reason for failed fax send
Hi all (especially Twilio evangelists out there)

I've connected my EMR app to Twilio in order to send faxes, and it works reasonably well, however there's one big problem I'm running into. Some faxes fail to send, and I can't find the reason for it. If the line is busy, or if there's no answer, Twilio marks the fax instances accordingly, and I can attempt a retry or whatever. But in some circumstances I do not understand, a sent fax immediately comes back as Failed through the webHook. So it gets "queued", but the first message I receive from the webHook is FAILED - no additional data whatsoever.

I've tried checking the developer tools Debugger, but there nothing there - it's 100% blank (checked last 30 days). I know from my test account that I should find the failure reason there, if there's something wrong with my implementation (e.g., if Twilio can't fetch my PDF, or I don't provide the "from" number, etc). But on production account, it's empty.

Faxes that I send to myself (Toshiba multifunction) work just fine, report busy when busy, etc. But the faxes sent to other companies fail, though I'm quite sure the numbers are OK. I was wondering if anybody can make a list of the possible reasons for a fax to fail? And I was also wondering why Twilio doesn't send more details on Failed faxes, it would be very helpful to know what happened from my logs...

Thanks,
Vic

答:
Twilio evangelist here.

The statusCallback parameter makes as request to a URL when the status of the fax changes and includes parameters like Status, ErrorCode and ErrorReason.

```<code>curl 'https://fax.twilio.com/v1/Faxes' \
    -X POST \
    -d 'To=%2B15558675309'  \
    -d 'From=%2B15017250604'  \
    -d 'MediaUrl=https://www.twilio.com/docs/documents/25/justthefaxmaam.pdf' \
    -d 'StatusCallback=https://example.com/statusUpdates' \
    -u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token
</code>```

Twilio Fax is still in beta but I know that adding the ability to display fax logs in the Twilio Console is planned.

Hope that helps.

ContentLicense: CC BY-SA 3.0

Body:
Twilio evangelist here.

The statusCallback parameter makes as request to a URL when the status of the fax changes and includes parameters like Status, ErrorCode and ErrorReason.

curl 'https://fax.twilio.com/v1/Faxes' \
    -X POST \
    -d 'To=%2B15558675309'  \
    -d 'From=%2B15017250604'  \
    -d 'MediaUrl=https://www.twilio.com/docs/documents/25/justthefaxmaam.pdf' \
    -d 'StatusCallback=https://example.com/statusUpdates' \
    -u ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX:your_auth_token

Twilio Fax is still in beta but I know that adding the ability to display fax logs in the Twilio Console is planned.

Hope that helps.


问:
Get last "column" after .str.split() operation on column in pandas DataFrame
I have a column in a pandas DataFrame that I would like to split on a single space. The splitting is simple enough with DataFrame.str.split(' '), but I can't make a new column from the last entry. When I .str.split() the column I get a list of arrays and I don't know how to manipulate this to get a new column for my DataFrame.

Here is an example. Each entry in the column contains 'symbol data price' and I would like to split off the price (and eventually remove the "p"... or "c" in half the cases).

```<code>import pandas as pd
temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
temp2 = temp.ticker.str.split(' ')
</code>```

which yields

```<code>0    ['spx', '5/25/2001', 'p500']
1    ['spx', '5/25/2001', 'p600']
2    ['spx', '5/25/2001', 'p700']
</code>```

But temp2[0] just gives one list entry's array and temp2[:][-1] fails. How can I convert the last entry in each array to a new column? Thanks!

Body:
I have a column in a pandas DataFrame that I would like to split on a single space. The splitting is simple enough with DataFrame.str.split(' '), but I can't make a new column from the last entry. When I .str.split() the column I get a list of arrays and I don't know how to manipulate this to get a new column for my DataFrame.

Here is an example. Each entry in the column contains 'symbol data price' and I would like to split off the price (and eventually remove the "p"... or "c" in half the cases).

import pandas as pd
temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
temp2 = temp.ticker.str.split(' ')

which yields

0    ['spx', '5/25/2001', 'p500']
1    ['spx', '5/25/2001', 'p600']
2    ['spx', '5/25/2001', 'p700']

But temp2[0] just gives one list entry's array and temp2[:][-1] fails. How can I convert the last entry in each array to a new column? Thanks!

Body:
Using Pandas 0.20.3:

In [10]: import pandas as pd
    ...: temp = pd.DataFrame({'ticker' : ['spx 5/25/2001 p500', 'spx 5/25/2001 p600', 'spx 5/25/2001 p700']})
    ...:

In [11]: temp2 = temp.ticker.str.split(' ', expand=True)  # the expand=True return a DataFrame

In [12]: temp2
Out[12]:
     0          1     2
0  spx  5/25/2001  p500
1  spx  5/25/2001  p600
2  spx  5/25/2001  p700

In [13]: temp3 = temp.join(temp2[2])

In [14]: temp3
Out[14]:
               ticker     2
0  spx 5/25/2001 p500  p500
1  spx 5/25/2001 p600  p600
2  spx 5/25/2001 p700  p700


问:
Return a member variable if it exist
Somehow I feel there are several answer to the similar question, however I couldn't find a final solution to my problem.So, my apologies in advance:
I have many message structures that are either incoming:

```<code>struct X_1 //Y_2, Z_x, _...
{
 IncomingHeader incoming_header;
 //.......
};
</code>```

or Outgoing:

```<code>struct A_1 //B_2, C_x, _...
{
 OutgoingHeader outgoing_header;
 //.......
};
</code>```

The message headers are of only two types:

```<code>struct IncomingHeader
{
  A a;
  B b;
};

struct OutgoingHeader
{
  A a;
  B b;
  char c[SIZE};
};

//If it helps, eventually I am only interested in a and b in header structs.
</code>```

At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).
Is there a way to solve this problem?
(I am using boost 1.46 and not C++11)

答:
At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).

You didn't require a uniform signature, so, that's easy:

Live On Coliru

```<code>IncomingHeader const& get_header(X_1 const& msg) { return msg.incoming_header; }
OutgoingHeader const& get_header(A_1 const& msg) { return msg.outgoing_header; }
</code>```

Using it:

```<code>int main() {
    X_1 x;
    A_1 a;

    // in your decode function:
    {
        IncomingHeader const& h = get_header(x);
    }

    {
        OutgoingHeader const& h = get_header(a);
    }
}
</code>```

Making It Generic

So you do not have to add an overload for each message type:

Live On Coliru

```<code>template <typename T> auto get_header(T&& msg) -> decltype((msg.incoming_header)) { return msg.incoming_header; }
template <typename T> auto get_header(T&& msg) -> decltype((msg.outgoing_header)) { return msg.outgoing_header; }
</code>```

Which you could use for any declared type:

```<code>struct X_1 { IncomingHeader incoming_header; };
struct Y_2 { IncomingHeader incoming_header; };
struct Z_x { IncomingHeader incoming_header; };

//or Outgoing :
struct A_1 { OutgoingHeader outgoing_header; };
struct B_2 { OutgoingHeader outgoing_header; };
struct C_x { OutgoingHeader outgoing_header; };

template <typename T>
void decode(T&& msg) {
    auto&& header = get_header(msg);
    std::cout << typeid(T).name() << " has " << typeid(header).name() << "\n";
}

int main() {
    X_1 x;
    A_1 a;

    decode(x);
    decode(a);
    decode(Y_2{});
    decode(Z_x{});
    decode(B_2{});
    decode(C_x{});
}
</code>```

Which prints

```<code>X_1 has IncomingHeader
A_1 has OutgoingHeader
Y_2 has IncomingHeader
Z_x has IncomingHeader
B_2 has OutgoingHeader
C_x has OutgoingHeader
</code>```

In fact, you can funky message types like:

```<code>struct Funky { std::map<std::string, std::string> outgoing_header; };
</code>```

And it will print

```<code>Funky has std::map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >
</code>```

(see it all Live On Coliru)

About Getting Specific Headers (A&, B&)

You can have a simpler interface:

```<code>template <typename T> auto get_header(T&& msg) -> decltype((msg.incoming_header)) { return msg.incoming_header; }
template <typename T> auto get_header(T&& msg) -> decltype((msg.outgoing_header)) { return msg.outgoing_header; }

struct A {};
struct B {};

template <typename T> A const& getHeaderA(T const& msg) { return get_header(msg).a; }
template <typename T> B const& getHeaderB(T const& msg) { return get_header(msg).b; }
</code>```

This removes the type differences:

```<code>template <typename T>
void decode(T&& msg) {
    A const& headerA = getHeaderA(msg);
    B const& headerB = getHeaderB(msg);
}
</code>```

See it Live On Coliru again

Title: Return a member variable if it exist

Body:
Somehow I feel there are several answer to the similar question, however I couldn't find a final solution to my problem.So, my apologies in advance:
I have many message structures that are either incoming:

struct X_1 //Y_2, Z_x, _...
{
 IncomingHeader incoming_header;
 //.......
};

or Outgoing:

struct A_1 //B_2, C_x, _...
{
 OutgoingHeader outgoing_header;
 //.......
};

The message headers are of only two types:

struct IncomingHeader
{
  A a;
  B b;
};

struct OutgoingHeader
{
  A a;
  B b;
  char c[SIZE};
};

//If it helps, eventually I am only interested in a and b in header structs.

At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).
Is there a way to solve this problem?
(I am using boost 1.46 and not C++11)

Body:
At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).

You didn't require a uniform signature, so, that's easy:

Live On Coliru

IncomingHeader const& get_header(X_1 const& msg) { return msg.incoming_header; }
OutgoingHeader const& get_header(A_1 const& msg) { return msg.outgoing_header; }

Using it:

int main() {
    X_1 x;
    A_1 a;

    // in your decode function:
    {
        IncomingHeader const& h = get_header(x);
    }

    {
        OutgoingHeader const& h = get_header(a);
    }
}

Making It Generic

So you do not have to add an overload for each message type:

Live On Coliru

template <typename T> auto get_header(T&& msg) -> decltype((msg.incoming_header)) { return msg.incoming_header; }
template <typename T> auto get_header(T&& msg) -> decltype((msg.outgoing_header)) { return msg.outgoing_header; }

Which you could use for any declared type:

struct X_1 { IncomingHeader incoming_header; };
struct Y_2 { IncomingHeader incoming_header; };
struct Z_x { IncomingHeader incoming_header; };

//or Outgoing :
struct A_1 { OutgoingHeader outgoing_header; };
struct B_2 { OutgoingHeader outgoing_header; };
struct C_x { OutgoingHeader outgoing_header; };

template <typename T>
void decode(T&& msg) {
    auto&& header = get_header(msg);
    std::cout << typeid(T).name() << " has " << typeid(header).name() << "\n";
}

int main() {
    X_1 x;
    A_1 a;

    decode(x);
    decode(a);
    decode(Y_2{});
    decode(Z_x{});
    decode(B_2{});
    decode(C_x{});
}

Which prints

X_1 has IncomingHeader
A_1 has OutgoingHeader
Y_2 has IncomingHeader
Z_x has IncomingHeader
B_2 has OutgoingHeader
C_x has OutgoingHeader

In fact, you can funky message types like:

struct Funky { std::map<std::string, std::string> outgoing_header; };

And it will print

Funky has std::map<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >, std::less<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >

(see it all Live On Coliru)

About Getting Specific Headers (A&, B&)

You can have a simpler interface:

template <typename T> auto get_header(T&& msg) -> decltype((msg.incoming_header)) { return msg.incoming_header; }
template <typename T> auto get_header(T&& msg) -> decltype((msg.outgoing_header)) { return msg.outgoing_header; }

struct A {};
struct B {};

template <typename T> A const& getHeaderA(T const& msg) { return get_header(msg).a; }
template <typename T> B const& getHeaderB(T const& msg) { return get_header(msg).b; }

This removes the type differences:

template <typename T>
void decode(T&& msg) {
    A const& headerA = getHeaderA(msg);
    B const& headerB = getHeaderB(msg);
}

See it Live On Coliru again


问:
Code review in GIT before commit to VSTS/TFS repo
I am working with the customer to land on TFS/VSTS as DevOps tool where they have opted GIT as their version control and while evaluating the same they have come across a specific ask, i.e. requesting code review before code commit from Visual Studio to GIT repo as similar to request code review in TFVC. Looking forward for any insights/help if it can be achieved using any tools or practices.</p>

答:
Git is a different version control system with a drastically different paradigm. There is no direct equivalent to TFVC code reviews for Git. You can't enforce code review prior to commit with Git, because commits in Git occur against the developer's local repo.

There is, however, a superior code review model in the form of Pull Requests combined with Branch Policies.

Pull requests allow developers to request that a change they made on a development branch and pushed to VSTS be merged into a different branch. The commits that are part of the pull request can then be reviewed prior to merging.

Branch policies force (among other things) certain branches to be protected, so that all commits to them must be through pull requests.


问:
Chrome doesn't send "If-Modified-Since"
I want browsers to always add (except first time) "If-Modified-Since" request header to avoid unnecessary traffic.

Response headers are:

```<code>Accept-Ranges:bytes
Cache-Control:max-age=0, must-revalidate
Connection:Keep-Alive
Content-Length:2683
Content-Type:text/html; charset=UTF-8
Date:Thu, 05 Apr 2012 13:06:19 GMT
Keep-Alive:timeout=15, max=497
Last-Modified:Thu, 05 Apr 2012 13:05:11 GMT
Server:Apache/2.2.21 (Red Hat)
</code>```

FF 11 and IE 9 both send "If-Modified-Since" and get 304 in response but Chrome 18 doesn't and get 200.

Why? How to force Chrome to sent "If-Modified-Since" header?
I do not know if it important or not but all requests going through HTTPS.

答:
Don't disable cache in Chrome Dev Tools (on "Network" tab).

Cache-Control should be Cache-Control: public. Use true as second parameter to header PHP function: header("Cache-Control: public", true);

Title: Chrome doesn't send "If-Modified-Since"

Body:
I want browsers to always add (except first time) "If-Modified-Since" request header to avoid unnecessary traffic.

Response headers are:

Accept-Ranges:bytes
Cache-Control:max-age=0, must-revalidate
Connection:Keep-Alive
Content-Length:2683
Content-Type:text/html; charset=UTF-8
Date:Thu, 05 Apr 2012 13:06:19 GMT
Keep-Alive:timeout=15, max=497
Last-Modified:Thu, 05 Apr 2012 13:05:11 GMT
Server:Apache/2.2.21 (Red Hat)

FF 11 and IE 9 both send "If-Modified-Since" and get 304 in response but Chrome 18 doesn't and get 200.

Why? How to force Chrome to sent "If-Modified-Since" header?
I do not know if it important or not but all requests going through HTTPS.


问:
JQuery conflict with will_paginate ajax pagination
I followed this and got the AJAX pagination to work. But, when I include the JQuery library, it doesn't work. I'm using the jrails plugin but that doesn't help either. Any ideas? Thanks !

Here's the javascript

```<code>document.observe("dom:loaded", function() {
var container = $(document.body)
if (container) {
var img = new Image
img.src = 'images/spinner.gif'

function createSpinner() {
  return new Element('img', { src: img.src, 'class': 'spinner' })
}

container.observe('click', function(e) {
  var el = e.element()
  if (el.match('.pagination a')) {
    el.up('.pagination').insert(createSpinner())
    new Ajax.Request(el.href, { method: 'get' })
    e.stop()
  }
})
</code>```

}
})

EDIT

This is my actual code and it works fine when I don't include JQUERY.
But I need to use both prototype and JQUERY. Also when I click on one of the page no.s I get this

```<code>try {jQuery("#testing").html("\n  <div class=\"pagination ajax\"> ......
</code>```

答:
When you include the jquery library, it will assume that all $ calls are calls to jquery (rather than prototype for example).  To prevent this, call the method noConflict on your jquery object immediately after pulling it in.  See http://api.jquery.com/jQuery.noConflict/

When you've done this, $ calls will be ignored by jQuery: it will only respond to "jQuery", ie

```<code>$("foo").something => prototype
jQuery("foo").something => jQuery
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I followed this and got the AJAX pagination to work. But, when I include the JQuery library, it doesn't work. I'm using the jrails plugin but that doesn't help either. Any ideas? Thanks !

Here's the javascript

document.observe("dom:loaded", function() {
var container = $(document.body)
if (container) {
var img = new Image
img.src = 'images/spinner.gif'

function createSpinner() {
  return new Element('img', { src: img.src, 'class': 'spinner' })
}

container.observe('click', function(e) {
  var el = e.element()
  if (el.match('.pagination a')) {
    el.up('.pagination').insert(createSpinner())
    new Ajax.Request(el.href, { method: 'get' })
    e.stop()
  }
})

}
})

EDIT

This is my actual code and it works fine when I don't include JQUERY.
But I need to use both prototype and JQUERY. Also when I click on one of the page no.s I get this

try {jQuery("#testing").html("\n
 ......

Body:
When you include the jquery library, it will assume that all $ calls are calls to jquery (rather than prototype for example).  To prevent this, call the method noConflict on your jquery object immediately after pulling it in.  See http://api.jquery.com/jQuery.noConflict/

When you've done this, $ calls will be ignored by jQuery: it will only respond to "jQuery", ie

$("foo").something => prototype
jQuery("foo").something => jQuery


问:
stack data and restructure without using var to cases or casestovar in SPSS
I have the following situation: a loop (stack data) with only 1 index variable and with multiple items corresponding to the statements, as in the picture below (sorry it is Excel, but is the same as in SPSS):
stack data - cases on multiple lines, but never filling for 1 respondent all the columns

I want to reach to the following situation but without using casestovars to restructure, because that creates a lot of empty variables. I remember for older versions it was a command like Update, which was moving up the cases, to reach the following result:
reducing the cases per respondent

Like starting from this:

```<code>ID Index Q1_1 Q1_2 Q1_3 Q1_4 Q1_5 Q1_6
1   1     1    1
1   2                1    1
1   3                         1     1
</code>```

To reach to this:

```<code>ID Q1_1 Q1_2 Q1_3 Q1_4 Q1_5 Q1_6
1    1    1    1   1     1   1
</code>```

But without using casestovars. Is there any command in SPSS syntax for this?

Thank you very much, have a nice day!

答:
Not entirely sure how variable your data structure is likely to be in reality but if as demo'ed where you have only a single response for each q1_1 to q1_6 per respondent ID, then the below would be sufficient:

```<code>dataset declare dsAgg.
aggregate outfile="dsAgg" /break=respid /q1_1 to q1_6=max(q1_1 to q1_6).
</code>```

Also not sure of the significance of duplicate index values within the same respondent IDs, if this was intended or not.

Body:
I have the following situation: a loop (stack data) with only 1 index variable and with multiple items corresponding to the statements, as in the picture below (sorry it is Excel, but is the same as in SPSS):
stack data - cases on multiple lines, but never filling for 1 respondent all the columns

I want to reach to the following situation but without using casestovars to restructure, because that creates a lot of empty variables. I remember for older versions it was a command like Update, which was moving up the cases, to reach the following result:
reducing the cases per respondent

Like starting from this:

ID Index Q1_1 Q1_2 Q1_3 Q1_4 Q1_5 Q1_6
1   1     1    1
1   2                1    1
1   3                         1     1

To reach to this:

ID Q1_1 Q1_2 Q1_3 Q1_4 Q1_5 Q1_6
1    1    1    1   1     1   1

But without using casestovars. Is there any command in SPSS syntax for this?

Thank you very much, have a nice day!

Body:
Not entirely sure how variable your data structure is likely to be in reality but if as demo'ed where you have only a single response for each q1_1 to q1_6 per respondent ID, then the below would be sufficient:

dataset declare dsAgg.
aggregate outfile="dsAgg" /break=respid /q1_1 to q1_6=max(q1_1 to q1_6).

Also not sure of the significance of duplicate index values within the same respondent IDs, if this was intended or not.


问:
Content based routing using Spring Cloud Dataflow
I need to achieve content based routing and filtering using Spring Cloud Dataflow.

For e.g. If the input to my processor is a String. If the String contains say xyz I need to pass it to component/step X in my Spring Cloud Stream; otherwise I want it to go to component/step Y of my Stream.

I know router-sink can be used to achieve the same; however I wanted to use the routing\decision making as a processor; because my decision making apps are the processors in my Stream.

What is the best way to achieve the same?

答:
If you are using StreamListener in your processor, you can have multiple methods annotated with StreamListener taking a String argument, then using the conditional support to determine where to send (route) the information to. Here is the relevant section for this from the docs.
Although it is talking about different POJO's, you can extend the concept to what you are trying to accomplish.


问:
Proxy request host is overwritten by the real request
I am trying to serve a proxy like this:

```<code>package main

import (
    "net/http"
)

func main() {
    http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        println(r.Host)
    }))
}
</code>```

and calling it with curl

curl -k -x http://localhost:8080 http://golang.org/

I get golang.org printed out. Why I do not get the proxy hostname localhost? is that a bug or limitation with the http proxy?

Update

To clarify, what I am looking for is something like Nginx server address http://nginx.org/en/docs/http/ngx_http_core_module.html#var_server_addr

答:
I should use LocalAddrContextKey but looks like there is a known bug with setting it https://github.com/golang/go/issues/18686
A workaround is to hijack the http.ResponseWriter ex:

```<code>package main

import (
    "net/http"
)

func main() {
    http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        hij, ok := w.(http.Hijacker)
        if !ok {
            panic("http server does not support hijacker")
        }

        clientConn, _, err := hij.Hijack()
        if err != nil {
            panic(err.Error())
        }

        println(clientConn.LocalAddr().String())

    }))
}
</code>```

Body:
I am trying to serve a proxy like this:

package main

import (
    "net/http"
)

func main() {
    http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        println(r.Host)
    }))
}

and calling it with curl

curl -k -x http://localhost:8080 http://golang.org/

I get golang.org printed out. Why I do not get the proxy hostname localhost? is that a bug or limitation with the http proxy?

Update

To clarify, what I am looking for is something like Nginx server address http://nginx.org/en/docs/http/ngx_http_core_module.html#var_server_addr

Body:
I should use LocalAddrContextKey but looks like there is a known bug with setting it https://github.com/golang/go/issues/18686
A workaround is to hijack the http.ResponseWriter ex:

package main

import (
    "net/http"
)

func main() {
    http.ListenAndServe(":8080", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        hij, ok := w.(http.Hijacker)
        if !ok {
            panic("http server does not support hijacker")
        }

        clientConn, _, err := hij.Hijack()
        if err != nil {
            panic(err.Error())
        }

        println(clientConn.LocalAddr().String())

    }))
}


问:
Conditional statement syntax help
I am going through this WPF tutorial http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=18 and I have a question about the CountToFontSizeConverter section of the tutorial. Could someone please explain the return statement to me i.e

```<code>return ((minFontSize + count + increment) < maxFontSize) ?
         (minFontSize + count + increment) : maxFontSize;
</code>```

I understand it's a conditional but the syntax looks rather bespoke. If possible could someone re-write this in a simpler way? Thanks

答:
This:

```<code>return ((minFontSize + count + increment) < maxFontSize) ? (minFontSize + count + increment) : maxFontSize;
</code>```

Effectively translates to:

```<code>if ((minFontSize + count + increment) < maxFontSize)
     return (minFontSize + count + increment);
else
     return maxFontSize;
</code>```

In this case, since the goal is to prevent the expression from being larger than "maxFontSize", I'd personally just use:

```<code>return Math.Min(minFontSize + count + increment, maxFontSize);
</code>```

I find this expresses the intent much more clearly.

Title: Conditional statement syntax help

Body:
I am going through this WPF tutorial http://blogs.vertigo.com/personal/alanl/Blog/Lists/Posts/Post.aspx?ID=18 and I have a question about the CountToFontSizeConverter section of the tutorial. Could someone please explain the return statement to me i.e

return ((minFontSize + count + increment) < maxFontSize) ?
         (minFontSize + count + increment) : maxFontSize;

I understand it's a conditional but the syntax looks rather bespoke. If possible could someone re-write this in a simpler way? Thanks

Body:
This:

return ((minFontSize + count + increment) < maxFontSize) ? (minFontSize + count + increment) : maxFontSize;

Effectively translates to:

if ((minFontSize + count + increment) < maxFontSize)
     return (minFontSize + count + increment);
else
     return maxFontSize;

In this case, since the goal is to prevent the expression from being larger than "maxFontSize", I'd personally just use:

return Math.Min(minFontSize + count + increment, maxFontSize);

I find this expresses the intent much more clearly.


问:
Get current no from prooph event store
I try to update a projection from event store. The following line will load all events:

```<code>$events = $this->eventStore->load(new StreamName('mystream'));
</code>```

Currently i try to load only not handled events by passing the fromNumber parameter:

```<code>$events = $this->eventStore->load(new StreamName('mystream'), 10);
</code>```

This will load all events eg from 15 to 40. But i found no way to figure out which is the current/highest "no" of the results. But this is necessary for me to load only from this entry on the next time.

If the database is truncated (with restarted sequences) this is not a real problem cause i know that the events will start with 1. But if the primary key starts with a number higher than 1 can not figure out which event has which number in the event store

答: When you are using pdo-event-store, you have a key _position in the event metadata after loading, so your read model can track which position was the last you were working on. Other then that, if you are working with proophs event-store projections, you don't need to take care of that at all. The projector will track the current event position for all needed streams internally, you just need to provide callbacks for each event where you need to do something.

Title: Get current no from prooph event store

Body:
I try to update a projection from event store. The following line will load all events:

$events = $this->eventStore->load(new StreamName('mystream'));

Currently i try to load only not handled events by passing the fromNumber parameter:

$events = $this->eventStore->load(new StreamName('mystream'), 10);

This will load all events eg from 15 to 40. But i found no way to figure out which is the current/highest "no" of the results. But this is necessary for me to load only from this entry on the next time.

If the database is truncated (with restarted sequences) this is not a real problem cause i know that the events will start with 1. But if the primary key starts with a number higher than 1 can not figure out which event has which number in the event store


问:
How to enumerate a list within a list that was enumerated
The lists are made up as I do not have my code in front of me.

I have one list that has two items: listA = [Region1, Region2]

Within those lists (they are objects with embedded information originally) they each have a set of items. frame1 has three items; let's say layer1 = [VA, GA, NC] and frame2 has two items; layer2 = [WI, MI].

So, hierarchically:

```<code>Region1:
    VA
    GA
    NC
Region2:
    WI
    MI
</code>```

What I am trying to do is enumerate the parent layers to be:

```<code>0 Region1
1 Region2
</code>```

While also enumerating from each respective sublist so the result would look something like:

```<code>0 Region1
0 VA
1 GA
2 NC
1 Region2
0 WI
1 MI
</code>```

The first enumeration is simple, but I am lost on how to enumerate properly using any nested loop. I keep getting all 5 layers for each frame no matter how I've gone about it.

Any tips, tricks, ideas? I specifically need this to work with the basic enumerate function; not the Enum module.

答:
Following the example shared by @Reblochon Masque,</p>

```<code>>>> listA = [['abc', 'def'], ['ghi', 'klm'], ['nop', 'qrs']]                    >>> [(index,region) for index,region in enumerate(listA)]
[(0, ['abc', 'def']), (1, ['ghi', 'klm']), (2, ['nop', 'qrs'])]
>>> [(index,[(ind,it) for ind,it in enumerate(region)]) for index,region in enumerate(listA)]
[(0, [(0, 'abc'), (1, 'def')]), (1, [(0, 'ghi'), (1, 'klm')]), (2, [(0, 'nop'), (1, 'qrs')])]
>>> [("Region %d"%index,[(ind,it) for ind,it in enumerate(region)]) for index,region in enumerate(listA)]
[('Region 0', [(0, 'abc'), (1, 'def')]), ('Region 1', [(0, 'ghi'), (1, 'klm')]), ('Region 2', [(0, 'nop'), (1, 'qrs')])]

>>> format printing the list comprehension
>>> print "\n".join("Region %d \n%s"%(index,"\n".join("%d %s"%(ind,it) for ind,it in enumerate(region)))  for index,region in enumerate(listA))
Region 0
0 abc
1 def
Region 1
0 ghi
1 klm
Region 2
0 nop
1 qrs
</code>```

Body:
The lists are made up as I do not have my code in front of me.

I have one list that has two items: listA = [Region1, Region2]

Within those lists (they are objects with embedded information originally) they each have a set of items. frame1 has three items; let's say layer1 = [VA, GA, NC] and frame2 has two items; layer2 = [WI, MI].

So, hierarchically:

Region1:
    VA
    GA
    NC
Region2:
    WI
    MI

What I am trying to do is enumerate the parent layers to be:

0 Region1
1 Region2

While also enumerating from each respective sublist so the result would look something like:

0 Region1
0 VA
1 GA
2 NC
1 Region2
0 WI
1 MI

The first enumeration is simple, but I am lost on how to enumerate properly using any nested loop. I keep getting all 5 layers for each frame no matter how I've gone about it.

Any tips, tricks, ideas? I specifically need this to work with the basic enumerate function; not the Enum module.

Body:
Following the example shared by @Reblochon Masque,

>>> listA = [['abc', 'def'], ['ghi', 'klm'], ['nop', 'qrs']]                    >>> [(index,region) for index,region in enumerate(listA)]
[(0, ['abc', 'def']), (1, ['ghi', 'klm']), (2, ['nop', 'qrs'])]
>>> [(index,[(ind,it) for ind,it in enumerate(region)]) for index,region in enumerate(listA)]
[(0, [(0, 'abc'), (1, 'def')]), (1, [(0, 'ghi'), (1, 'klm')]), (2, [(0, 'nop'), (1, 'qrs')])]
>>> [("Region %d"%index,[(ind,it) for ind,it in enumerate(region)]) for index,region in enumerate(listA)]
[('Region 0', [(0, 'abc'), (1, 'def')]), ('Region 1', [(0, 'ghi'), (1, 'klm')]), ('Region 2', [(0, 'nop'), (1, 'qrs')])]

>>> format printing the list comprehension
>>> print "\n".join("Region %d \n%s"%(index,"\n".join("%d %s"%(ind,it) for ind,it in enumerate(region)))  for index,region in enumerate(listA))
Region 0
0 abc
1 def
Region 1
0 ghi
1 klm
Region 2
0 nop
1 qrs


问:
Open Linux terminal command in PHP
I have a server running on Linux that execute commands to 12 nodes (12 computers with Linux running in them). I recently downloaded PHP on the server to create web pages that can execute commands by opening a specific PHP file.

I used exec(), passthru(), shell_exec(), and system(). system() is the only one that returns a part of my code. I would like PHP to act like open termainal command in linux and I cannot figure out how to do it!

Here is an example of what is happening now (Linux directly vs PHP):
When using linux open terminal command directly:

```<code>user@wizard:/home/hyperwall/Desktop> /usr/local/bin/chbg -mt
</code>```

I get an output:

```<code>The following settings will be used:
  option = mtsu   COLOR =    IMAGE = imagehereyouknow!
  NODES  = LOCAL
and additional code to send it to 12 nodes.
</code>```

Now with PHP:

```<code>switch($_REQUEST['do'])
{ case 'test':
    echo system('/usr/local/bin/chbg -mt');
    break;
}
</code>```

Output:

```<code>The following settings will be used:
  option = mtsu   COLOR =    IMAGE = imagehereyouknow!
  NODES  = LOCAL
</code>```

And stops! Anyone has an explanation of what is happening? And how to fix it? Only system displays part of the code the other functions display nothing!

答:
I am working on a project that uses Terminal A on machine A to output to Terminal B on Machine B, both using linux for now. I didnt see it mentioned, but perhaps you can use redirection, something like this in your webserver:

```<code>switch($_REQUEST['do'])
 { case 'test':
    #process ID on the target (12345, 12346 etc)
    echo system('/usr/local/bin/chbg -mt > /proc/<processID>/fd/1');
    #OR
    #device file on the target (pts/0,tty0, etc)
    echo system('/usr/local/bin/chbg -mt > /dev/<TTY-TYPE>/<TTYNUM>');
    break;
 }
</code>```

Definitely the permissions need to be set correctly for this to work. The command "mesg y" in a terminal may also assist...Hope that helps.

Title: Open Linux terminal command in PHP

Body:
I have a server running on Linux that execute commands to 12 nodes (12 computers with Linux running in them). I recently downloaded PHP on the server to create web pages that can execute commands by opening a specific PHP file.

I used exec(), passthru(), shell_exec(), and system(). system() is the only one that returns a part of my code. I would like PHP to act like open termainal command in linux and I cannot figure out how to do it!

Here is an example of what is happening now (Linux directly vs PHP):
When using linux open terminal command directly:

user@wizard:/home/hyperwall/Desktop> /usr/local/bin/chbg -mt

I get an output:

The following settings will be used:
  option = mtsu   COLOR =    IMAGE = imagehereyouknow!
  NODES  = LOCAL
and additional code to send it to 12 nodes.

Now with PHP:

switch($_REQUEST['do'])
{ case 'test':
    echo system('/usr/local/bin/chbg -mt');
    break;
}

Output:

The following settings will be used:
  option = mtsu   COLOR =    IMAGE = imagehereyouknow!
  NODES  = LOCAL

And stops! Anyone has an explanation of what is happening? And how to fix it? Only system displays part of the code the other functions display nothing!

Body:
I am working on a project that uses Terminal A on machine A to output to Terminal B on Machine B, both using linux for now. I didnt see it mentioned, but perhaps you can use redirection, something like this in your webserver:

switch($_REQUEST['do'])
 { case 'test':
    #process ID on the target (12345, 12346 etc)
    echo system('/usr/local/bin/chbg -mt > /proc/<processID>/fd/1');
    #OR
    #device file on the target (pts/0,tty0, etc)
    echo system('/usr/local/bin/chbg -mt > /dev/<TTY-TYPE>/<TTYNUM>');
    break;
 }

Definitely the permissions need to be set correctly for this to work. The command "mesg y" in a terminal may also assist...Hope that helps.


问:
Multiple enum implementing protocols questions
I defined enums as confirming to a protocol Eventable:

```<code>protocol Eventable {
    var name: String { get }
    static var all: [Eventable] { get }
}

enum MyEnum: String, Eventable {
    case bla = "bla"
    case blu = "blu"

    var name: String {
        return self.rawValue
    }

    static var all: [Eventable] {
        return [
            MyEnum.bla,
            MyEnum.blu
        ]
    }
}
</code>```

I have other enums like MyEnum also under the form:
    enum Bla: String, Eventable {
    }

I have two questions:

for the enums having a String data type, I would like to avoid duplicating the generation of the variable name:
var name: String
I am not sure how to write that in Swift. I tried to play around with the "where" clause but not success. How can I achieve that?

when I write my enums and conform to the protocol for that part:
static var all: [Eventable] { get }.
I would like that for the enum MyEnum, it constrains the variable to:
static var all: [MyEnum] { ... }
because for now I can put in the returned array any element being an Eventable and it's not what I need.
Amongst other things, I tried to define a generic constraint in the protocol for it, but I get the following error:

Protocol 'Eventable' can only be used as a generic constraint because
  it has Self or associated type requirements

Thank you very much for the help!

答:
For your second question, you just need to use Self:

```<code>protocol Eventable {
    var name: String { get }
    static var all: [Self] { get }
}
</code>```

Self, similar to self, just means "the current type".

The first question is a little bit harder because you can't really get all the values of an enum safely. See here for more info. The closest I got was:

```<code>extension Eventable where Self: RawRepresentable, Self.RawValue == String {
    var name: String {
        return self.rawValue
    }
}
</code>```

This means that you can omit the declaration of name in MyEnum, but not all.

Body:
I defined enums as confirming to a protocol Eventable:

protocol Eventable {
    var name: String { get }
    static var all: [Eventable] { get }
}

enum MyEnum: String, Eventable {
    case bla = "bla"
    case blu = "blu"

    var name: String {
        return self.rawValue
    }

    static var all: [Eventable] {
        return [
            MyEnum.bla,
            MyEnum.blu
        ]
    }
}

I have other enums like MyEnum also under the form:
    enum Bla: String, Eventable {
    }

I have two questions:

for the enums having a String data type, I would like to avoid duplicating the generation of the variable name:
var name: String
I am not sure how to write that in Swift. I tried to play around with the "where" clause but not success. How can I achieve that?

when I write my enums and conform to the protocol for that part:
static var all: [Eventable] { get }.
I would like that for the enum MyEnum, it constrains the variable to:
static var all: [MyEnum] { ... }
because for now I can put in the returned array any element being an Eventable and it's not what I need.
Amongst other things, I tried to define a generic constraint in the protocol for it, but I get the following error:

Protocol 'Eventable' can only be used as a generic constraint because
  it has Self or associated type requirements

Thank you very much for the help!

Body:
For your second question, you just need to use Self:

protocol Eventable {
    var name: String { get }
    static var all: [Self] { get }
}

Self, similar to self, just means "the current type".

The first question is a little bit harder because you can't really get all the values of an enum safely. See here for more info. The closest I got was:

extension Eventable where Self: RawRepresentable, Self.RawValue == String {
    var name: String {
        return self.rawValue
    }
}

This means that you can omit the declaration of name in MyEnum, but not all.


问:
How to properly add document.addEventListener to Angular2?
I've came across cordova RemoteControl plugin where, to listen to its event, the addEventListener is needed to be registered. </p>

```<code>//listen for the event
document.addEventListener("remote-event", function(event) {
//do something
});
</code>```

<p>Is it a proper way for me to do it? </p>

答:
this works for me like magic</p>

```<code> document.querySelector('#videostop').addEventListener('click', () => {
            //function here
            console.log('your result');
         });
</code>```

Body:
I've came across cordova RemoteControl plugin where, to listen to its event, the addEventListener is needed to be registered.

//listen for the event
document.addEventListener("remote-event", function(event) {
//do something
});

Is it a proper way for me to do it?

Body:
this works for me like magic

 document.querySelector('#videostop').addEventListener('click', () => {
            //function here
            console.log('your result');
         });


问:
How to understand "individual neurons are the basis directions of activation space"?
In a recent article at Distill (link) about visualizing internal representation of convolutional neural networks, there is the following passage (bold is mine):

If neurons are not the right way to understand neural nets, what is? In real life, combinations of neurons work together to represent images in neural networks. Individual neurons are the basis directions of activation space, and it is not clear that these should be any more special than any other direction.

Szegedy et al.[11]  found that random directions seem just as meaningful as the basis directions. More recently Bau, Zhou et al.[12]  found basis directions to be interpretable more often than random directions. Our experience is broadly consistent with both results; we ﬁnd that random directions often seem interpretable, but at a lower rate than basis directions.

I feel like they are talking about linear algebra representations, but struggle to understand how one neuron can represent a basis vector.

So at this point I have 2 main questions:

A neuron has only a scalar output, so how that can be a basic direction?

What is an activation space and how to intuitively think about it?

I feel like understanding these can really broaden my intuition about internal geometry of neural nets. Can someone please help by explaining or point me in the direction of understanding internal processes of neural nets from the linear algebra point of view?

答:
My intuition would be: If you have a hidden layer with e.g. 10 neurons, then the activations of these 10 neurons span a 10-dimensional space. "Individual neurons are the basis directions of activation space" then means something like "the 10 states where exactly one neuron is 1 and the others are 0 are unit vectors that span this 'activation space'". But obviously, any independent set of 10 vectors spans the same space. And since a fully-connected layer is basically just a matrix product with the output of the previous layer, there's no obvious reason why these unit vectors should be special in any way.

This is important if you try to visualize what this hidden layer represents: Who says that "neuron 3" or the state "neuron 3 is active and the other neurons are 0" even does represent anything? It's equally possible that "neurons 2,3 and 5 are 1, neuron 7 is -2 and the others are 0" has a visual representation, but the unit vectors do not.

Ideally, you would hope that random vectors represent distinct concepts, because that way a hidden layer with n neurons can represent O(p^n) concepts (for some p > 1), instead of n concepts for n unit vectors


问:
Find out how many thousands and hundreds and tens are there in a amount
I am having a asp application and in that amount column is there. I need to find out how many thousands and hundreds and tens are there in that amount

For example

if i am having amount as 3660 means
1000's - 3
100's - 6
10's - 6

like this i need

Can any body help me

答:
Decide where the first digit of the quotient should be placed. Do not complete the division.

The first digit of the quotient for 2,370÷24
2,370÷24
 should be in the Choose... ones tens hundreds thousands   place


问:
Shuffling biased random numbers
While thinking about this question and conversing with the participants, the idea came up that shuffling a finite set of clearly biased random numbers makes them random because you don't know the order in which they were chosen.  Is this true and if so can someone point to some resources?

EDIT:  I think I might have been a little unclear. Suppose a bad random numbers generator. Take n values. These are biased(the rng is bad). Is there a way through shuffling to make the output of the rng over multiple trials statistically match the output of a known good rng?

答:
False.

There is an easy test: Assume the bias in the original set creation algorithm is "creates sets whose arithmetic average is significantly lower than expected average". Obviously, shuffling the result of the algorithm will not change the averages and thus not remove the bias.

Also, regarding your clarification: How would you shuffle the set? Using the same bad output from the bad RNG that created the set in the first place? Or using a better RNG? Which raises the question why you don't use that directly.

OwnerDisplayName: JPunyon

ContentLicense: CC BY-SA 4.0

Title: Shuffling biased random numbers

LastEditorDisplayName: JPunyon

OwnerDisplayName: David Schmitt


问:
Ice Chat Application
I'm ICE starter. At http://zeroc.com there is good tutorial on how to create chat. I decided to use the tutorial as base. And first thing I tried to do was writing ChatRoom class in c# instead of given c++ implementation. I tried to do the same in my c# code. ChatRoom implementation in c++:

```<code>// C++
class ChatRoomCallbackAdapter { /* ... */ };
typedef IceUtil::Handle<ChatRoomCallbackAdapter> ChatRoomCallbackAdapterPtr;
class ChatRoom : public IceUtil::Shared
{
public:
    ChatRoom(bool trace, const Ice::LoggerPtr& logger);
    void reserve(const std::string&);
    void unreserve(const std::string&);
    void join(const std::string&, const ChatRoomCallbackAdapterPtr&);
    void leave(const std::string&);
    Ice::Long send(const std::string&, const std::string&);
private:
    typedef std::map<std::string, ChatRoomCallbackAdapterPtr> ChatRoomCallbackMap;
    ChatRoomCallbackMap _members;
    std::set<std::string> _reserved;
    IceUtil::Mutex _mutex;
    const bool _trace;
    const Ice::LoggerPtr _logger;
};
</code>```

Some piece of class-members implementation:

```<code>// ...
void ChatRoom::reserve(const string& name)
{
    IceUtil::Mutex::Lock sync(_mutex);
    if(_reserved.find(name) != _reserved.end() ||
       _members.find(name) != _members.end())
    {
        throw string("The name " + name + " is already in use.");
    }
    _reserved.insert(name);
}
// ...
</code>```

I was writng next:

```<code>public class ChatRoom : IceUtil
</code>```

when I encountered an error. I found that IceUtil dll in distribution package isn't COM-visible therefore I can't use it in my c# project.

What can I use instead of c++

```<code>IceUtil::Handle<T>
</code>```

as far as I understand it is a smart pointer.
How can I implement server like the one's given in c#?

Would it be the same in c# (talking about mutexes) comparing to above c++ class:

```<code>public class ChatRoom
{
    // ...
    void Reserve(System.String Name)
    {
        lock(this)
        {
            // operations
        }
    }
}
</code>```

?

Thanks!

答: I don't know anything about ICE, but their website lists a .NET implementation - why don't you use that instead of COM if you want to use C#? There's even a section of documentation with an example of a C# server.</p>

Title: Ice Chat Application

Body:
I'm ICE starter. At http://zeroc.com there is good tutorial on how to create chat. I decided to use the tutorial as base. And first thing I tried to do was writing ChatRoom class in c# instead of given c++ implementation. I tried to do the same in my c# code. ChatRoom implementation in c++:

// C++
class ChatRoomCallbackAdapter { /* ... */ };
typedef IceUtil::Handle<ChatRoomCallbackAdapter> ChatRoomCallbackAdapterPtr;
class ChatRoom : public IceUtil::Shared
{
public:
    ChatRoom(bool trace, const Ice::LoggerPtr& logger);
    void reserve(const std::string&);
    void unreserve(const std::string&);
    void join(const std::string&, const ChatRoomCallbackAdapterPtr&);
    void leave(const std::string&);
    Ice::Long send(const std::string&, const std::string&);
private:
    typedef std::map<std::string, ChatRoomCallbackAdapterPtr> ChatRoomCallbackMap;
    ChatRoomCallbackMap _members;
    std::set<std::string> _reserved;
    IceUtil::Mutex _mutex;
    const bool _trace;
    const Ice::LoggerPtr _logger;
};

Some piece of class-members implementation:

// ...
void ChatRoom::reserve(const string& name)
{
    IceUtil::Mutex::Lock sync(_mutex);
    if(_reserved.find(name) != _reserved.end() ||
       _members.find(name) != _members.end())
    {
        throw string("The name " + name + " is already in use.");
    }
    _reserved.insert(name);
}
// ...

I was writng next:

public class ChatRoom : IceUtil

when I encountered an error. I found that IceUtil dll in distribution package isn't COM-visible therefore I can't use it in my c# project.

What can I use instead of c++

IceUtil::Handle<T>

as far as I understand it is a smart pointer.
How can I implement server like the one's given in c#?

Would it be the same in c# (talking about mutexes) comparing to above c++ class:

public class ChatRoom
{
    // ...
    void Reserve(System.String Name)
    {
        lock(this)
        {
            // operations
        }
    }
}

?

Thanks!


问:
Shell remove a comma in a file
I want to remove first/last comma of multiple commas which are in between semicolon.

clarification: I have a comma separated key:value records in a text file which i want them to load into a db. Out of these records I have certain values which are separated by a comma as shown below. So, before i trim off key's from each record i want to remove "," which is in between firstname and lastname.

Note: All the names are not of same format meaning with first name and second name, some records are with only name.

Current format:

SNO:01, ID:123, Name: firstname, lastname, fname: firstname , lastname, sex:male, age:42

SNO:02, ID:124, Name: name,  fname: firstname , lastname, sex:male, age:40

     SNO:03, ID:125, Name: firstname , lastname, fname: name, sex:male, age:37

SNO:04, ID:126, Name: name, fname: name, sex:male, age:35

Required format:

SNO:01, ID:123, Name: firstname+lastname, fname: firstname+lastname, sex:male, age:42

SNO:02, ID:124, Name: name,  fname: firstname+lastname, sex:male, age:40

SNO:03, ID:125, Name: firstname+lastname, fname: name, sex:male, age:37

SNO:04, ID:126, Name: name, fname: name, sex:male, age:35

I want firstname and lastname to be as just name. To achieve this i want to make sure there is only one comma in between two ":".

Thanks.

答:
You can try this awk.

```<code>awk -F: -vOFS=: '{for(i=1;i<=NF;i++)if($i ~ /[^,]*,[^,]*,.*/)sub(",","+",$i)}1' infile
</code>```

Field separator = : , Output field separator = :

For each field, look for 2 comma.

If find, substitute the first by +

1 for print the line.

Title: Shell remove a comma in a file

Body:
You can try this awk.

awk -F: -vOFS=: '{for(i=1;i<=NF;i++)if($i ~ /[^,]*,[^,]*,.*/)sub(",","+",$i)}1' infile

Field separator = : , Output field separator = :

For each field, look for 2 comma.

If find, substitute the first by +

1 for print the line.


问:
javascript - missing array
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}
</code>```

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

```<code>function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));
</code>```

My output is:

```<code>charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }
</code>```

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

答:
You can shortify your code a bit:</p>

```<code>const string = "aabbcc", result = {};

for(const char of string)
  result[char] = 0;
</code>```

Title: javascript - missing array

Body:
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));

My output is:

charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

Body:
You can shortify your code a bit:

const string = "aabbcc", result = {};

for(const char of string)
  result[char] = 0;


问:
SQL Restore DB frozen at 100% [SQL SERVER 2008 R2]
This is the second time I've restored my DB and it freezes at 100% not sure why.

```<code>10 percent processed.
20 percent processed.
30 percent processed.
40 percent processed.
50 percent processed.
60 percent processed.
70 percent processed.
80 percent processed.
90 percent processed.
100 percent processed.
Processed 16305440 pages for database 'db1', file 'db1' on file 1.
Processed 74479 pages for database 'db1', file 'db1_log' on file 1.
</code>```

I've tried using the console for restoring and also running the command directly into the window and it stays at 100%, it took 63m to completely restore and now is being sometime since then.

```<code>session_id  command Percent Complete    ETA Completion Time Elapsed Min ETA Min ETA Hours
61  RESTORE DATABASE    100.00  2017-11-13 16:02:54 69  0.00    0.00
</code>```

What is going on?

```<code>RESTORE DATABASE [db1] FROM  DISK = N'D:\DATA\db1.bak' WITH  FILE = 1,  MOVE N'db1' TO N'D:\DATA\db1.mdf',  MOVE N'db1_log' TO N'D:\DATA\db1_1.ldf',  NOUNLOAD,  STATS = 10
</code>```

SQL SERVER 2008 R2

答:
Your RESTORE command has no WITH NORECOVERY and the default is WITH RECOVERY, so it was no need to execute another RESTORE WITH RECOVERY.

Check your SQL Server log instead. Maybe you'll find there smth like

Recovery completed for database MyDB (database ID 5) in N
  second(s) (analysis K ms, redo L ms, undo M ms.) This is an
  informational message only. No user action is required.

This means that even if your database was restored the database recovery was not finished yet. This happens when your db has open
 transactions at the time backup starts, so these transactions should be rolled forward/rolled back depending on whether they were committed or not at the moment backup was finished

Body:
This is the second time I've restored my DB and it freezes at 100% not sure why.

10 percent processed.
20 percent processed.
30 percent processed.
40 percent processed.
50 percent processed.
60 percent processed.
70 percent processed.
80 percent processed.
90 percent processed.
100 percent processed.
Processed 16305440 pages for database 'db1', file 'db1' on file 1.
Processed 74479 pages for database 'db1', file 'db1_log' on file 1.

I've tried using the console for restoring and also running the command directly into the window and it stays at 100%, it took 63m to completely restore and now is being sometime since then.

session_id  command Percent Complete    ETA Completion Time Elapsed Min ETA Min ETA Hours
61  RESTORE DATABASE    100.00  2017-11-13 16:02:54 69  0.00    0.00

What is going on?

RESTORE DATABASE [db1] FROM  DISK = N'D:\DATA\db1.bak' WITH  FILE = 1,  MOVE N'db1' TO N'D:\DATA\db1.mdf',  MOVE N'db1_log' TO N'D:\DATA\db1_1.ldf',  NOUNLOAD,  STATS = 10

SQL SERVER 2008 R2


问:
setResult is ignored when user presses the back button
In my application, I defined 2 activities in the Manifest file like this:

```<code><activity android:name=".event.EventDetailsActivity"
      android:launchMode="singleTop"
      android:parentActivityName=".main.MainActivity"
      android:theme="@style/AppTheme.WithActionBar"/>

<activity
      android:name=".main.MainActivity"
      android:launchMode="singleTop"/>
</code>```

In the MainActivity, I have 4 fragments. In one fragment, I start the EventDetailsActivity in one fragment using:

```<code>Intent intent = new Intent(new Intent(getContext(), EventDetailsActivity.class));
intent.putExtra(EventDetailsActivity.ID_KEY, id);
intent.putExtra(EventDetailsActivity.TYPE_KEY, true);
startActivityForResult(intent, DETAILS_REQUEST);
</code>```

How I handle the back navigation in EventDetailsActivity:

```<code>public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public boolean onSupportNavigateUp() {
    Log.d(TAG, "Navigate up");
    onBackPressed();
    return true;
}

@Override
public void onBackPressed() {
    Log.d(TAG, "Back pressed " + isChanged);
    if (isChanged) {
        Log.d(TAG, "Set result");
        setResult(RESULT_OK);
        finish();
    }
    super.onBackPressed();
}
</code>```

The problem is onActivityResult get called in the calling Fragment but the result code is always 0 (RESULT_CANCELED). Also, onSupportNavigateUp never gets called if I press the back arrow button. Is there any workaround for this problem?

答:
Remove : android:launchMode="singleTop"

and remove super.onBackpressed in on onBackpressed function
because you used finish()

Body:
In my application, I defined 2 activities in the Manifest file like this:

<activity android:name=".event.EventDetailsActivity"
      android:launchMode="singleTop"
      android:parentActivityName=".main.MainActivity"
      android:theme="@style/AppTheme.WithActionBar"/>

<activity
      android:name=".main.MainActivity"
      android:launchMode="singleTop"/>

In the MainActivity, I have 4 fragments. In one fragment, I start the EventDetailsActivity in one fragment using:

Intent intent = new Intent(new Intent(getContext(), EventDetailsActivity.class));
intent.putExtra(EventDetailsActivity.ID_KEY, id);
intent.putExtra(EventDetailsActivity.TYPE_KEY, true);
startActivityForResult(intent, DETAILS_REQUEST);

How I handle the back navigation in EventDetailsActivity:

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            NavUtils.navigateUpFromSameTask(this);
            return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
public boolean onSupportNavigateUp() {
    Log.d(TAG, "Navigate up");
    onBackPressed();
    return true;
}

@Override
public void onBackPressed() {
    Log.d(TAG, "Back pressed " + isChanged);
    if (isChanged) {
        Log.d(TAG, "Set result");
        setResult(RESULT_OK);
        finish();
    }
    super.onBackPressed();
}

The problem is onActivityResult get called in the calling Fragment but the result code is always 0 (RESULT_CANCELED). Also, onSupportNavigateUp never gets called if I press the back arrow button. Is there any workaround for this problem?


问:
Using PouchDB+CouchDB sync capabilities with a Laravel
We are thrilled about the new IndexDB API and the different overlays that have been created.

One got our attention for it's sync capabilities : CouchDB on the server and PouchDB for the clients.

It should work very well for webApp that should work by themselfs, but in the real life we often need server-side work.
A simple example : imagine you want to shoot an email when a user change a book's title.

This is a simplified example but we would use Laravel as our back-end framework.

So in the use-case :

the user change the book's title,

it's saved on his PouchDB

it's synced on the CouchDB

the other clients get the book's title updated in their PouchDB

... but how does the Laravel knows the book's title has been updated ?

Is there any events system it should hook on ? Maybe thrue redis ?

And once it's done, if the Laravel update the CouchDB, will it fire a sync for all the clients ?

This is a very open question, please feel free to share other solutions than Couch+Pouch.

答:
Have you heard of Websocket ?

This library is exactly what you want. Using PouchDB with socket connection it will open a websocket connection with server. And on the backend you will listen on same port for events.

Regarding to use it in laravel, I think you can use this package to listen on events.

Have a look at this video (just to see how sync works) https://www.youtube.com/watch?v=8jOF23dfvl4


问:
Max image width in Mobile Safari? Getting unwanted downscaling on panos
I want to display very wide, panoramic images in Mobile Safari (iPhone, iPod, iPad). These work fine in OS X Safari and in other browsers, but on Mobile Safari there seems to be a limit on the maximum image width.

Consider this web page:

http://basepath.com/public/test1.html

with this source:

```<code><!DOCTYPE HTML>
<html>
<head>
<meta name = 'viewport' content = 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0'>
<title>Test Image 1</title>
</head>
<body>
<p>
2415 x 750 (about 3.2:1)
<p>
<img src='http://farm5.static.flickr.com/4129/4987348894_76194e79d6_o.jpg' />
</body>
</html>
</code>```

It does exactly what I want on Mobile Safari. You can pan the photo. The aspect ratio is about 3.2:1.

But a wider image, about 4:1, gets scaled down, as seen on this page:

[http://]basepath.com/public/test2.html

[My low reputation prevents me from providing the above as a link. Limited to just one.]

The source is identical except for the commentary and image:

```<code><!DOCTYPE HTML>
<html>
<head>
<meta name = 'viewport' content = 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0'>
<title>Test Image 2</title>
</head>
<body>
<p>
3028 x 750 (about 4:1)
<p>
<img src='http://farm5.static.flickr.com/4113/4994072964_1a7f7f90fe_o.jpg' />
</body>
</html>
</code>```

You have to view these on Mobile Safari to see the problem.

Before you answer, some additional facts:

Image #2, which doesn't work, is only 200K (very low JPEG quality). Image #1, which does, is 700K. So size isn't the problem.

Putting an explicit width and height on the IMG element does indeed make the image the right size, but it's scaled up and therefore has jaggies. I want actual pixels. The problem therefore seems to be in loading the image originally, not processing it for presentation.

I've tried it without the viewport meta stuff, with no effect.

OK, now for my questions:

Is there in fact a limit on how wide Mobile Safari will show an image? Does anyone know of documentation for it, and, if so, what the rules are?

Is there any way to get around the problem? I've horsed around with JavaScript quite a bit to try to construct dynamic HTML to do the job, but, as I said above, I think the problem occurs when the image is first downloaded, far too early for anything done in JavaScript to be effective.

答:
I found something about the rules that are applied whether an image is automatically downscaled in mobile safari:

http://teknocat.org/blog/computer-stuff/web-development/show/6/mobile-safari-background-image-scaling-quirk

Body:
I want to display very wide, panoramic images in Mobile Safari (iPhone, iPod, iPad). These work fine in OS X Safari and in other browsers, but on Mobile Safari there seems to be a limit on the maximum image width.

Consider this web page:

http://basepath.com/public/test1.html

with this source:

<!DOCTYPE HTML>

<meta name = 'viewport' content = 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0'>
<title>Test Image 1</title>

2415 x 750 (about 3.2:1)

It does exactly what I want on Mobile Safari. You can pan the photo. The aspect ratio is about 3.2:1.

But a wider image, about 4:1, gets scaled down, as seen on this page:

[http://]basepath.com/public/test2.html

[My low reputation prevents me from providing the above as a link. Limited to just one.]

The source is identical except for the commentary and image:

<!DOCTYPE HTML>

<meta name = 'viewport' content = 'width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0'>
<title>Test Image 2</title>

3028 x 750 (about 4:1)

You have to view these on Mobile Safari to see the problem.

Before you answer, some additional facts:

Image #2, which doesn't work, is only 200K (very low JPEG quality). Image #1, which does, is 700K. So size isn't the problem.

Putting an explicit width and height on the IMG element does indeed make the image the right size, but it's scaled up and therefore has jaggies. I want actual pixels. The problem therefore seems to be in loading the image originally, not processing it for presentation.

I've tried it without the viewport meta stuff, with no effect.

OK, now for my questions:

Is there in fact a limit on how wide Mobile Safari will show an image? Does anyone know of documentation for it, and, if so, what the rules are?

Is there any way to get around the problem? I've horsed around with JavaScript quite a bit to try to construct dynamic HTML to do the job, but, as I said above, I think the problem occurs when the image is first downloaded, far too early for anything done in JavaScript to be effective.


问:
Laravel Controller use same object in two functions
Is there a way to use a object variable instantiated from a class in two functions?

Here's the code I've tried, but its just returning null:

```<code>class bookAppointmentsController extends APIController
{
    private $business;

    public funcition check($key)
    {
        $this->business = new APIClass();
        $setconnection = $this->business->connectAPI($key);
    }

    public function book()
    {
        dd($this->business) //returns null
        $this->business->book();
    }
}
</code>```

I am trying to use the $business object in two functions but it does not work, when I dd($business) it returns null

Any way to do this?

答:
Maybe the solution could be to make the variable Global

You could make the variable global:

```<code>function method( $args ) {
    global $newVar;
    $newVar = "Something";

}

function second_method() {
    global $newVar;
    echo $newVar;
}
</code>```

Or you could return it from the first method and use it in the second method

```<code>public function check($key)
{
    $this->business = new APIClass();
    $setconnection = $this->business->connectAPI($key);
    return $this->business;
}

public function book()
{
   $business = check($key);
   $business->book();
}
</code>```

Body:
Is there a way to use a object variable instantiated from a class in two functions?

Here's the code I've tried, but its just returning null:

class bookAppointmentsController extends APIController
{
    private $business;

    public funcition check($key)
    {
        $this->business = new APIClass();
        $setconnection = $this->business->connectAPI($key);
    }

    public function book()
    {
        dd($this->business) //returns null
        $this->business->book();
    }
}

I am trying to use the $business object in two functions but it does not work, when I dd($business) it returns null

Any way to do this?

Body:
Maybe the solution could be to make the variable Global

You could make the variable global:

function method( $args ) {
    global $newVar;
    $newVar = "Something";

}

function second_method() {
    global $newVar;
    echo $newVar;
}

Or you could return it from the first method and use it in the second method

public function check($key)
{
    $this->business = new APIClass();
    $setconnection = $this->business->connectAPI($key);
    return $this->business;
}

public function book()
{
   $business = check($key);
   $business->book();
}


问:
Bulk updating normalized Redux state
Let's say I have normalized state like this (using normalizr)

```<code>entities: {
  todos: {
    'aaa': {
      id: 'aaa',
      text: 'Todo A',
      completed: false
    },
    'bbb': {
      id: 'bbb',
      text: 'Todo B',
      completed: false
    },
    'ccc': {
      id: 'ccc',
      text: 'Todo C',
      completed: false
    }
  }
}
</code>```

Then I have an action that fetches array of IDs from the server, that are completed. For that action type, I have reducer like this:

```<code>const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: action.payload.completedIds.map((id) => {
          return {
            [id]: {
              ...state.todos[id],
              completed: true
            }
          }
        })
      };
    default:
      return state;
  }
};
</code>```

If I recieved an array with ['aaa', 'ccc'] (could be thousands of items in real world app), I want to set "completed" to TRUE on those respective todos in a single action, is it possible?

My current implementation of reducer doesn't work since it returns an array of objects, while original normalized state is object with IDs as key.

Thanks.

答:
You could store the modified todos in an object and then update it using the spread syntax like</p>

```<code>const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      let newTodos = {};
      action.payload.completedIds.forEach((id) => {
          newTodos[id]: {
              ...state.todos[id],
              completed: true
            }
          })
        })
      return {
        ...state,
        todos: {
             ...state.todos,
             ...newTodos
        }
      };
    default:
      return state;
  }
};
</code>```

Title: Bulk updating normalized Redux state

Body:
Let's say I have normalized state like this (using normalizr)

entities: {
  todos: {
    'aaa': {
      id: 'aaa',
      text: 'Todo A',
      completed: false
    },
    'bbb': {
      id: 'bbb',
      text: 'Todo B',
      completed: false
    },
    'ccc': {
      id: 'ccc',
      text: 'Todo C',
      completed: false
    }
  }
}

Then I have an action that fetches array of IDs from the server, that are completed. For that action type, I have reducer like this:

const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      return {
        ...state,
        todos: action.payload.completedIds.map((id) => {
          return {
            [id]: {
              ...state.todos[id],
              completed: true
            }
          }
        })
      };
    default:
      return state;
  }
};

If I recieved an array with ['aaa', 'ccc'] (could be thousands of items in real world app), I want to set "completed" to TRUE on those respective todos in a single action, is it possible?

My current implementation of reducer doesn't work since it returns an array of objects, while original normalized state is object with IDs as key.

Thanks.

Body:
You could store the modified todos in an object and then update it using the spread syntax like

const todos = (state = initialState, action) => {
  switch (action.type) {
    case ActionTypes.FETCH_COMPLETED_SUCCESS:
      let newTodos = {};
      action.payload.completedIds.forEach((id) => {
          newTodos[id]: {
              ...state.todos[id],
              completed: true
            }
          })
        })
      return {
        ...state,
        todos: {
             ...state.todos,
             ...newTodos
        }
      };
    default:
      return state;
  }
};


问:
Spring get ServletContext and provide it as a Bean

I want to get the ServletContext in a Java Spring Webproject and use
  it to get the absolute path of my web-application project. I'm still a
  beginner in JavaEE and Spring, so maybe I've got some concepts wrong.
  In the java class, in which I want to use the ServletContext, I got
  only an empty object when using   @Autowired ServletContext context;
  But in my RestConfiguartion class, which extends the
  WebMvcConfigurerAdapter class, I got the ServletContext and I'm able
  to use it in a Java Bean, with the return type of ServletContext. But I
  have no idea, how I can use the Bean in another class to get the
  ServletContext, is this possible?

```<code>@Configuration
@EnableWebMvc
@Import({ ServiceConfiguration.class, SecurityConfiguration.class })
@ComponentScan(basePackages = { "de.rest", "de.security" })
public class RestConfiguration extends WebMvcConfigurerAdapter {

  @Autowired
  ServletContext context;

  @Bean
  public ServletContext getServletContext() {
    System.out.println("*** Context path: *** " + context.getRealPath("/"));
    return context;
  }}
</code>```

答:
You can write

```<code>@Autowired
ServletContext context;
</code>```

In other bean annotated classes too. You'll get the same context.
Because of it, you don't need to specify:

```<code>@Bean
  public ServletContext getServletContext() {
    System.out.println("*** Context path: *** " + context.getRealPath("/"));
    return context;
  }}
</code>```

For example (any class in directories, specified in your annotation @ComponentScan):

```<code>@Bean
class X {
    @Autowired
    ServletContext context;

    ...
}
</code>```

Body:
I want to get the ServletContext in a Java Spring Webproject and use
  it to get the absolute path of my web-application project. I'm still a
  beginner in JavaEE and Spring, so maybe I've got some concepts wrong.
  In the java class, in which I want to use the ServletContext, I got
  only an empty object when using   @Autowired ServletContext context;
  But in my RestConfiguartion class, which extends the
  WebMvcConfigurerAdapter class, I got the ServletContext and I'm able
  to use it in a Java Bean, with the return type of ServletContext. But I
  have no idea, how I can use the Bean in another class to get the
  ServletContext, is this possible?

@Configuration
@EnableWebMvc
@Import({ ServiceConfiguration.class, SecurityConfiguration.class })
@ComponentScan(basePackages = { "de.rest", "de.security" })
public class RestConfiguration extends WebMvcConfigurerAdapter {

  @Autowired
  ServletContext context;

  @Bean
  public ServletContext getServletContext() {
    System.out.println("*** Context path: *** " + context.getRealPath("/"));
    return context;
  }}

Body:
You can write

@Autowired
ServletContext context;

In other bean annotated classes too. You'll get the same context.
Because of it, you don't need to specify:

@Bean
  public ServletContext getServletContext() {
    System.out.println("*** Context path: *** " + context.getRealPath("/"));
    return context;
  }}

For example (any class in directories, specified in your annotation @ComponentScan):

@Bean
class X {
    @Autowired
    ServletContext context;

    ...
}


问:
Firebase CLI: No project is currently active
I'm following this Firebase intro tutorial:

https://codelabs.developers.google.com/codelabs/firebase-web/

I follow the instructions and when I get to step 3, I run firebase use --add and I get the following:

```<code># firebase use --add

> web-start@1.0.0 firebase ~/repos/friendlychat/web-start
> firebase "use"

No project is currently active.

Run firebase use --add to define a new project alias.
</code>```

But if I run firebase list I see this:

```<code>┌──────────────┬───────────────────────┬─────────────┐
│ Name         │ Project ID / Instance │ Permissions │
├──────────────┼───────────────────────┼─────────────┤
│ FriendlyChat │ friendlychat-x3sd0    │ Owner       │
└──────────────┴───────────────────────┴─────────────┘
</code>```

So I am clearly logged in correctly as I can list my projects and have some sort of access to them on the CLI. But does the error mean it's not active? How do I activate it? There is nothing in the tutorial about this.

What am I missing here? Seems like it's something obvious that I'm just not seeing.

答:
I had the same issue and fixed it by running firebase init again.
The file that was missing was the .firebaserc.

The content of this file

```<code>{
   "projects": {
     "default": "yourid"
   }
}
</code>```

hope that helps,
Muki

Body:
I'm following this Firebase intro tutorial:

https://codelabs.developers.google.com/codelabs/firebase-web/

I follow the instructions and when I get to step 3, I run firebase use --add and I get the following:

# firebase use --add

> web-start@1.0.0 firebase ~/repos/friendlychat/web-start
> firebase "use"

No project is currently active.

Run firebase use --add to define a new project alias.

But if I run firebase list I see this:

┌──────────────┬───────────────────────┬─────────────┐
│ Name         │ Project ID / Instance │ Permissions │
├──────────────┼───────────────────────┼─────────────┤
│ FriendlyChat │ friendlychat-x3sd0    │ Owner       │
└──────────────┴───────────────────────┴─────────────┘

So I am clearly logged in correctly as I can list my projects and have some sort of access to them on the CLI. But does the error mean it's not active? How do I activate it? There is nothing in the tutorial about this.

What am I missing here? Seems like it's something obvious that I'm just not seeing.

Body:
I had the same issue and fixed it by running firebase init again.
The file that was missing was the .firebaserc.

The content of this file

{
   "projects": {
     "default": "yourid"
   }
}

hope that helps,
Muki


问:
Dynamically changing a listbox line using VIsual Basic 2015
I was wondering if it is possible to change lines in a Listbox that have only a certain character in it.  For example I have a list of names. I am using Visual Basic 2015

Joe

John

Mike

*Steve

*Tim

Michelle

I would like to make the ones that have the *(or any special character) turn the line Red. I can hard wire in the code exact matches and make it turn red but my listbox will have dynamic information in it so it will be changing all the time.  I am marking the information I would like to highlight the information that has the *.  Thank you for your time.  Here is a small snipet of the generic code I was trying to use.

```<code>    If ListBox1.Items(e.Index).ToString() = "red.txt" Then
        e.Graphics.FillRectangle(Brushes.red, e.Bounds)
    End If

    e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), e.Font, Brushes.Black, New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y))
    e.DrawFocusRectangle()
</code>```

答:
Handle the DrawItem event and paint each item yourself. You must have ListBox1.DrawMode = DrawMode.OwnerDrawFixed

```<code>Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem
    Dim s As ListBox = CType(sender, ListBox)
    If e.Index < 0 Then Exit Sub
    Dim t = s.Items(e.Index).ToString()
    Using g = e.Graphics
        e.DrawBackground()
        If t.Contains("*"c) Then ' your custom condition
            g.FillRectangle(New SolidBrush(Color.Red), e.Bounds)
        End If
        g.DrawString(t, e.Font, New SolidBrush(e.ForeColor), New Point(e.Bounds.X, e.Bounds.Y))
        e.DrawFocusRectangle()
    End Using
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ListBox1.DrawMode = DrawMode.OwnerDrawFixed
End Sub
</code>```

Body:
I was wondering if it is possible to change lines in a Listbox that have only a certain character in it.  For example I have a list of names. I am using Visual Basic 2015

Joe

John

Mike

*Steve

*Tim

Michelle

I would like to make the ones that have the *(or any special character) turn the line Red. I can hard wire in the code exact matches and make it turn red but my listbox will have dynamic information in it so it will be changing all the time.  I am marking the information I would like to highlight the information that has the *.  Thank you for your time.  Here is a small snipet of the generic code I was trying to use.

    If ListBox1.Items(e.Index).ToString() = "red.txt" Then
        e.Graphics.FillRectangle(Brushes.red, e.Bounds)
    End If

    e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), e.Font, Brushes.Black, New System.Drawing.PointF(e.Bounds.X, e.Bounds.Y))
    e.DrawFocusRectangle()

Body:
Handle the DrawItem event and paint each item yourself. You must have ListBox1.DrawMode = DrawMode.OwnerDrawFixed

Private Sub ListBox1_DrawItem(sender As Object, e As DrawItemEventArgs) Handles ListBox1.DrawItem
    Dim s As ListBox = CType(sender, ListBox)
    If e.Index < 0 Then Exit Sub
    Dim t = s.Items(e.Index).ToString()
    Using g = e.Graphics
        e.DrawBackground()
        If t.Contains("*"c) Then ' your custom condition
            g.FillRectangle(New SolidBrush(Color.Red), e.Bounds)
        End If
        g.DrawString(t, e.Font, New SolidBrush(e.ForeColor), New Point(e.Bounds.X, e.Bounds.Y))
        e.DrawFocusRectangle()
    End Using
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ListBox1.DrawMode = DrawMode.OwnerDrawFixed
End Sub


问:
multiple return variables from graphical function in stateflow
I'm using stateflow graphical function and one of my return parameters are not updated after exiting the function.

I'm using matlab as my default code language.

Is it possible to return more than one variable from a graphical function?

What is the correct way for returning more than one parameter from a graphical function?

Thank u

答:
As per the documentation: The syntax for calling a function with multiple outputs is exactly the same as in MATLAB.

There are several examples of doing this in the documentation, including Multi-Output Graphical Function


问:
Loading XML into a browser with jQuery
Does anyone know why the following code does not work in FireFox but does in IE (on the server) and the other way around locally?</p>

```<code>function load_xml(msg) {   //this function will load xml even used in IE or any other browser
            if ( typeof msg == 'string') {
                data = new ActiveXObject( 'Microsoft.XMLDOM');
                data.async = false;
                data.loadXML( msg);
                } else {
                    data = msg;
                }
                return data;
        }

        function getTitle(letter) {
            $('#wordle').html('');
    jQuery.ajax({
        type: "POST",
        url: "wordle-list.dat",
        dataType: ($.browser.msie) ? "text/xml" : "xml",
        success: function(xml) {
                    var xml2 = load_xml(xml);
            var i=0;
            $(xml2).find('wordle').each(function(){
                        $(xml2).find('w').each(function(){ //can change to w:lt(50)
                            var tmpHold = $(this).text();
                            if (tmpHold.substring(0, 1) == letter) {
                                $('#wordle').append('<li class="w">'+$(this).text()+'</li>');
                            }
                        });
                    });
        }
    });
}
</code>```

答:
FOR EVERYONE WONDERING:

It was because I had the file extension as .dat and the server was saying it was a binary mime type...

Title: Loading XML into a browser with jQuery

Body:
Does anyone know why the following code does not work in FireFox but does in IE (on the server) and the other way around locally?

function load_xml(msg) {   //this function will load xml even used in IE or any other browser
            if ( typeof msg == 'string') {
                data = new ActiveXObject( 'Microsoft.XMLDOM');
                data.async = false;
                data.loadXML( msg);
                } else {
                    data = msg;
                }
                return data;
        }

        function getTitle(letter) {
            $('#wordle').html('');
    jQuery.ajax({
        type: "POST",
        url: "wordle-list.dat",
        dataType: ($.browser.msie) ? "text/xml" : "xml",
        success: function(xml) {
                    var xml2 = load_xml(xml);
            var i=0;
            $(xml2).find('wordle').each(function(){
                        $(xml2).find('w').each(function(){ //can change to w:lt(50)
                            var tmpHold = $(this).text();
                            if (tmpHold.substring(0, 1) == letter) {
                                $('#wordle').append('
'+$(this).text()+'
');
                            }
                        });
                    });
        }
    });
}


问:
Install MediaWiki locally with a large DB: "LocalSettings.php" couldn't be generated
I'm trying to install MediaWiki (1.29.1 or 1.27.3) locally with a large Wiktionary dump (3GB).
After converting the xml dump into an sql file and importing the latter into my DB that I create with this script, I followed the MediaWiki installation instructions in the browser to generate my specific "LocalSettings.php". I get the message

There are MediaWiki tables in this database. To upgrade them to MediaWiki 1.29.1, click Continue."

By clicking the "continue" button, the browser stays in loading state forever.

My understanding is that my DB containing the wiktionary dump has some tables that are not compatible with the version of wikimedia that I'm using. Therefore, an update of the DB is required.
I tried to run install.php from the command line to avoid having timeout with the browser. The command didn't return anything (after waiting more than 2 hours).

I tried as well a workaround:

Create my DB with empty Tables

Generate "LocalSettings.php" from the browser (that was fast since the DB is small)

Import the wiki sql dump to my DB

Refresh the index.php page

I got then a blank page with this message

Exception caught inside exception handler.Set $wgShowExceptionDetails
  = true; and $wgShowDBErrorBacktrace = true; at the bottom of LocalSettings.php to show detailed debugging information.

All the examples and tutorials that I found online about this matter are assuming/using a small or new created DB.

Any idea what's wrong? Did really someone tried to use an existing wikimedia dump and run it locally? Why is there no such an advanced example?

答:
The issue in a first level originates from mwdumper which seems to be outdated. An sql DB I generated using mwdumper is missing some tables which should have been though created by running update.php. It was not possible for me to run any php file neither from shell nor from the browser and I suspect the size of the dump to be the cause.

The workaround which by some magic helped to overcome this issue was:

run the update.php from shell with missing db credentials. This somehow enables logs and make the execution of index.php possible through the browser

add manually to the missing table columns claimed in the error messages (the column types here should be respected)

place a LocalSettings.php file, generated easily from a Wiktionary DB with empty tables, in the right directory of the mediawiki installation.

Run index.php from the browser

Et voila! The huge wiktionary mysql dump is queryable now throw the mediawiki interface. Not sure if such a trick could be called a solution but it solved the problem in my case. An explanation for what could have happened in background would be definitely helpful.


问:
Thymeleaf spring loop n item
I am quite new to spring framework.

I try to iterate 10 item in a list. I use thymeleaf template.

This is my code for ;

```<code><li th:each="item,iter : ${list}">
        <span th:if="${iter.index} <=10  " th:text="${item}"/>
</li>
</code>```

This code is not working and I could not find a way to run the code.

Thanks for your interest.

答:
To iterate 10 items in a list. You should:

```<code> <li th:each="item, index : ${yourList}" th:unless="${index.index > 10}"></li>
</code>```

This code works. Send me a comment if it doesn't fit for you.

Title: Thymeleaf spring loop n item

Body:
I am quite new to spring framework.

I try to iterate 10 item in a list. I use thymeleaf template.

This is my code for ;

        <span th:if="${iter.index} <=10  " th:text="${item}"/>

This code is not working and I could not find a way to run the code.

Thanks for your interest.

Body:
To iterate 10 items in a list. You should:

 <li th:each="item, index : ${yourList}" th:unless="${index.index > 10}"></li>

This code works. Send me a comment if it doesn't fit for you.


答:
```<code> if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
</code>```

Your call to alreadyInArr.includes has a ! in front. This reads as so: If NOT(alreadyInarr has a letter CharrsArr[i] within it) then continue:

Which then becomes if the letter is not already in the array then do this.

Since the array  is always empty because you don't push anything to it it will always be true and will never step into the else portion

Title: javascript - missing array

Body:
I need to write a JS function that creates an object from a given string. String characters are object keys. Repeated characters should not be included twice. Values of all keys are zero.

Example: input objFromStr("aaabc") should return {a: 0, b: 0, c: 0}

Here is my solution:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  return charsObj;
}

This solution works as expected, but I don't understand why.
I check chars duplication using alreadyInArr. However when I log my alreadyInArr, it's empty.

So after running this code:

function objFromStr(inStr) {
  let charsArr = inStr.split("");

  console.log("charsArr is:", charsArr);

  let charsObj = {};
  var alreadyInArr = [];

  for (var i = 0; i < charsArr.length; i++) {
    if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }
  }

  console.log("alreadyInArr is:", alreadyInArr);

  return charsObj;
}

console.log(objFromStr("aaabc"));

My output is:

charsArr is: [ 'a', 'a', 'a', 'b', 'c' ]
alreadyInArr is: []
{ a: 0, b: 0, c: 0 }

Can someone explain, why alreadyInArr is empty and yet function still works as expected?

Here's a pen: https://codepen.io/t411tocreate/pen/bYReRj?editors=0012

Body:
 if (!(alreadyInArr.includes(charsArr[i]))) {
      charsObj[charsArr[i]] = 0;
    } else {
      alreadyInArr.push(charsArr[i]);
    }

Your call to alreadyInArr.includes has a ! in front. This reads as so: If NOT(alreadyInarr has a letter CharrsArr[i] within it) then continue:

Which then becomes if the letter is not already in the array then do this.

Since the array  is always empty because you don't push anything to it it will always be true and will never step into the else portion