问:
RESTfully Returning Diagnostics Data With Response
In a REST API I am working with, under certain circumstances (ex/ request originated in network) diagnostics data is returned with the response. Right now, a property is appended to the root object of the response with the diagnostic information (magically by the framework).

For Example:

```<code>{
 "results" : [ ],
 "timestamp" : 1427734909284
}
</code>```

becomes:

```<code> {
  "results" : [ ],
  "timestamp" : 1427734909284,
  "additionalinfo" : [POTENTIALLY A BUNCH OF JSON DATA THAT CAN INCLUDE TIMING,
                      DESCRIPTIONS OR RECOVERABLE ERRORS, AND CODE PATH INFO]
 }
</code>```

This never sat well with me, but right now I am attempting to build some documentation processing into this project, which makes this even more problematic.

Is this the RESTfully correct manner in which to return this data? Should it be a response header instead? Why/Why not?

答:
There are two ways you can view your diagnostic information: part of an existing resource, or a separate resource. How you view it depends on your application requirements.

If the information is part of an existing resource, then you have the most "RESTful" representation possible. Note that REST does not strictly place requirements on the structure of your response objects. Use whatever is convenient. However, this approach may not be compatible with resource caching as your diagnostics may be stale with subsequent requests. If you don't want to cache resources while collecting diagnostics, then great.

If the information is its own resource, then refer to HATEOAS and include a link to the diagnostic resource in your response. This approach requires a way to persist diagnostics on the server. You should also use a REST-compliant JSON format such as HAL JSON if you're concerned about "RESTful" responses.

Sending diagnostics in a response header should the last option to consider. You have to properly encode/decode the data according to the HTTP/1.1 specification. Also, HTTP/1.1 headers are not compressed so your responses will be larger and slower than they would be if the diagnostics were part of the body. There's nothing inherently wrong with it, just more trade-offs to consider.


问:
Why are people making tables with divs?
In modern web development I'm coming across this pattern ever more often. It looks like this:

```<code><div class="table">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>
</code>```

And in CSS there is something like:

```<code>.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }
</code>```

* (Class name are illustrative only; in real life those are normal class names reflecting what the element is about)

I even recently tried doing this myself because... you know, everyone's doing it.

But I still don't get it. Why are we doing this? If you need a table, then just make a blasted
 and be done with it. Yes, even if it's for layout. That's what tables are for - laying out stuff in tabular fashion.

The best explanation that I have is that by now everyone has heard the mantra of "don't use tables for layout", so they follow it blindly. But they still need a table for layout (because nothing else has the expanding capabilities of a table), so they make a
 (because it's not a table!) and then add CSS that makes it a table anyway.

For all the world this looks to me like putting arbitrary unnecessary obstacles in your way and then doing extra work to circumvent them.

The original argument for moving away from tables for layout was that it's hard to modify a tabular layout afterwards. But modifying a "faux-table" layout is just as hard, and for the same reasons. In fact, in practice modifying a layout is always hard, and it's almost never enough to just change the CSS, if you want to do something more serious than minor tweaks. You will need to understand and change HTML structure for serious design changes. And tables don't make the job any harder or easier than divs.

In fact, the only way I see that tables could make a layout difficult to modify, is if you abused them and created an ungodly mess. You can do that with divs too.

So... in an attempt to change this from a rant into a coherent question: what am I missing? What are the actual benefits of using a "faux-table" over a real one?

About the duplicate link: This isn't a suggestion to use another tag or something. This is a question about using a
 vs display:table.

答:
If I can get a little "meta" here, this brings two problems to my mind:

One: Someone proposes a rule for some good reason, and people completely miss the point by following the technical letter of the rule while ignoring the spirit. They find some way to accomplish all the bad things that the rule was trying to prevent, while still technically following the rule as worded.

Two: Someone sees a problem and proposes a rule to prevent it. Others see the value of this rule. Then they insist on blind devotion to this rule without regard to the original problem it was supposed to solve and/or regardless of what other problems it creates. I've had many conversations where someone says, "You must do X because that's the rule", and then I ask, "But why should we do X?", and they look at me with bafflement and exasperation and say,  "But I just told you! Because it's the rule!" I reply, "But it seems to cause more problems than it solves. I think we'd be better off to do Y." And then the person says, "No, look, I'll show you. See, it's right here in this book. X is the rule."

In this case, we have a problem: The table tag does two things: One, it controls the layout of a document. Two, it conveys the idea that the enclosed data is made up of rows and columns of numbers or other data.

So many people proposed the solution: Don't use table tags to control layout of things that aren't logically "tables". Use CSS.

But there's a problem with this solution. The table tag and its subtags do many very useful layout functions that are not easy to achieve using CSS, and when they can be achieved, the code necessary to do it is often cumbersome -- difficult to read and difficult to maintain. Why should we do things in a clumsy, difficult way when there is a clean, easy way?

Personally, I think we would have been better off to just declare, "The fact that something is inside a table tag does not necessarily mean that it represents rows and columns of numbers." This would not have been an outrageous pronouncement. I have never heard someone say that the "p" tag can only be used for things that are really paragraphs of grammatically-correct, logically-constructed English sentences. I've never heard someone say that it is wrong to use a "ul" tag for a list that does, in fact, come in a logical order, just because you wanted bullets and not sequence numbers. Etc.

ContentLicense: CC BY-SA 3.0

Title: Why are people making tables with divs?


问:
is a DoS attack a good analogy of Dining Philosophers?
Let's say that, instead philosophers, we have TCP/IP connections to a server, and instead forks we have the server's TCP/IP avaliable ports. In this scenario, we don't have a lot of connections competing for the ports: we have a few number of malicious connections that will take a lot of time to process, so they will take the awaliable ports and release them after a long time (from some minutes to several hours). In this scenario, actual non-attacking connections will "starve".

In this case, the analogy would be:

avaliable ports: forks

non attacking connections: philosophers that spend more time thinking than eating

attacking or malicious connections: philosophers that spend a lot more time eating than
thinking.

If we ignore the case when every philosopher takes one fork (they deadlock eachother), I consider Dining-Philosophers an example for resource starvation, because if there are no avaliable shared resources, the threads will wait (maybe forever) until a resource is released by another thread.

答:
The more I think about this analogy the less sense it makes.

Ports don't work as a resource here. A server will have only a handful of ports open, perhaps only one (say, port 80 for HTTP). Any number of clients can connect to this and their connections are differentiated by the client port ID (and client IP), which are independent for each client. Port numbers aren't the limited resource that's attacked by DoS attacks, network bandwidth or CPU time or similar things are.

Although network bandwidth and CPU time are, in the end, an integer amount (in the appropriate unit), it is not meaningful to identify these units with forks. Clock cycles or bandwidth is interchangeable, while forks have identity, and the analogy becomes absurd when each philosopher needs 5 million forks. Furthermore, now a philosopher can take, say, one clock cycle and hold onto it for a minute, which is at least more abstract and makes philosopher-time meaningless.

The philosophers have spatial arrangement and choose from the forks around them. In contrast, any reasonable notion of resource in your analogy will not be constrained like this: Any client can get any resource, probably at the discretion of the server rather than by choice of the client.

As you note, there is no potential for deadlocks. The dining philosophers is more about deadlocks (and livelocks) than starvation, though I'm certain some discussion of fairness can be found. Resource starvation is typically discussed with other examples.


问:
How to test model binding within an MVC controller when Bind attribute with Include list is used?
Auto-generated action methods in MVC5 make use of the BindAttribute with an Include list that contains the field names in a string literal.

Example:

```<code>// POST: MyTable/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to,
//   for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Field1, Field2, Field3")] MyEntity myEntity)
{
    ...
}
</code>```

If Field1 is renamed in MyEntity, it will not automatically be updated in the Include list.  If the developer forgets to update the Include lists, the compiler will not complain and the issue might not be discovered until runtime.

I understand that it is common to use view-model classes and a tool such as AutoMapper to map between view-model and domain-model, and it is then easy to create unit tests for those mappings to catch rename errors.

However, if the action method is using the domain-model directly and using a Bind Include list as shown above, is there a way to create a unit test to test the model binding and catch a rename error?

答:
I've worked on and continue to work on large scale api projects and I've never used the BindAttribute. I would say with this code remove it completely, it will still work and it will remove the error prone strings in the attribute.

Personally and from my experiences you shouldn't pass out your data entities from an api endpoint.

We use view models, but call them DataContract, like CarDataContract, HouseDataContract etc. Then as you mentioned we use AutoMapper to map view model to domain model.

From there (as long as you've written it well) you can then test your controllers, the mappings and the domain all in splendid isolation!


问:
REST API, nested routes without providing identifiers at every nested level
Obviously a RESTful API could contain base routes such as:

```<code>api/competitions
api/competitions/{id}
api/teams
api/teams/{id}
api/players
api/players/{id}
</code>```

And nested routes such as:

```<code>api/competitions/{id}/teams
api/competitions/{id}/teams/{id}/players
api/teams/{id}/players
...
</code>```

But what about the following example (Route A):

```<code>api/competitions/{id}/teams/players
</code>```

So all players, for all teams that are in a certain competition?

Q1: Would this contravene REST design?

Q2: Presumably it does, but is there any documentation that explicitly states this? I have done some research and cannot find anything that rules it out as the examples are all very simplistic.

You could implement (Route B):

```<code>api/competitions/{id}/players
</code>```

instead, and then underneath the logic would ensure that the players are not ALL players (as in api/players) but take into account team and therefore competition - so that players that are without a team are excluded.

However, moving away from this simple example to a more abstract model, there might be scenarios where Route B might be more confusing to an API consumer than Route A.

Q3: Would there ever be a justification for implementing a nested route (like Route A) without all identifiers at every level?

答:
No. REST doesn't care about how your organize your resources, only that individual resources are identified by URLs and that resources are discoverable from other resources. If api/competitions/{id}/teams/players makes sense for your application then use it, as long as users can find a link to it.

Roy Fielding's dissertation on Representational State Transfer, specifically sections 5.2.1.1 Resources and Resource Identifiers and 6.2 REST Applied to URI. Also look into HATEOAS (Hypertext as the Engine of Application State).

Yes, if it is both understood by and convenient for users of your application.

REST is a high-level architectural concept. It's not concerned with how you nest your identifiers. That's up to you and your application requirements. Do what makes sense and be obvious about it.


问:
How does StackExchange load data from the server without making an XHR request?
When viewing the questions for a tag on SE networks, every now and then you will get a message at the top:

n questions with new activity.

However the weird thing (to me) is that I don't see any network requests made. How exactly is this accomplished?

答: You're not seeing requests because it's not making any; the page is maintaining an open Web Socket connection to the server, and the updates are being pushed from the server to your browser, rather than downloaded at your browser's request.


问:
Sequencing distributed tasks with a distributed DB

Background

I have two separate processes, WriteIt() and ReadIt().  One creates records, and the other processes the records in a DB cluster.

Once WriteIt() creates a record, it queues a ReadIt() task to process the same record.

To illustrate:

Unfortunately, the database write and replication takes an unreliable amount of time, so ReadIt() has to keep checking for the presence of the updated record, which seems quite inefficient.

Question

This has got to be a common pattern for distributed systems.  So my questions are:

Is there a general term (or terms) for this pattern, so that I can read about how to solve it?  Unfortunately I don't even know what the right terminology is so I've had a heck of a time doing research on Google/SO/Programmers.SE.

(for extra credit) Is there an specific common approach to solving this issue with SQLAlchemy/MySQL and Celery?

I recognize that #2 is pretty specific, so I would be happy with just #1 since I just need to be pointed in the right direction to research the pattern.

答:
Specifically yes the name of the pattern in distributed systems is called eventual consistency.

The common approach is to synchronously write the data to an event store and then write to SQL. Your queued background read job can rest assured that once the data is in the event store, it's a success and won't be lost.

Usually people use a high-performance storage system that is very fast at handling and serialising a lot of concurrent writes for the event store.

A good approach is often called command-query responsibility separation with event sourcing.


问:
What are the key points of Code Complete?
I have heard a lot of people mention Code Complete as a book worthwhile reading. Unfortunately, I am so busy that I don't have time to read it, so can anyone tell me what the key points of the book are?</p>

答:
It's an intermediate book, a potpourri of software development best practices.

If you're a beginning programmer you won't understand a lot of the material, and if you are experienced, the book will only confirm what you already know.  Consequently, the book might be of most value to intermediate programmers, who already have a bit of programming knowledge, but need a book of best practices to tie it all together.

Several pages are spent on how to format code blocks, and the relative merits of each approach.  Personally, I think the great debate on where to put your curly braces is over. (or is it?)

ContentLicense: CC BY-SA 2.5


问:
Using XML to store and edit data records in Java
I want to use XML to store data for an assignment .
In this Java assignment I'll get data from the user in form of lines in a file below

```<code>INSERT INTO student(id,name,family,isMale) VALUES (10,null,”Maryam”, “Hasani”, false)
CREATE TABLE student(id:integer, gpa:decimal, name:string, family:string,isMale:Boolean)
INSERT INTO student(id,gpa,name,family,isMale) VALUES (50,”Ali”, “Hasani”, true)
SELECT id, name FROM student WHERE id=0
so on ..
</code>```

and after reading the file and processing them ,the program will generate logs about the outcome of the input files .like examples below:

```<code>ERROR: Invalid data type for value of column family
ERROR: Invalid table name st
</code>```

my question is about the processing data and storing them. I shouldn't use the usual tools for database like sql as the assignment wants me to somehow do what sql does without sql.
I've chosen XML for this job so after reading the input ;program will parse the data of each line using regex and then store the data in a third file (between output and input files) using XML to have a more organized data.

```<code><student id  = "1" >
   <active>True</active>
   <gpa> 12 </gpa>
   <name> ali </name>
   <family>alavi</name>
   <isMale>True</isMale>
</student>
</code>```

is XML a good choice for what I want?

if it is what parts of XML should I learn for this task as there seems to be a lot to learn?

what things should I note in working with XML and coding the program working with XML file ?

if XML is not suited for this task what are the alternatives ?especially the ones who are easier to learn and work with for someone like me(look at p.s).

p.s:I'm quite new to java and programming as whole

答:
Use XML if your data is a lot more nested and complicated than this.

In this particular case I would suggest using JSON (if you cannot use relational databases as you have mentioned yourself).

As for learning JSON it is very simple. There is nothing to it but learning the structure. Once you got the structure down you can pretty much create any type of data you want.

Here are some references to get started with JSON:

1) http://www.w3schools.com/json/

2) http://json.org/

3) https://code.google.com/p/json-simple/wiki/EncodingExamples


问:
Avoid opt(options) in javascript
A lot of frameworks, most like jQuery plugins uses the "optional" parameter. Basically a dictionary (or key/value structure) with a bunch of additional parameters instead of send in the parameter's function.

As an example:

```<code>function (param1, param2, param3, param4, param4) {

  ...
}
</code>```

Is replaced for:

```<code>function (opts) {
  opts.param1
  opts.param2,
  opts.param3
  ...
}
</code>```

IMO using opt is almost equal to use a lot of parameters in the constructor.
I think is a little hard to maintain the configurations (sometimes) and understand what is inside of it.

Maybe it is for non typecheck of javascript, and the IDES normally doesn't help easily to know what is inside of opt.

But I don't know how to improve the creation of a configurable object.

Someone knows better solution or how to improve the design in this situations?

答:
I would say it depends of the language. In a strongly typed language like Java, pasing a Map<String, Object> means that you risk using the wrong type for a parameter.

That said, I have seen this been used in frameworks like ExtJS and, for some tasks that require lots of parameters (like initialization, configuration) it is worth it. It actually helps, because when building the objects you have the param name right next to the value, instead of having to count which parameter it is in the function argument list and count which parameter you are actually using.

Compare this code

```<code>function createWindow({
  top: 10,
  right: 10,
  width: 100,
  height: 200,
  title: 'My title',
  text: 'My text',
  buttons: [button1, button2],
  borderStyle: myBorderStyle
});
</code>```

to

```<code>function createWindow(
  10,
  10,
  100,
  200,
  `My title`, /* I am sure it is the right order? or is text before title? */
  `My text`,
  null, /* I do not need this param, or the next other 3*/
  null,
  null,
  null,
  [button1, button2],
  null,
  null,
  null,
  myBorderStyle /* This is the 13th or the 12th parameter? */
);
</code>```

Which one is easier to understand?

Additionally, you can use the builder pattern to set parameters in the dictionary, something like

```<code>var conf = {}
setTop(conf, 10);
setRight(conf, 10);
...
</code>```

although IMO you are not improving the first version (and I don't actually see it being used much).

Now, for strongly typed languages, I would use a ConfigurationClass, where each parameter is defined as an attribute and its type is defined, but in JS there is little use for that since, if you write the attribute name wrong, the compiler won't tell you.

Title: Avoid opt(options) in javascript

Body:
I would say it depends of the language. In a strongly typed language like Java, pasing a Map<String, Object> means that you risk using the wrong type for a parameter.

That said, I have seen this been used in frameworks like ExtJS and, for some tasks that require lots of parameters (like initialization, configuration) it is worth it. It actually helps, because when building the objects you have the param name right next to the value, instead of having to count which parameter it is in the function argument list and count which parameter you are actually using.

Compare this code

function createWindow({
  top: 10,
  right: 10,
  width: 100,
  height: 200,
  title: 'My title',
  text: 'My text',
  buttons: [button1, button2],
  borderStyle: myBorderStyle
});

to

function createWindow(
  10,
  10,
  100,
  200,
  `My title`, /* I am sure it is the right order? or is text before title? */
  `My text`,
  null, /* I do not need this param, or the next other 3*/
  null,
  null,
  null,
  [button1, button2],
  null,
  null,
  null,
  myBorderStyle /* This is the 13th or the 12th parameter? */
);

Which one is easier to understand?

Additionally, you can use the builder pattern to set parameters in the dictionary, something like

var conf = {}
setTop(conf, 10);
setRight(conf, 10);
...

although IMO you are not improving the first version (and I don't actually see it being used much).

Now, for strongly typed languages, I would use a ConfigurationClass, where each parameter is defined as an attribute and its type is defined, but in JS there is little use for that since, if you write the attribute name wrong, the compiler won't tell you.


答:
HTML and CSS have evolved a degree of flexibility that means that even conceptually "block" elements like
 (HTML's oldest and most general form of block content) don't need to be displayed as blocks:

div { display: inline; }
```

<p>As you note, <code><div></code> can be repurposed to emulate <code><table></code> and its fellow travelers. Actually, most tags can. Given their special roles, I doubt you could usefully remap macro tags like <code><html></code>,  <code><head></code>, <code><body></code>, and <code><script></code>, but "common" tags like <code><div></code>, <code><p></code>, <code><b></code>, <code><em></code>, <code><span></code>, and <code>```? Up for grabs. Make the inline tags blocks, the blocks inline, the pre-formatted tags flow, the stationary ones float. Go crazy, if you like!

It's possible. You may want to spin a yarn about how we should all use "semantic markup" blah blah blah, or believe with the Pythonistas that "There should be one--and preferably only one--obvious way to do it." Yet Tim Toady is a clever and curious guy. Given a free hand, he'll explore them all. That includes using the available flexibility to make substitutions. Some are wise, some will be proven otherwise. But trial, error, and experience is the only way to find that out. So the sufficient conditions for substitution are present.

I don't think it's overstepping to say that substitution is also necessary. At minimum, it's extremely convenient. For a long time, HTML didn't have <menu>,
, or  elements. Yet web pages and apps everywhere have menus, sections, and sidebars. How? Because HTML list elements (
,
, and
) were easily repurposed and some usages re-classified as menu containers and parts.
 could stand in for
,
, ,
, and . HTML5 has caught up with, and added bespoke elements for, some previously-unaddressed use cases. It's a great update and correction to accommodate common, real-world use.

Even so, there remain a lot of common idioms that don't have bespoke tags or semantic models. Things like pages, footnotes, pull-quotes, comment streams, associated avatars, "likes," subheads, and subtitles that I and many others use every day. What are we to do? What we can. Repurpose "close but inexact" elements with classes and ids to stand in and support our work for the next five or ten or however many years until HTML6 or HTML7 catches up. HTML/CSS's "yes, it's an X, in theory, but we're going to tag it and work with it as a Y" ability is incredibly convenient. Indispensable, really. It makes Web content flex, and not be brittle.

Going even further, "semantic markup" has irreducible limitations. That's true of any kind of rigorous structure you can imagine for content.

Standard formats cannot encompass the entire wealth of human need, desire, and variety. They will always will be "behind the curve" of what people are doing now. How they are innovating. Heck, HTML5 is still behind the curve on footnotes, subheads, and other printing innovations of the 17th century. It lacks features essential to many information workers and content creators. So we improvise.

Even more unchanging is that information doesn't abide by one set of rules. Sure, it starts as a table. But maybe you just want the summary--say the title for each row, as a list. Maybe it takes up too much space, and you'd like it as a space-saving inline list. Maybe you have records you just want the title of, then if you click, you see the underlying details. Or you want items in a complex list or table to be grouped and categorized. Oh, now you want it transposed and categorized a different way. Or the values plotted as a bar chart. These are things done every day in apps, spreadsheets, and data visualization. They are part and parcel of our information landscape, and what we want and need to do on the web. Humans constantly reorganize the form and presentation of our data. It isn't just one thing, or one format/layout, or one concept. It's fungible, with semantics depending on the circumstance and on choices users make interactively. Yes, mark text as "emphasized" (), but that's just a convention. I've worked on documents with at least a half-dozen different kinds of "emphasis." We need to be able to customize and remap that for different uses, different interpretations. One kind of HTML emphasis? Excruciatingly reductionistic. Limiting. Brittle. The same is true for
,
, etc.

It's great to have tags/elements that help organize the entire community's thinking about "what goes where." That helps establish conventions and idioms, and makes us collectively more efficient. But the ability to remap things, to redesignate and repurpose those structures? That's part and parcel of the Web's inclusiveness and its success.

Title: Why are people making tables with divs?

Body:
In modern web development I'm coming across this pattern ever more often. It looks like this:

```<code><div class="table">
    <div class="row">
        <div class="cell"></div>
        <div class="cell"></div>
        <div class="cell"></div>
    </div>
</div>
</code>```

And in CSS there is something like:

```<code>.table { display: table; }
.row { display: table-row; }
.cell { display: table-cell; }
</code>```

* (Class name are illustrative only; in real life those are normal class names reflecting what the element is about)

I even recently tried doing this myself because... you know, everyone's doing it.

But I still don't get it. Why are we doing this? If you need a table, then just make a blasted
 and be done with it. Yes, even if it's for layout. That's what tables are for - laying out stuff in tabular fashion.

The best explanation that I have is that by now everyone has heard the mantra of "don't use tables for layout", so they follow it blindly. But they still need a table for layout (because nothing else has the expanding capabilities of a table), so they make a
 (because it's not a table!) and then add CSS that makes it a table anyway.

For all the world this looks to me like putting arbitrary unnecessary obstacles in your way and then doing extra work to circumvent them.

The original argument for moving away from tables for layout was that it's hard to modify a tabular layout afterwards. But modifying a "faux-table" layout is just as hard, and for the same reasons. In fact, in practice modifying a layout is always hard, and it's almost never enough to just change the CSS, if you want to do something more serious than minor tweaks. You will need to understand and change HTML structure for serious design changes. And tables don't make the job any harder or easier than divs.

In fact, the only way I see that tables could make a layout difficult to modify, is if you abused them and created an ungodly mess. You can do that with divs too.

So... in an attempt to change this from a rant into a coherent question: what am I missing? What are the actual benefits of using a "faux-table" over a real one?

About the duplicate link: This isn't a suggestion to use another tag or something. This is a question about using a
 vs display:table.

Body:
HTML and CSS have evolved a degree of flexibility that means that even conceptually "block" elements like <div> (HTML's oldest and most general form of block content) don't need to be displayed as blocks:

div { display: inline; }

As you note, <div> can be repurposed to emulate <table> and its fellow travelers. Actually, most tags can. Given their special roles, I doubt you could usefully remap macro tags like <html>,  <head>, <body>, and <script>, but "common" tags like <div>, <p>, <b>, <em>, <span>, and <pre>? Up for grabs. Make the inline tags blocks, the blocks inline, the pre-formatted tags flow, the stationary ones float. Go crazy, if you like!

It's possible. You may want to spin a yarn about how we should all use "semantic markup" blah blah blah, or believe with the Pythonistas that "There should be one--and preferably only one--obvious way to do it." Yet Tim Toady is a clever and curious guy. Given a free hand, he'll explore them all. That includes using the available flexibility to make substitutions. Some are wise, some will be proven otherwise. But trial, error, and experience is the only way to find that out. So the sufficient conditions for substitution are present.

I don't think it's overstepping to say that substitution is also necessary. At minimum, it's extremely convenient. For a long time, HTML didn't have <menu>, <section>, or <aside> elements. Yet web pages and apps everywhere have menus, sections, and sidebars. How? Because HTML list elements (<ul>, <ol>, and <li>) were easily repurposed and some usages re-classified as menu containers and parts. <div> could stand in for <article>, <section>, <aside>, <figure>, and <summary>. HTML5 has caught up with, and added bespoke elements for, some previously-unaddressed use cases. It's a great update and correction to accommodate common, real-world use.

Even so, there remain a lot of common idioms that don't have bespoke tags or semantic models. Things like pages, footnotes, pull-quotes, comment streams, associated avatars, "likes," subheads, and subtitles that I and many others use every day. What are we to do? What we can. Repurpose "close but inexact" elements with classes and ids to stand in and support our work for the next five or ten or however many years until HTML6 or HTML7 catches up. HTML/CSS's "yes, it's an X, in theory, but we're going to tag it and work with it as a Y" ability is incredibly convenient. Indispensable, really. It makes Web content flex, and not be brittle.

Going even further, "semantic markup" has irreducible limitations. That's true of any kind of rigorous structure you can imagine for content.

Standard formats cannot encompass the entire wealth of human need, desire, and variety. They will always will be "behind the curve" of what people are doing now. How they are innovating. Heck, HTML5 is still behind the curve on footnotes, subheads, and other printing innovations of the 17th century. It lacks features essential to many information workers and content creators. So we improvise.

Even more unchanging is that information doesn't abide by one set of rules. Sure, it starts as a table. But maybe you just want the summary--say the title for each row, as a list. Maybe it takes up too much space, and you'd like it as a space-saving inline list. Maybe you have records you just want the title of, then if you click, you see the underlying details. Or you want items in a complex list or table to be grouped and categorized. Oh, now you want it transposed and categorized a different way. Or the values plotted as a bar chart. These are things done every day in apps, spreadsheets, and data visualization. They are part and parcel of our information landscape, and what we want and need to do on the web. Humans constantly reorganize the form and presentation of our data. It isn't just one thing, or one format/layout, or one concept. It's fungible, with semantics depending on the circumstance and on choices users make interactively. Yes, mark text as "emphasized" (<em>), but that's just a convention. I've worked on documents with at least a half-dozen different kinds of "emphasis." We need to be able to customize and remap that for different uses, different interpretations. One kind of HTML emphasis? Excruciatingly reductionistic. Limiting. Brittle. The same is true for <table>, <p>, etc.

It's great to have tags/elements that help organize the entire community's thinking about "what goes where." That helps establish conventions and idioms, and makes us collectively more efficient. But the ability to remap things, to redesignate and repurpose those structures? That's part and parcel of the Web's inclusiveness and its success.


答:
One way to fight the large amount of parameters is a builder pattern + fluid interface.

Consider:

```<code>widget = makeWidget(100, 200)
         .withSize(384, 256)
         .withColors(foreground, background)
         .withBorder('solid', 'black', 1)
         .withDialogButtons('OK', 'Cancel', 'Help')
</code>```

This approach groups related sets of parameters so that each set is named and observable, allows to vary the order and omit the parts where default values oar OK.

Title: Avoid opt(options) in javascript

Body:
A lot of frameworks, most like jQuery plugins uses the "optional" parameter. Basically a dictionary (or key/value structure) with a bunch of additional parameters instead of send in the parameter's function.

As an example:

```<code>function (param1, param2, param3, param4, param4) {

  ...
}
</code>```

Is replaced for:

```<code>function (opts) {
  opts.param1
  opts.param2,
  opts.param3
  ...
}
</code>```

IMO using opt is almost equal to use a lot of parameters in the constructor.
I think is a little hard to maintain the configurations (sometimes) and understand what is inside of it.

Maybe it is for non typecheck of javascript, and the IDES normally doesn't help easily to know what is inside of opt.

But I don't know how to improve the creation of a configurable object.

Someone knows better solution or how to improve the design in this situations?

Body:
One way to fight the large amount of parameters is a builder pattern + fluid interface.

Consider:

widget = makeWidget(100, 200)
         .withSize(384, 256)
         .withColors(foreground, background)
         .withBorder('solid', 'black', 1)
         .withDialogButtons('OK', 'Cancel', 'Help')

This approach groups related sets of parameters so that each set is named and observable, allows to vary the order and omit the parts where default values oar OK.


答:
JavaScript does not support parameter defaults for function declarations.

```<code>function foo(x) {
    console.log(x);
}
foo(); // outputs undefined
</code>```

You would have to add extra code per parameter to set the default value.

```<code>function foo(x) {
  if(typeof x === 'undefined') {
    x = 0;
  }
  console.log(x);
}
foo(); // outputs 0
</code>```

This becomes a pain when there are a number of parameters like function foo(param1,param2,param2).

You can quickly define default values using an object as the parameters.

```<code>function foo(opts) {
   opts = $.extend({x:0,y:0,z:0},opts);
   console.log(opts.x);
}
foo(); // outputs 0
</code>```

That's basically why most people use key/value objects to hold parameters.

Title: Avoid opt(options) in javascript

Body:
JavaScript does not support parameter defaults for function declarations.

function foo(x) {
    console.log(x);
}
foo(); // outputs undefined

You would have to add extra code per parameter to set the default value.

function foo(x) {
  if(typeof x === 'undefined') {
    x = 0;
  }
  console.log(x);
}
foo(); // outputs 0

This becomes a pain when there are a number of parameters like function foo(param1,param2,param2).

You can quickly define default values using an object as the parameters.

function foo(opts) {
   opts = $.extend({x:0,y:0,z:0},opts);
   console.log(opts.x);
}
foo(); // outputs 0

That's basically why most people use key/value objects to hold parameters.


问:
As a lone developer, how can I be sure I am learning and doing decent work?
Background: I work in a small (less than 75) person engineering/manufacturing company. I was hired as a developer to work with a single teammate, our purpose being to migrate the company to the modern digital age. My teammate however is not a developer, but instead an industrial engineer, who primarily works on broad ideas, planning, and other non-code related areas. I do all the development.

Problem: I enjoy my work, and it's (shockingly) low stress, probably due to the fact that pretty much no one understands what I do. This includes my boss, he hired me only knowing that he needed someone who can "code". The problem with this is that I am forced to solve every task myself, without any input from colleagues/seniors. I am very good at what I do, but also quite young (haven't even started college yet), and so I would have seriously benefited from having seniors to teach and correct me. Unfortunately this isn't possible at the current time, so I'm stuck doing everything my way and hoping it works out.

This works I suppose, except I have no way to know if I am doing things in a terrible fashion that will eventually cost me months of rework time. Am I doing things efficiently? And although I haven't run into this yet, what if I really just can't figure out a problem that blocks our project? I can't hand it off! And what about when I leave? What if the next developer grows to curse my very being because of what lays before his eyes? :)

These questions worry me quite frequently, and it brings me to my question:

As a lone developer, what can/should I do to make sure I am learning, and producing efficient, maintainable, and proper (near bug free) code. How can I do things like:

review my own code

review my own designs

etc.

EDIT:

My question is similar but not a duplicate of Can a lone programmer become a mid or senior level programmer without a mentor?, that question is about "ranking up" as an individual programmer, I am asking how I can make sure I am learning and doing things properly without any other technical oversight.

答:
In my personal experience:

Read open source code sounds great, but most of us rarely have the bandwidth to dive into projects. Especially with the kind of time that a project deserves. Without that kind of time one cannot always appreciate the whys behind the way code was written.

What i do now is- i pick up only modules of open source projects as a reference than starting from the beginning. Coding python and want to see how pros do logging or config? Pick up a project you have used. That familiarity fends off exhaustion. For me it was Graphite's carbon daemon.

While good mentors are good, bad ones are really bad.

It is actually a rather freeing being a lone developer, as you get to pick your influences. They can be the best in the world. If you are the only dev, the job is most probably not as stressful as one in which the fastest coding monkey gets the banana. Pick up Code complete 2, The unix programming environment, 97 things every programmer should know. You are your limit. This can be both liberating and intimidating.

A "xyz best practices" on stackoverflow combined with the top five on a google-search is for most practical cases- better than any mentor around you.

It is more common to find bad mentors than good ones. And even the good ones won't be the utter best at everything across the board. They will have their limitations, biases. Top voted answers would not. Make it a point to subscribe to the Newsletters of code-review and programmers.se. And if you can afford to go through the comments on relevant threads on HackerNews, i don't think any team of mentors can beat this.

Low energy barrier to newer tools.

You don't have to convince a team to move from svn to git. Stick around HN and you can be as good as good gets.

All said, your biggest obstacle is the size of your project. As rightly mentioned in answers above, you have to write bad code. You arrive at good coding practices.

Things i could never make-up-for:

In teams that pivot frequently because of the mgt, the code itself is revelatory in the sense that you can eventually see what's wrong. When you have-to bend your code for different use-cases, you 'see' what breaks. In general programming with fixed requirements, this flexibility is rarely demanded which allows room for hardcoding, bad design, a short sighted procedural approach.

OwnerDisplayName: Josiah


问:
Pass the whole object to a method or just parts?
I have an object that has about 50 properties, but one of my methods only uses about 3 of these properties.  Is it still better to pass the whole object or parts.  A scenario would be were I am using Dapper to query a database to map data into a POCO object, but I only need a few of the properties, so I am faced with these two scenarios:

```<code>var car = db.Query<Car>("SELECT * FROM Car Where Id = @Id", new {Id}).FirstOrDefault();

Process(car);
</code>```

Or

```<code>var car = db.Query<car>("SELECT VIN, Year, Color FROM Car Where Id = @Id", new {Id}).FirstOrDefault();

Process(car.VIN, car.Year, car.Color);
</code>```

In the above case, does the fact that I am using Dapper matter? I know the less properties it has to map to the less time it takes.  But at the same time, by only bringing back a set of properties, if I ever need something else, I will have to modify the query or add a new method to bring back what I want.

答:
It sounds like you have a good grasp of the issues involved. I don't know specifically whether Dapper makes a difference in your strategy, but in general you only want to return the data from the database that you need.

Will you have to alter your query if you need another property in the future? Of course, and that's the downside of returning only what you need. Whether excluding the unused data makes a difference in your application depends largely on scale. At web scale, companies like Twitter, Facebook, and Google go to great lengths to optimize everything, and excluding unused data from a query is a standard optimization.

As for the Process() call, you are better off passing the car object:

```<code>Process(car);
</code>```

but you need to be able to do that with the optimized query:

```<code>var car = db.Query<car>("SELECT VIN, Year, Color FROM Car Where Id = @Id", new {Id}).FirstOrDefault();
</code>```

Then your method signature doesn't need to change. When you need a new property, you just add it to the query string.

Body:
It sounds like you have a good grasp of the issues involved. I don't know specifically whether Dapper makes a difference in your strategy, but in general you only want to return the data from the database that you need.

Will you have to alter your query if you need another property in the future? Of course, and that's the downside of returning only what you need. Whether excluding the unused data makes a difference in your application depends largely on scale. At web scale, companies like Twitter, Facebook, and Google go to great lengths to optimize everything, and excluding unused data from a query is a standard optimization.

As for the Process() call, you are better off passing the car object:

Process(car);

but you need to be able to do that with the optimized query:

var car = db.Query<car>("SELECT VIN, Year, Color FROM Car Where Id = @Id", new {Id}).FirstOrDefault();

Then your method signature doesn't need to change. When you need a new property, you just add it to the query string.


答:
I have an object that has about 50 properties,

Stop! Go - right now - and fix this.

Of course you're going to run into functions that only use part of your object, when your object is doing everything under the sun. No object needs 50 independent properties. Certainly some of them can be organized into sub-objects. Those three that your function takes are a good candidate set.

should I pass the whole object to a function or just parts?

In the more general case, it depends. Best practices say to pass in just what you need. Best practices also say to code to an interface (in this case, the signature of the method). So this is one of those cases where you need to weigh the two best practices against the likelihood that they will come into play.

Does the method make sense to take the whole thing (since you might use other parts later)? Does the method make sense to the parts and not care that they are from independent sources?

And the other consideration is similar to the above advice: if you often find yourself taking bits from an object, it is a sign that those bits are their own cohesive object. Consider making them their own sub-object, or otherwise divvying up responsibilities to better align with how you're actually using the stuff.

Also, this answer is specifically about functions. If you're working across communication boundaries, you will often want to/need to cut down your data size. Sending 50 fields across the wire when you only need 3 is more troublesome there.

Title: Pass the whole object to a method or just parts?

Body:
I have an object that has about 50 properties, but one of my methods only uses about 3 of these properties.  Is it still better to pass the whole object or parts.  A scenario would be were I am using Dapper to query a database to map data into a POCO object, but I only need a few of the properties, so I am faced with these two scenarios:

```<code>var car = db.Query<Car>("SELECT * FROM Car Where Id = @Id", new {Id}).FirstOrDefault();

Process(car);
</code>```

Or

```<code>var car = db.Query<car>("SELECT VIN, Year, Color FROM Car Where Id = @Id", new {Id}).FirstOrDefault();

Process(car.VIN, car.Year, car.Color);
</code>```

In the above case, does the fact that I am using Dapper matter? I know the less properties it has to map to the less time it takes.  But at the same time, by only bringing back a set of properties, if I ever need something else, I will have to modify the query or add a new method to bring back what I want.


答: Pass a whole object, but, select from databse only that fields that you eally need. You will get object with three filled properties, and others properties will get defaults. Such way it will be simplier to fill other properties with data just by adding field name to query, without changing method's signature.</p>


问:
Creating algorithms
I am a relatively new programmer. I can pick up languages and learn syntax at a speed that I consider good, but I can't figure out how to solve problems logically using algorithms very well. I know about the proper steps that we are taught in Comp Sci, but a lot of my friends are just spitting out algorithms. Have any of you had this problem? If so, how did you overcome it? Are there any exercises that I could do to improve my skills?</p>

答: A coworker of mine always says that if you can draw it you can program it. I think there is a lot of truth to that. I usually draw out a very specific case (on paper) and try to generalize from there gradually. I find it more challenging to know if I can actually do something as opposed to how since there is a lot of resources out there on the how. Also you don't have to reinvent the wheel for every task either, just use tired and true methods to simplify your problems. And find some enjoyment in the challenge of problem solving since whether you spit out algorithms or not you still have to solve problems everyday that you will not instantly know the answers to (or you may have many competing answers and you wont know which is the best one). I am honestly in a state of partial confusion everyday but I really enjoy the challenge and I would be somewhat bored otherwise. The field is so wast that there is no way any one person is an expert on everything. Good luck and don't get discouraged by not knowing things - just ask or research it.</p>

Title: Creating algorithms


问:
What features would you like to have in PHP?
Since it's the holiday season now and everybody's making wishes, I wonder - which language features you would wish PHP would have added? I am interested in some practical suggestions/wishes for the language. By practical I mean:

Something that can be practically done (not: "I wish PHP would guess what my code means and fix bugs for me" or "I wish any code would execute under 5ms")

Something that doesn't require changing PHP into another language (not: "I wish they'd drop $ signs and use space instead of braces" or "I wish PHP were compiled, statically typed and had # in it's name")

Something that would not require breaking all the existing code (not: "Let's rename 500 functions and change parameter order for them")

Something that does change the language or some interesting aspect of it (not: "I wish there was extension to support for XYZ protocol" or "I wish bug #12345 were finally fixed")

Something that is more than a rant (not: "I wish PHP wouldn't suck so badly")

Anybody has any good wishes?

Mod edit: Stanislav Malyshev is a core PHP developer.

答:
I wouldn't mind named parameters.

```<code>getData(0, 10, filter => NULL, cache => true, removeDups => true);
// instead of:
getData(0, 10, NULL, true, true);

// or how about:
img(src => 'blah.jpg', alt => 'an albino platypus', title => 'Yowza!');
</code>```

Unfortunately the PHP devs shot that idea down already.

Body:
I wouldn't mind named parameters.

getData(0, 10, filter => NULL, cache => true, removeDups => true);
// instead of:
getData(0, 10, NULL, true, true);

// or how about:
img(src => 'blah.jpg', alt => 'an albino platypus', title => 'Yowza!');

Unfortunately the PHP devs shot that idea down already.


问:
Is it possible to implement a robust 2 node P2P protocol?
I am thinking about how to implement a P2P protocol with only two nodes.

At first I read about different DHT implementations in the hope that this scenario would be feasible. Turns out most intrinsically expect more than a few nodes to be effective.

Thinking about this naively gives me the following challenges:

Where would the nodes look to find each other during bootstrapping?

What about NAT traversal and other network nasties?

Has anyone succeeded with this?

答:
Basically, it can't be done efficiently.

Most P2P networks rely on seeding information (lists of existing nodes it can try to connect to). I take it from your question that you want to a solution that doesn't require seeding information to be given to the nodes.

Without seeding information, nodes in P2P networks are limited to trying random addresses. This can work successfully if (A) the number of P2P nodes in the network is large and (B) many/most nodes have the ability to accept incoming connections (i.e., are not behind NAT).

For 2 nodes on IPv4, this will mean billions of packets sent before they discover each other, if one of them can accept inbound connections.

If neither can accept inbound connections, they must attempt to connect to each other simultaneously to achieve nat traversal. The chance of success is only about one in 2^64 per attempt. This is since they each have to guess the other's address correctly. This is simply not going to work.

Obviously, everything gets harder with IPv6.


问:
How often is software speed evident in the eyes of customers?
In theory, customers should be able to feel the software performance improvements from first-hand experience.

In practice, sometimes the improvements are not noticible enough, such that in order to monetize from the improvements, it is necessary to use quotable performance figures in marketing in order to attract customers.

We already know the difference between perceived performance (GUI latency, etc) and server-side performance (machines, networks, infrastructure, etc).

How often is it that programmers need to go the extra length to "write up" performance analyses for which the audience is not fellow programmers, but managers and customers?

答:
It depends who you are selling your software product to.

More often then not, your customer is not the end /day to day user. So often you end up with making more nice and shiny reports instead of fixing performance issues. Because  really you're selling to management, not end user.

Which means in that case, you will be hard pressed to mark up for some performance issues but will make top dollar on automating that report.


问:
Which things instantly ring alarm bells when looking at code?
I attended a software craftsmanship event a couple of weeks ago and one of the comments made was "I'm sure we all recognize bad code when we see it" and everyone nodded sagely without further discussion.

This sort of thing always worries me as there's that truism that everyone thinks they're an above average driver. Although I think I can recognize bad code I'd love to learn more about what other people consider to be code smells as it's rarely discussed in detail on people's blogs and only in a handful of books. In particular I think it'd be interesting to hear about anything that's a code smell in one language but not another.

I'll start off with an easy one:

Code in source control that has a high proportion of commented out
  code - why is it there? was it meant
  to be deleted? is it a half finished
  piece of work? maybe it shouldn't have
  been commented out and was only done
  when someone was testing something
  out? Personally I find this sort of
  thing really annoying even if it's just the odd line here and there, but when you see large blocks interspersed with the rest of the code it's totally unacceptable. It's
  also usually an indication that the rest of
  the code is likely to be of dubious
  quality as well.

答:
Sometimes I see parts of a method that given all possible inputs, it would still NEVER run, so it shouldn't be there confusing people in the first place.
An example would be...

If the method can only be called inside the context of an Admin superuser and I see something checking if the request user is not an Admin superuser... :/


问:
Is it a acceptable approach to put try catch wherever null pointer exception occurs?
There are instances where the references to objects, fields, variables etc can be null and there might be a possible occurrence of Null Pointer exception occurring at that point.

Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

答:
Is is a permanent solution to put these code blocks which expect Null ponter exception to be put in a try catch block?

This sounds like the anti-pattern of using exceptions for control flow (specifically, null pointer exceptions).

So, no, it is not good programming practice to do this. When possible, your code should avoid raising a null pointer exception, and use break/return for control flow instead.

The only exception is when interfacing with a library that non-deterministially raises a null pointer exception to signal a certain type of error. In this case, the library is an example of the anti-pattern, and the only thing you can do is catch the exception, of course.


问:
Server and Client apps that will send files and other info to each other
I am trying to do a Server and Client programs, that will communicate with each other, but I can't figure out the best way to do it, so let me explain what I need:

The Server app should be able to accept both files and other info (like string arrays, if possible) from the client app.

The client app must be able to receive commands from the Server app (like SEND_REPORT, STOP_SELF....)

The whole server-client communication should be direct

I have tried using a FTP server for that, but it requires a third party program for that to work (unless I make my Server app a FTP server itself).
So now I am trying to do it with TcpClient and NetworkStream, but I figured out there would be no way to distinguish if the sent info is a file, or a simple string array.

Here is what I have so far, the server side code:

```<code>private void handleClient(TcpClient client) {
        NetworkStream stream = client.GetStream();
        stream.WriteByte(1);
        FileStream fileStream = File.Open(le_path, FileMode.Create);
        int read;
        int totalRead = 0;
        byte[] buffer = new byte[1024];
        while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) {
            fileStream.Write(buffer, 0, read);
            totalRead += read;
        }
        fileStream.Dispose();
        client.Close();
    }
</code>```

This code does create a file, but it is bugged, or I don't know, it never leaves the while loop and never goes to Dispose and Close... I can access the file, when I close the program.

Here is the client app code:

```<code>client = new TcpClient();
client.Connect(serverIP, serverPort);
byte[] file = File.ReadAllBytes(Constants.TARGET_PATH_LOGS + "squad.jpg");
byte[] fileBuffer = new byte[file.Length];
NetworkStream stream = client.GetStream();
stream.Write(file, 0, fileBuffer.GetLength(0));
</code>```

So here is what I am asking you:

If this is the best way to do it, how can I make the receive code recognizes if it's a file that is sent, or a simple array list data, and how do I make it able to accept any file (meaning to properly get it's name, metadata...)

If not, please tell me another way to do what I need.

答:
You need to close the connection stream from your client. The server's while loop will not exit until the client closes the connection.

As for your question regarding how will you know what is your client sending, you could use an initial series of bytes to denote what you are sending. So if you send 0x00, you are sending a file, if you send 0x01, you are sending an array list, and so on.

For the first point, you could do it like so:

```<code>using NetworkStream stream = client.GetStream()
    stream.Write(file, 0, fileBuffer.GetLength(0));
</code>```

For the second, you could try something like so (NOTE: This code is not compiled, but it should point you in the right direction):

```<code>byte[] transType = new byte[] {(byte)0};   //Assuming that 0 means you are sending a file.
byte[] file = File.ReadAllBytes(Constants.TARGET_PATH_LOGS + "squad.jpg");
byte[] transData = new byte[transType.Length + file.Length]
transType.CopyTo(transData, 0);

file.CopyTo(transData, tansType.Length);
byte[] fileBuffer = new byte[file.Length];
using NetworkStream stream = client.GetStream()
        stream.Write(file, 0, fileBuffer.GetLength(0));
</code>```

In your server:

```<code>bool isFirst = true;
TransmissionType transmissionType = TransmissionType.Unknown;   //This is an enumeration you can create.

while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
    if(isFirst)
    {
        isFirst = false;
        byte transType = buffer[0];
        switch(transType)
        {
            case (byte)0:
            {
                transmissionType = TransmissionType.File;
                byte[] bufferToWrite = new byte[buffer.Length - 1];
                Array.Copy(buffer, 1, bufferToWrite, bufferToWrite.Length);
                fileStream.Write(bufferToWrite, 0, read);
                totalRead += read;
                continue;
            }
            ... //Other Cases
        }
    }

    switch(transmissionType)
    {
        case TransmissionType.File :
        {
            fileStream.Write(buffer, 0, read);
            totalRead += read;
            break;
        }
    }
}
</code>```

Body:
You need to close the connection stream from your client. The server's while loop will not exit until the client closes the connection.

As for your question regarding how will you know what is your client sending, you could use an initial series of bytes to denote what you are sending. So if you send 0x00, you are sending a file, if you send 0x01, you are sending an array list, and so on.

For the first point, you could do it like so:

using NetworkStream stream = client.GetStream()
    stream.Write(file, 0, fileBuffer.GetLength(0));

For the second, you could try something like so (NOTE: This code is not compiled, but it should point you in the right direction):

byte[] transType = new byte[] {(byte)0};   //Assuming that 0 means you are sending a file.
byte[] file = File.ReadAllBytes(Constants.TARGET_PATH_LOGS + "squad.jpg");
byte[] transData = new byte[transType.Length + file.Length]
transType.CopyTo(transData, 0);

file.CopyTo(transData, tansType.Length);
byte[] fileBuffer = new byte[file.Length];
using NetworkStream stream = client.GetStream()
        stream.Write(file, 0, fileBuffer.GetLength(0));

In your server:

bool isFirst = true;
TransmissionType transmissionType = TransmissionType.Unknown;   //This is an enumeration you can create.

while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
    if(isFirst)
    {
        isFirst = false;
        byte transType = buffer[0];
        switch(transType)
        {
            case (byte)0:
            {
                transmissionType = TransmissionType.File;
                byte[] bufferToWrite = new byte[buffer.Length - 1];
                Array.Copy(buffer, 1, bufferToWrite, bufferToWrite.Length);
                fileStream.Write(bufferToWrite, 0, read);
                totalRead += read;
                continue;
            }
            ... //Other Cases
        }
    }

    switch(transmissionType)
    {
        case TransmissionType.File :
        {
            fileStream.Write(buffer, 0, read);
            totalRead += read;
            break;
        }
    }
}


问:
Do designer tools degrade the programming experience?
I've been looking around lately, specifically at some of the MS tools that are available, and I'm noticing a big focus on designer tools and wizards. Not just for UI development but for everything.

Entity Framework has the modeller

RIA Services has the DomainService wizard(s)

Workflow has the whole workflow designer thingy... (I don't know, haven't really used it)

There's more, but I think you get the idea. There's lots of designer tools. Using some of these I find that:

They complicate matters beyond the prescribed use cases

(ie all of the tech demo videos)

I have been evaluating some of these technologies recently, and trying to work with them I end up having to dissect exactly what the designers, modellers and wizards are doing for me... otherwise I'm lost when I actually have to try to do something with whatever was created.

This ends up being a case where I have to fight the tool, or fight its output enough such that I could have just done the whole thing myself without it - and had a much stronger understanding of what's going on. I find this particularly infuriating with the silverlight designer and RIA services domain service wizard.

I find myself asking "What good is this tool if I have to figure out its inner workings or re-write half of its output in order to use it?"

They're not as fast

The selling point of these tools is to increase productivity and this point may change over time using the tool, and doesn't necessarily apply to UI designers (though, in some cases it still does -> I'm looking at you silverlight designer). I find that I can hack some code much faster than I can drag-and-drop, resize, move, whatever in a designer.

The UI gets in the way of the model

Maybe this is just me, but when I am using anything reminiscent of a UML design tool I end up spending more time laying everything out so that my lines don't cross and so that I can see it all on the screen than modelling what I'm trying to achieve.

They're no fun

Half of the reason that I code for a living is that I enjoy it. Clicking checkboxes and selecting comboboxes and then fixing everything that comes out isn't fun.

I don't appear to be alone

The community seems to not want these tools either. The best example I can think of at the moment is Entity Framework Code-First.

So I ask:

Do designer tools actually improve productivity?

Are they fun-killers?

Is 'the community' actually asking for more designer tools, or are vendors just thinking we are?

答:
as usual, it depends

When I first investigated using web services, Java had a 50-page tutorial and .NET had a wizard. Guess which one got used?


问:
PHP Composer vendors licensing
I'm using a composer as a dependency manager for my PHP project. Composer operates as a library, which uses packagist as a software repository to fetch third-party dependencies.

I'm interested, whether usage of third-party library is counted as dynamic linking or so.
Third-rd party libraries are not present in source code by themselves, but are fetched during the deployment of application (much similar as usual software repository). They are required to application to work properly.

To be more certain, given I've forked AGPLv3 project (composer not used before). Can I just use composer with it or should I check that all dependencies are recursively compatible with given project license?

答:
This is a hotly disputed aspect of software licensing.

One interpretation is that, if you are not -distributing- a library, you do not need a license, nor do you need to accept or comply with any terms attached to use of the library (with the caveat that you might still have to accept terms to do any meaningful testing of your program).

By this interpretation, a non-free program could dynamically fetch GPL'd code from the internet, dynamically link with it, and execute the result.

Needless to say, you're in better shape if you just comply with licenses or write your own.

Title: PHP Composer vendors licensing


问:
PHP: is read file at every page load too heavy?
In F3 Framework Controller I wrote a function checking whether MySql data are saved in a file, otherwise loading a form to ask users for that data (similar to Wordpress Installation).

This function is loaded every time that a page / method is called:

```<code>abstract class Controller
{

    /* F3 */
    protected $f3;
    protected $file_configuration = 'setup.cfg';

    function __construct()
    {
        $f3 = Base::instance();
        $this->f3 = $f3;
        $this->setDatabase();
        $this->setup();
    }
}
</code>```

and setDatabase() is a simple:

```<code>private function setDatabase()
    {
        $search = 'TEST';
        $file = $this->file_configuration;
        // Read from file
        $lines = file('app/config/'.$file);
        $found = false;
        foreach($lines as $line)
        {
            // Check if the line contains the string we're looking for, and print if it does
            if(strpos($line, $search) !== false)
            {
                $found = true;
            }
        }
        if ($found===false)
        {
            $fh = fopen('app/config/'.$file, 'a') or die("can't open file");
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 1";
            fwrite($fh, $stringData);
            $stringData = "\n";
            fwrite($fh, $stringData);
            $stringData = "New Stuff 2";
            fwrite($fh, $stringData);
            fclose($fh);
        }
    }
</code>```

(Please don't see the values of variables... only test at the moment) ;-)

My question is:

Others classes start extending Controller, will I put too much strain on my server reading every time the file?

Can you hint me a best approach?

Imagine wordpress: I think that every time you call the page, it checks if database exists / is properly configured, otherwise stop / ask for insert connection data (username, password, etc)

答:
This approach is normal, but if you are aware of performance loss, you have to implement some Cache layer between this configuration file and controller.

This simple example looks like (pseudo-code, not sure for correct php)

public function setupConfig() {

    if (is_file('db_config.cache')) {
       $this->setConfig(unserialize(file_get_contents('db_config.cache')));
       return;
    }

    if (is_file('db_config.ini')) {
       $configContent = file_get_contents('db_config.ini');
       if ( null !== ($config = $this->parseConfig($configContent))) {
          $this->setConfig($config);
          file_put_contents('db_config.cache', serialize($config));
          return;
       }
    }

    // ...
    // Ask for config data from user here or set default values or something else

}
```


问:
Selecting between multiple actions in PHP
I have been programming for a number of years now and in PHP for about 4 of those years. I have always wondered what is the best approach when it comes your program deciding what action to take based on a user action.

Let me narrow this down a little bit. I have a small custom built CMS running, one of the pages allows an admin to view and edit user account details such as name, generate a new password, change payment dates and so on.

I have a number of different actions here:

View all users

View single user

View users (search string)

Edit user

Edit Subscription

Edit Name

Etc

Delete User

Blacklist

For all of these actions i provide a let with GET data, for exampele:

```<code>User A
</code>```

The links for the other things like editing a user would be "action=edit_subscription" for example.

When My page loads i usually use an IF ELSE statement to check if an action is present before doing on.

```<code>if($_GET['action'] == "show_user"){
}
else if($_GET['action'] == "edit_subscription"){
}
</code>```

Once the program matches the action it checks for other data such as UID and then sends that data off into a classes to be processed. Sometimes this can feel a little long winded and can be a little difficult to debug.

I don't know if this is the best way of doing it, i was recently looking into using a switch statement and wondered if this would be better but I'm not sure if it.

So if there a better way for me to achieve this selection process, maybe some sort of pattern that can be used?

Once last point is that i am trying to keep everything in once file (apart from classes) so the HTML and the PHP for matching actions are all in the same .php file, also not 100% sure if this is best practice as well.

Thanks for your time.

答:
I think, you are looking for the Routing component for your code. The code I linked is rather individual code library used and provided by Symfony2 framework.

You could inspect approaches it uses to configure and determine routes and controllers for them.

Body:
I have been programming for a number of years now and in PHP for about 4 of those years. I have always wondered what is the best approach when it comes your program deciding what action to take based on a user action.

Let me narrow this down a little bit. I have a small custom built CMS running, one of the pages allows an admin to view and edit user account details such as name, generate a new password, change payment dates and so on.

I have a number of different actions here:

View all users

View single user

View users (search string)

Edit user

Edit Subscription

Edit Name

Etc

Delete User

Blacklist

For all of these actions i provide a let with GET data, for exampele:

```<code><a href="users.php?action=show_user&uid=12">User A</a>
</code>```

The links for the other things like editing a user would be "action=edit_subscription" for example.

When My page loads i usually use an IF ELSE statement to check if an action is present before doing on.

```<code>if($_GET['action'] == "show_user"){
}
else if($_GET['action'] == "edit_subscription"){
}
</code>```

Once the program matches the action it checks for other data such as UID and then sends that data off into a classes to be processed. Sometimes this can feel a little long winded and can be a little difficult to debug.

I don't know if this is the best way of doing it, i was recently looking into using a switch statement and wondered if this would be better but I'm not sure if it.

So if there a better way for me to achieve this selection process, maybe some sort of pattern that can be used?

Once last point is that i am trying to keep everything in once file (apart from classes) so the HTML and the PHP for matching actions are all in the same .php file, also not 100% sure if this is best practice as well.

Thanks for your time.


问:
What kind of base for Decorator: interface, abstract class, non-abstract
What should be at the top of inheritance tree of Decorator design pattern?
I mean the base for both components and decorators

non-abstract class: has data fields, implements methods

abstract class: has data fields, has only abstract (pure virtual) methods

interface: no data fields, has only abstract (pure virtual) methods

abstract class & interface: interface is the base for decorator, abstract class is the base for decorated components

Simple example

IText - interface declares getContent() method

AbstractText - abstract class  declares getContent() method and defines txt data
field

Text - non-abstract class, general, can be also used as base for other classes

HelloWorld  - non-abstract class, more specific than Text

HelloSomeone  - non-abstract class, extends Text with the data field name

Decorator abstract class for decorators (might be redundant?)

PrefixDecorator decorator class prefixes  getContent() with a string prefix

SuffixDecorator decorator class suffixes  getContent() with a string suffix

getContent() method that should return txt with optional additional data (suffixes and prefixes from decorators, name field in the HelloSomeone class)

What base class should be chosen?

non-abstract class

abstract class

interface

abstract class & interface

Code for last example

```<code>#include <iostream>
#include <string>
using namespace std;

/* Base for decorator & abstract: no fields, getContent()  is pure virtual */
class IText {
public:
    virtual string getContent() = 0;
    virtual ~IText() { }
};

/* Base: has a field, getContent()  is pure virtual */
class AbstractText : public IText {
protected:
    string txt;
public:
    virtual ~AbstractText() { cout << " AbstractText dtor" << endl; }
    AbstractText(string t = "...") : txt(t) { }
    virtual string getContent() = 0;
};

/* Concrete, general */
class Text : public AbstractText {
public:
    virtual ~Text() { cout << " Text dtor" << endl; }
    Text(string t) : AbstractText(t) { }
    virtual string getContent() { return txt; }
};

/* Concrete, more specific */
class HelloWorld : public AbstractText {
public:
    virtual ~HelloWorld() { cout << " HelloWorld dtor" << endl; }
    HelloWorld() : AbstractText("Hello world") {}
    virtual string getContent() { return txt; }
};

/* Additional field */
class HelloSomeone : public AbstractText {
private:
    string name;
public:
    virtual ~HelloSomeone() { cout << " HelloSomeone dtor" << endl; }
    HelloSomeone(string n) : AbstractText("Hello, "), name(n) { }
    string getContent() { return (txt + name + "!"); }
};

class Decorator : public IText {
public:
    virtual string getContent() = 0;
    virtual ~Decorator() { cout << " Decorator dtor" << endl; }
};

class PrefixDecorator : public Decorator {
private:
    IText *t;
public:
    PrefixDecorator(IText *te)  { t = te; }
    virtual ~PrefixDecorator() { cout << " PrefixDecorator dtor" << endl; delete t; }
    virtual string getContent() { return "---" + t->getContent(); }
};

class SuffixDecorator : public Decorator {
private:
    IText *t;
public:
    SuffixDecorator(IText *te)  { t = te; }
    virtual ~SuffixDecorator() { cout << " SuffixDecorator dtor" << endl; delete t; }
    virtual string getContent() { return t->getContent() + "---"; }
};

int main() {
    IText *t = new Text("some text");
    IText *hw = new HelloWorld();
    IText *hs = new HelloSomeone("Mark");
    cout << t->getContent() << endl;
    cout << hw->getContent() << endl;
    cout << hs->getContent() << endl;
    t = new PrefixDecorator(t);
    hw = new PrefixDecorator(hw);
    hw = new SuffixDecorator(hw);
    cout << t->getContent() << endl;
    cout << hw->getContent() << endl;
    cout << "DELETE Text" << endl;
    delete t;
    cout << "DELETE Helloworld" << endl;
    delete hw;
    cout << "DELETE HelloSomeone" << endl;
    delete hs;
}
</code>```

答:
It depends entirely on what you want.  These variations exist for your convenience, not because one way is a better way than another.

Personally I'm partial to the non-abstract class, because it requires the fewest number of classes, which in my opinion is always a plus.  However, you may find yourself in the situation in which there is an AbstractText class or IText and an Text implementation, in which case you may model your Decorator pattern accordingly.

If you do decide to choose the non-abstract class variation, it is probably the easiest to adapt into the other variations later since it is usually easier to add classes than to remove them, so I would give the non-abstract class variation a try.


问:
Deciding factors in pair programming
Are there specific things that you look out for before getting the team into pair programming? Obviously pairing someone who's great with C++ with another who knows ASP.NET best won't get me far, but how about someone who's great with C++ with another who knows Java best but can pick up C++ quick enough? </p>

<p>What else? Experience levels? Character traits? </p>

答:
At my last job we did a lot of pair programming.  We found it was not a good method for teaching/learning.  When we tried to use it for teaching often the pair would lag, one would get frustrated.

The best performance was usually from 2 people of similar skill level with sightly differing strengths, approaches and ideas.  People would develop a sense for the others strengths and weakness and would be an effective complement as a result.

We also found pairing to not be very effective for simple bugfixes, features.  Areas where the work was straightforward and simple.

Then again that's just my experience in one development team.

Title: Deciding factors in pair programming


问:
Why does CI stipulate that we should be able to rollback to any version of a software?
I was reading the book "Continuous delivery, reliable software deployments through build, tests and deployment automation ". And the author mentions that one should be able to rollback to any version of a software with one click.

I am wondering if this is really useful, and especially in the following scenarios :

You are working on web projects. Sounds to me that in this case, you don't really need the ability to rollback to any previous version. Being able to rollback the current release should be enough. Once it's deployed and working, why would you ever want to go back to a previous version ?

And actually this argument holds true if you are working on desktop applications.

Perhaps I misunderstood what he means by "being able to rollback to any version".

Does he mean the production environment or the development environment ? If it's the later that would make more sense - even if I still find it kind of unecessary for the web, source control branching should do the trick for desktop applications.

And still if it's the later, do you think that using tools like Entity Framework Code First Migration that allow you to recreate the database from the source code is enough to say that we have reach this standard ? Because then, with source control, we'd even have the referential data that need to be seeded for this particular version after the database is created.

答:
In short:

Since you don't know whether a build contains a critical bug at the time of deployment, you may need to roll back more than one version when you're deploying at a relatively high frequency. If your setup doesn't allow you to do so, your only alternative is to roll forward as quickly as you can.

As soon as you have an application that has 3rd party dependencies (say an API) or storage (say a database with schema), rolling back may be a lot harder than just deploying the same bits again. Source control is not enough, your schema needs to be reselient. You may need to build forward and backward compatibility into the design of your code and database schema to be able to pull that off.

Code First Migrations will allow you to easily move forward, but it doesn't fix your schema if you accidentally delete a vital column, or populate a default value with the wrong value or something else that may happen during a migration. being able to roll back would mean being able to restore the accidental changes, while retaining important (business) data. Patterns like CQRS provide you with a form of record and playback of changes, which will allow you to reconstruct the data in it's original form if needed.

Your interpretation probably holds when you're able to take down the site/application, back it up, install the new version, test it (can you absolutely be certain you did not introduce a critical bug?) and see that it works. If you want to take a step forward, do rolling deployments, canary builds/releases, dark launching, live failovers and other advanced deployment techniques, you need to take a step back and take in the whole picture.

Say you have Continuous Integration and you want to deploy every build when it passes all tests, you may already be 2 or 3 deployments ahead when you may find a critical defect which you weren't testing for.

If you can only go back one deployment, you're stuck and will have to fix the defect and roll forward. This puts a number of demands on your ability to come up, test and distribute a patch in short order.

If you're able to turn back to the last known good build, you're in much safer water.

You'll see that teams who have the ability to roll over at any point int time, will be less strict about this rule, than teams who need the ability to roll back.


答:
Being able to rollback to the current version is a different way of saying "rollback to the previous version", now to do that you have 2 ways of doing this:

You can simply make a copy of the current version before deployment, and if anything goes wrong, just replace the new version with the backup copy.

You can create a system where you can deploy any version at all, so deploying a new release means running the deploy task with the newer version, and rolling back is just the same process - only you specify the previous version.

The 2nd way is obviously more work, but it is far superior - it is the "right" way of doing this. You shift the problem of rolling back to one of deployment, so you do not need special work to make the backup and re-deploy the backup. Saving yourself this extra work means you can spend it on creating the correct deployment mechanism - which you have to do anyway as its what you use for deployment of new versions!

So, setting up your CI system to deploy is easier, better and also lets you deploy very old versions for free. In some businesses this is essential as you may be called upon to debug a problem a customer has in their version - so you'll need a way to re-create the version they are running. You may not need this for your single-deployment website so you aren't seeing what the benefit might be, but trust me - its very real.

Set up your CI system like this and you'll be set for the future, and any future roles you may have where you do need a fully working CI system, you'll have experience setting it up correctly.

Title: Why does CI stipulate that we should be able to rollback to any version of a software?

Body:
I was reading the book "Continuous delivery, reliable software deployments through build, tests and deployment automation ". And the author mentions that one should be able to rollback to any version of a software with one click.

I am wondering if this is really useful, and especially in the following scenarios :

You are working on web projects. Sounds to me that in this case, you don't really need the ability to rollback to any previous version. Being able to rollback the current release should be enough. Once it's deployed and working, why would you ever want to go back to a previous version ?

And actually this argument holds true if you are working on desktop applications.

Perhaps I misunderstood what he means by "being able to rollback to any version".

Does he mean the production environment or the development environment ? If it's the later that would make more sense - even if I still find it kind of unecessary for the web, source control branching should do the trick for desktop applications.

And still if it's the later, do you think that using tools like Entity Framework Code First Migration that allow you to recreate the database from the source code is enough to say that we have reach this standard ? Because then, with source control, we'd even have the referential data that need to be seeded for this particular version after the database is created.


问:
Enforcing open source software license
How can one enforce open source licensing terms on the usage of its derivative works?

For example, if a software is GPL licensed, and I use that software to develop some closed-source application of my own and distribute just the binary executable, how can the copyright owner find out that I used his software?

答:
Quite often, corporate misconduct is revealed by disgruntled employees or ex-employees.

When no inside source is available, and the only proof you have is the compiled binary of the product, it might get harder to prove that a copyright violation has happened. But there are a few things you can try:

One possible sign is identical behavior. When both products have the exact same obscure bug, it might be a sign that they obviously use the same code-base. When a product is based on an open source product, they likely did so because they did not want to reimplement everything themselves, so you can assume that most of the behavior will be the same.

When there is a limited amount of possible compiler toolchains and settings for the technology used to build the application, you might be able to reproduce the build-process and generate a binary from the open source codebase which is in large parts identical to the binary delivered by the company. This would be clear evidence that a copyright violation has happened.

Sometimes you find debugging symbols or other identifiers in a binary which hint on the structure and content of the original sourcecode. This can be a smoking gun. However, these can be suppressed through technology-dependent compiler-settings and/or obfuscators.

Whether or not any of this evidence would hold up in court is a question only a lawyer can answer.

Title: Enforcing open source software license


问:
Back button after doing posts on the same page
I have 3 pages to my site. The 1st page allows you to select a bunch of options. Those options get sent to the 2nd page to be displayed with some data about those options. From here I can click on a link to get to page 3 on 1 of the options. On page 3 I can create a new/edit/delete all on the same page where reloads come back to page 3.

I want a "back" button on page 3 to go back to page 2, but retain the options it had from the original page 1 request. Page 1 has a bunch of check boxes which are passed to page 2 as arrays to the controller. My thought is that I have to pass these arrays (I converted them to lists) to page 3 (even thought page 3 directly doesn't need them) so that page 3 can use them in the back link to it can recreate the values page 1 sent to page 2 originally.

I'm using asp.net MVC and when I pass the converted array it seems to convert it to the type instead of actually showing the values: "types=System.Collections.Generic.List" (where types is a List.

Is this what is needed or are there other options to getting a "back" button in this case to go back to page 2. It's sort of a pain to pass information to page 3 that isn't really relevant to page 3 except the back button.

答:
If the POST is changing state on the server, then respond to the POST with a 303 so that the browser can GET a page describing that new state (that is, from page 1 you are directed to page 2 and the information page 2 contains was affected by the POST). History will now work correctly.

If the state of page 2 is a reflection solely of the choices made on page 1, then it shouldn't be a POST in the first place, it should be a GET where the URI (perhaps including query string options) reflects the choices made. (E.g. most search engines work this way because e.g. going to https://www.google.com/search?q=some+search+criteria doesn't change anything on google, but it does affect what is returned. History will now work correctly.

If the state hasn't changed, but could have, or you are otherwise dealing with a very temporary situation, then respond directly to the POST (e.g. if doing the first approach here but reporting a validation error to the user instead of doing what they wanted). (History won't work without reposting, but then it shouldn't).


问:
Forking a GitHub repo and including code from pull requests within a LGPL license?
There is a project hosted at GitHub which is no longer maintained that I want to use for my project. However it has some bugfixes contained within pull requests from other users, and I would like to include them in the fork and thus my project.

So I was just wondering: under which license do the contributions made as pull requests fall? Is it the same LGPL license as the project, even if the changes haven’t been merged?

答:
Under normal circumstances, it can be assumed that contributions to an open-source project are made available under the same license as the project itself.

In very rare cases, a contributor might explicitly state that the contribution is made under a different license than the one used for the rest of the project. In such cases the copyright situation becomes complex and it might be better to ignore such contributions unless they provide a very large amount of added value to the project.

If you do decide to use such contributions, you should seriously investigate how the licenses interact with each other. You are well advised to consult a lawyer in such cases.


问:
Domain Driven Design - designing Aggregate Roots
Imagine you're designing an application for organizing Workshops.
Workshop itself is quite complicated - it acts as a state machine with multiple possible states and transitions between them.

We're using DDD, CQRS and Event Sourcing.

And now, the use cases:

1) one should be able to assign TodoItems to a Workshop and perform CRUD operations on them

2) one should be able to submit additional Resources for a given Workshop (slides, photos, zip/tar.gz archives etc.) and also perform CRUD operations on them

3) one should be able to add a PossibleTerm (with a Lecturer, Date and Room specified) to a Workshop. Also, there should be a way to modify/delete them.

Later on there is a Voting on those terms, system tries to book room for few terms (let's say, for two terms) that won Voting and Users should be split between those Terms.

Here I have following solutions:

1) Model TodoItems, Resources and PossibleTerms as a part of a Workshop.

Pros:

everything is where it conceptually belongs to

no eventual consistency (not a big problem probably...)

Cons:

Workshop aggregate is cluttered with all those CRUD methods for all stuff.

According to Implementing Domain Driven Design by Vaughn Vernon, creating huge  aggregate roots is an antipattern

2) Create aggregate roots for holding all those "items" (e.g. TodoItemList, PossibleTermList, Resources or whatever you're gonna call them).

Pros:

Workshop aggregate is smaller, it's not related with those Lists at all (the only connection would be that for example PossibleTermList holds a reference to WorkshopId)

Cons:

when CreateWorkshopCommand arrives, you're forced to create not only a Workshop, but also additional aggregates as they need to exist after Workshop creation. To avoid this, there could be some kind of CreationalSaga, listening for WorkshopCreatedEvent and producing proper commands to create relatives, but I don't think this is a good idea.

3) Model PossibleTerms, Resource, TodoItem as aggregate roots itself

Pros:

no need for creating 'aggregate wrappers' (as in 2))

Cons:

again, you're cluttering Workshop with at least factory methods

it is hard for me to implement term-choosing feature - for counting votes and later on assigning User to a particular Term you need to query your repository for all Terms matching your Workshop ID and so on - this leads to operations on multiple aggregates within one transaction.

Question: which solution sound best for you? Maybe you have differents ideas?

(Bonus question: I need to perform CRUD operations on individual Resources/TodoItem. I'd rather model then as value objects, but how are they then identified?)

答:
I think you're missing the transactional analysis. Which entities will be modified by each of your use cases ? Will some of them impact more than one entity ?

What are your invariants ? Do some of them span multiple entities (e.g., two Terms can't use the same Room at the same date/time) ? Are they true invariants or could eventual consistency be sufficient ?

Vaughn Vernon has a good step by step approach to aggregate modelling here : https://vaughnvernon.co/?p=926