问:
When is lock not needed in multithreading
I want 500 objects to be processed concurrently using multithreading. These objects will have some initial data before the threads are created.

I am creating 5 threads and each thread takes 100 objects and starts the operation.

Here is the code.

```<code>public class InputData
{
   public string initialData {get; set;}
   public string formula {get; set;}
   public string resultData {get; set;}
}

public static List<string> result = new List<string>(500);

public static void Main()
{
    List<InputData> lst = new List<InputData>(500);

    List<InputData> lst_1 = .. // This will hold 1 to 100 objects
    List<InputData> lst_2 = .. // This will hold 101 to 200 objects
    List<InputData> lst_3 = .. // This will hold 201 to 300 objects
    List<InputData> lst_4 = .. // This will hold 301 to 400 objects
    List<InputData> lst_5 = .. // This will hold 401 to 500 objects

    Thread t1 = new Thread(Update);
    ...
    ...
    Thread t5 = new Thread(Update);

    t1.Start(lst_1);
    ...
    t5.Start(lst_5);

    //while condition to wait for the threads to finish processing
    while(...)
    {
        ..
    }
}

public static void Update(List<InputData> lstAll)
{
    lstAll.resultData = lstAll.initalData + lstAll.formula;

    //result.Add(lstAll.resultData);
}
</code>```

As you can see from the code, each thread uses a bunch of objects. And I am updating only the resultData property of each object.

Is locking needed in this program? Can anyone please help

.net version is 3.5

答:
You will need to analyze it like peeling an onion.

Changing the properties of objects that are stored within a List<> will not cause its index position to shift. It will not cause the List<> to perform any reallocations either.

Therefore, If the List<> are not being modified (objects inserted, deleted, moved, or replaced), then:

(1) you are right in that using List<> that is fully pre-initialized with objects would be sufficient.

But (2) you should then look at the next layer: does the computation of each object have any possibility of interfering with each other. Since we cannot see the code for the computation, we can't comment on that.

This analysis is only applicable to the List<> implementation provided in the .NET framework. If someone implements its own IList<>, with non-trivial logic and behaviors (such that they do not mimic the behaviors of the standard implementation at all, say, by autonomously modifying the ordering or index positions of objects) then the analysis does not apply.


问:
Is there a way to define a consistent date in a dependent type language?
I am looking for an example (if exists at all) of a definition of a date in a programming language (Idris, Coq, etc) that features dependent types where such definition is consistent and type safe by which I mean that invalid date expression or literal would give a compile time error. If the complete definition isn't possible what would be the best one you can think of?</p>

答:
ISO Dates

Well you don't really need dependent types to model a wellformed month,

```<code> data Month = January
            | February
            | March
            ...
            | November
            | December
</code>```

It becomes slightly more painful with the day and year, since those are rather larger. Indeed, the legal representation of a day of the month depends on month. Let's define a function

```<code>numDays : Month -> Nat
numDays January = 31
...
numDays December = 31
</code>```

Now, what we want to say is that Day is a type which takes a month and returns a new type. So

```<code>Day : Month -> Type
Day m = ...
</code>```

where ... somehow says "I'm a number between 0 and numDays m". We can represent this with a type called Fin

```<code>data Fin (n : Nat) : Type where
  FinZ : Fin n
  FinS : Fin m -> m + 1 < n -> Fin (m + 1)
</code>```

In other words, Fin is all the numbers from 0 to n, excluding n.

So now we can say

```<code>Day : Month -> Type
Day m = Fin (numDays m)
</code>```

As for years, those are independent of both the month and the day, leaving us with

```<code>data Date : Type where
  mkDate : (year : Nat)(month : Month)(day : Day month) -> Date
</code>```

If we wanted to be precise, we could have day depend on year to take into account leap years.

If we where working in Agda and had mix-fix syntax. To get literals all we'd have to do is say

```<code>[_-_-_] : Nat -> (m : Month) -> Day m -> Date
[_-_-_] = mkDate
</code>```

We could do something similar with Coq's notations.

As a compileable mini example,

```<code>open import Data.Nat
open import Data.Fin

data Month : Set where
  January : Month
  February : Month

numDays : Month -> ℕ
numDays January  = 31
numDays February = 28

Day : Month → Set
Day m = Fin (numDays m)

record Date : Set where
  constructor mkDate
  field
    month : Month
    day   : Day month

_/_ : (m : Month)(n : ℕ){p : Data.Nat._≤_ (suc n) (numDays m)} → Date
_/_ m n {p} = mkDate m (inject≤ (fromℕ n) p)
</code>```

Quotients and Building Up Times

Now another obvious way to model dates and times is to have notions like an absolute time and other notions like a duration. Then we can combine these and produce other time stamps.

So for example we might want to say "5 seconds before 1 minute after T". The issue comes when comparing times like this for equality. We really don't care about the precise internal structure of how we can to a point in time, just that we got there. So we have to be careful not to let our data have any structure that might distinguish to otherwise equivalent values.

This is a really subtle and thorny issue as it turns out. There isn't really a good way to address this in Idris or Coq since they lack quotient types.

ContentLicense: CC BY-SA 3.0

Body:
ISO Dates

Well you don't really need dependent types to model a wellformed month,

 data Month = January
            | February
            | March
            ...
            | November
            | December

It becomes slightly more painful with the day and year, since those are rather larger. Indeed, the legal representation of a day of the month depends on month. Let's define a function

numDays : Month -> Nat
numDays January = 31
...
numDays December = 31

Now, what we want to say is that Day is a type which takes a month and returns a new type. So

Day : Month -> Type
Day m = ...

where ... somehow says "I'm a number between 0 and numDays m". We can represent this with a type called Fin

data Fin (n : Nat) : Type where
  FinZ : Fin n
  FinS : Fin m -> m + 1 < n -> Fin (m + 1)

In other words, Fin is all the numbers from 0 to n, excluding n.

So now we can say

Day : Month -> Type
Day m = Fin (numDays m)

As for years, those are independent of both the month and the day, leaving us with

data Date : Type where
  mkDate : (year : Nat)(month : Month)(day : Day month) -> Date

If we wanted to be precise, we could have day depend on year to take into account leap years.

If we where working in Agda and had mix-fix syntax. To get literals all we'd have to do is say

[_-_-_] : Nat -> (m : Month) -> Day m -> Date
[_-_-_] = mkDate

We could do something similar with Coq's notations.

As a compileable mini example,

open import Data.Nat
open import Data.Fin

data Month : Set where
  January : Month
  February : Month

numDays : Month -> ℕ
numDays January  = 31
numDays February = 28

Day : Month → Set
Day m = Fin (numDays m)

record Date : Set where
  constructor mkDate
  field
    month : Month
    day   : Day month

_/_ : (m : Month)(n : ℕ){p : Data.Nat._≤_ (suc n) (numDays m)} → Date
_/_ m n {p} = mkDate m (inject≤ (fromℕ n) p)

Quotients and Building Up Times

Now another obvious way to model dates and times is to have notions like an absolute time and other notions like a duration. Then we can combine these and produce other time stamps.

So for example we might want to say "5 seconds before 1 minute after T". The issue comes when comparing times like this for equality. We really don't care about the precise internal structure of how we can to a point in time, just that we got there. So we have to be careful not to let our data have any structure that might distinguish to otherwise equivalent values.

This is a really subtle and thorny issue as it turns out. There isn't really a good way to address this in Idris or Coq since they lack quotient types.


问:
Convincing my boss that touching the Database is integration testing
I am currently working on introducing continuous integration and switching to git, and as part of that, we must also better structure our tests.

We have agreed on splitting the tests in "integration" and "unit" - however he doesn't seem to agree that touching the database is also integration testing.

The code is horrible, everything is coupled to the database, it's hard to mock and stub, and I want to move it on the long term towards a better modularisation and testability.

Getting him to accept and use the proper naming is critical in future arguments.

So how to convince him that every test which touches the database is also integration testing?

At the moment he thinks that exec()-ing an external program or using an external interface (e.g. via SOAP) is an integration test.

He also thinks that everything which is slow belongs to integration testing, while he's in love with his "lightning fast database".

答:
Challenging someone who thinks they know best is always a problem. You have run into someone who believes "everything is a unit test," and that kind of miscategorization is hard to address.

Provide him with a scale of interactions, that has some hierarchy to it. Ask him to draw lines where he wants to define things. For instance.

Single method/procedure, no side effects; returns zero or more values.

Single method/procedure, side effects affect the class it's in only; returns zero or more values.

Single method/procedure, no side effects but uses an imported library.

Single method/procedure, no side effects but uses other classes/methods that are part of the code under test.

Single method/procedure, no side effects, but reads the database using JDBC library.
... and so on.

At what point does he draw the lines for "Unit", "Functional" and "Integration" tests?

Here is a similar scale: 1) single class, 2) single class plus a couple of jars, 3) single class plus JDBC/H2 in-memory database, 4) single class plus JDBC/MySQL on same machine, 5) single class plus JDBC/Oracle on separate database machine.

Another scale: 1) sub-millisecond test time, 2) sub-tenth of a second test time, 3) sub-second test time.


答:
As long as all of your five lists above contain disjoint sets of objects, and as long as the line

```<code>  result.Add(lstAll.resultData);
</code>```

is commented out, there is no locking needed. But I guess you are telling us not the whole story, the program above in the current form does not make much sense, since any results are thrown away after processing. So tell us how and in which thread you intend to aggregate the results, then you might get better answers.

Title: When is lock not needed in multithreading

Body:
I want 500 objects to be processed concurrently using multithreading. These objects will have some initial data before the threads are created.

I am creating 5 threads and each thread takes 100 objects and starts the operation.

Here is the code.

```<code>public class InputData
{
   public string initialData {get; set;}
   public string formula {get; set;}
   public string resultData {get; set;}
}

public static List<string> result = new List<string>(500);

public static void Main()
{
    List<InputData> lst = new List<InputData>(500);

    List<InputData> lst_1 = .. // This will hold 1 to 100 objects
    List<InputData> lst_2 = .. // This will hold 101 to 200 objects
    List<InputData> lst_3 = .. // This will hold 201 to 300 objects
    List<InputData> lst_4 = .. // This will hold 301 to 400 objects
    List<InputData> lst_5 = .. // This will hold 401 to 500 objects

    Thread t1 = new Thread(Update);
    ...
    ...
    Thread t5 = new Thread(Update);

    t1.Start(lst_1);
    ...
    t5.Start(lst_5);

    //while condition to wait for the threads to finish processing
    while(...)
    {
        ..
    }
}

public static void Update(List<InputData> lstAll)
{
    lstAll.resultData = lstAll.initalData + lstAll.formula;

    //result.Add(lstAll.resultData);
}
</code>```

As you can see from the code, each thread uses a bunch of objects. And I am updating only the resultData property of each object.

Is locking needed in this program? Can anyone please help

.net version is 3.5

Body:
As long as all of your five lists above contain disjoint sets of objects, and as long as the line

  result.Add(lstAll.resultData);

is commented out, there is no locking needed. But I guess you are telling us not the whole story, the program above in the current form does not make much sense, since any results are thrown away after processing. So tell us how and in which thread you intend to aggregate the results, then you might get better answers.


问:
When is it acceptable for business logic to be exposed on distributed applications?
When developing applications (for simplicity, use a client-server model) intended to be deployed on customer systems, when it is acceptable to expose business logic outside of compiled code (for instance in stored procedures)?

I used to subscribe to the thought that any and all logic should always be within the compiled code as it is both protected from being altered in addition to providing a level of IP protection. However, after distributing a few small client specific applications relying heavily on stored procedures, I have found that the ability to make fixes/customer specific adjustments "on the fly" (responsibly, of course) directly in SQL has made both support and maintenance significantly easier and faster as a change doesn't have to be compiled.

I do realize the drawbacks of this approach:

Anybody with DB rights could change the behavior/break the
application without you knowing

Version control difficulties

Some loss of IP protection

Assuming the platform will always be the same (no need to support multiple SQL DB's) and the application could be deployed by multiple distinct clients, does it make good sense - from a development and business perspective - to allow business logic to exist somewhere it is relatively easy to view and alter?

答:
Anybody with DB rights could change the behavior/break the application without you knowing

There is relatively simple protection from this: just write it in your contract that as soon as someone manipulates your product, you will refuse to do any maintenance any more. Add also a note that with each new release of your software you will replace existing stored procedures by new versions. This will hold most customers back from changing things they should not change.

Version control difficulties

Why should these be different than for client-side code? Since you wrote it is a standard product, you should separate customer specific changes / parameters rigorously from the source code of your product. There is no general difference for client code or server-side code in this. When you follow this rule, version control for your server-side code should be as easy or as hard as for your client-side code.

Some loss of IP protection

I would not overrate this. As long as there is no "ground-breaking, totally ingenious algorithm" hidden in your stored procedures, I guess the code is not of much value to anyone else as long as he has not also the client-side source code of your application. Moreover, for some database systems there are also options available to hide or obfuscate stored procedures - Google is your friend.

So the gist is: try to deal with your server-side code the same way you deal with your client-side code, then your "drawbacks" will vanish.


问:
Why is type inference useful?
I read code way more often than I write code, and I'm assuming that most of the programmers working on industrial software do this. The advantage of type inference I assume is less verbosity and less written code. But on the other hand if you read code more often, you'll probably want readable code.

The compiler infers the type; there are old algorithms for this. But the real question is why would I, the programmer, want to infer the type of my variables when I read the code? Isn't it more faster for anyone just to read the type than to think what type is there?

Edit: As a conclusion I understand why it is useful. But in the category of language features I see it in a bucket with operator overloading - useful in some cases but affecting readability if abused.

答:
I think the answer to this is really simple: it saves reading and writing redundant information.  Particularly in object oriented languages where you have a type on both sides of the equal sign.

Which also tells you when you should or should not use it -- when the information isn't redundant.

Title: Why is type inference useful?


问:
Algorithm for mapping users to a schedule based on time availability
I have a project where I must map employees to a schedule. The basic concept is:

Company Opens between 08:30 and 17:00.

Employee 1 can work from 08:30 to 12:00 then from 13:00 to 1700;

Employee 2 can work from 12:00 to 13:00.

Employee 3 can work from 17:30 to 00:00

I would then want the employees mapped to the company object based on when they can work. So if I require one employee on at all times, in the example above Employee 1 and 2 would be working on that day.

I've got a couple of ideas in my head on how to approach this but wanted to check to see if there are any algorithms designed around this kind of task.

答:
This is written from the pragmatic point of view. Don't reinvent the wheel. You are better off learning and using a known piece of software than writing your own scheduling program that likely won't preform as well and will be 'fun' to maintain - both for you and the next guy.

Scheduling problems are hard... and not just hard, but they can often be NP-hard.  The problem described is a modification of the nurse scheduling problem which is a classic one that has been studied for several decades because of its difficulty.

If one wants to try to code it oneself, there are a number of techniques.  Those mentioned in the wikipedia article include decomposition, parallel computing, stochastic optimization, genetic algorithms, colony optimization, simulated annealing, Tabu search, and coordinated descent.

I should also point out that there is an entire industry of software programs around the nurse scheduling program.  A search for nurse scheduling software turns up numerous results from different companies.

All of these fall into the area of constraint programming, and while one could sit down with prolog (or write your own), this tends to be the area where one would grab a rules engine appropriate to your platform and let it do the work.  One such example is that of drools, which has an example of employe shift rostering using nurses (there are some other examples too including patient admission schedule, exam timetabling, and a traveling tournament problem).


答:
Brute force may not be feasible for even small datasets.

I have written something like this in my beginnings, in C#. I used a genetic algorithm.

The source code (hosted at Codeplex) is awful, I didn't know any better at the time. But you can take a look at the video presentation: http://vimeo.com/20610875

I start talking about the subject of your interest around 6:00.

Personally I got the idea from http://mkweb.bcgsc.ca/carpalx/?simulated_annealing which is an interesting read. Nevermind the math, you can ignore it.

The solution yields really good results, as demonstrated in my video.

Title: Algorithm for mapping users to a schedule based on time availability

Body:
I have a project where I must map employees to a schedule. The basic concept is:

Company Opens between 08:30 and 17:00.

Employee 1 can work from 08:30 to 12:00 then from 13:00 to 1700;

Employee 2 can work from 12:00 to 13:00.

Employee 3 can work from 17:30 to 00:00

I would then want the employees mapped to the company object based on when they can work. So if I require one employee on at all times, in the example above Employee 1 and 2 would be working on that day.

I've got a couple of ideas in my head on how to approach this but wanted to check to see if there are any algorithms designed around this kind of task.


问:
How to make an open source project popular?
I have recently started a project, a CSS/JS library, on Github. I'm already pretty far with it and was wondering: How do I make it popular? How did other libraries that are very famous now, like jQuery, become that famous. Because I don't think they just left the project on Github for awhile, and then all the interested people came without doing a thing? </p>

答:
The first couple projects that I did that were open source never got off the ground. The mistake I made is that I kept my coworkers, as well as friends and family, completely separate from the work I was doing, and I only talked about these projects on my rarely-visited blog.

I did the opposite of what I should have done.

Now, I have a few projects I've worked on where I've marketed them on different channels. For Stack Exchange browser add-ons, I use Stack Apps, and I also publish them on the respective stores, the Mozilla Add-on and Chrome Web Stores.

For things that aren't browser add-ons, I use Twitter, Reddit, Google Groups, and the GitHub issue tracker to help spread awareness of tools that I think can provide value to other developers facing problems.

The key to spreading awareness is not to spam people. Ideally, your project solves a problem that hasn't already been solved. One of my projects helps make it easier for Chrome App developers to migrate their existing apps to node-webkit, so I talk about this in their forums whenever people ask about how to get started migrating. The key is to interject where it's relevant. Follow the 80/20 rule. Make sure you're contributing 80% to these communities where you're not promoting your products, and use the 20% as opportunities to talk about a problem you've solved that's important to that community.

The most successful open source projects have a passionate community built around them. To succeed, you'll need to get out and talk to people, and solve their problems in order to create that passion. Since most of this will happen over the Internet, work on your written communication skills. Learn how to communicate ideas efficiently and cleanly so that people trust you as an expert in your area. As amon says in the comments, demo pages and clear documentation will be key. No one will reverse engineer your project. You need to clearly demonstrate both how and why it solves their problem. Hope this helps.


答:
Suppose one sees the code:

```<code>someBigLongGenericType variableName = someBigLongGenericType.someFactoryMethod();
</code>```

If someBigLongGenericType is assignable from the return type of someFactoryMethod, how likely would someone reading the code be to notice if the types don't match precisely, and how readily could someone who did notice the discrepancy recognize whether it was intentional or not?

By allowing inference, a language can suggest to someone who is reading code that when the type of a variable is explicitly stated the person should try to find a a reason for it.  This in turn allows people who are reading code to better focus their efforts.  If, by contrast, the vast majority of the times when a type is specified, it happens to be exactly the same as what would have been inferred, then someone who is reading code may be less prone to notice the times that it is subtly different.

Title: Why is type inference useful?

Body:
I read code way more often than I write code, and I'm assuming that most of the programmers working on industrial software do this. The advantage of type inference I assume is less verbosity and less written code. But on the other hand if you read code more often, you'll probably want readable code.

The compiler infers the type; there are old algorithms for this. But the real question is why would I, the programmer, want to infer the type of my variables when I read the code? Isn't it more faster for anyone just to read the type than to think what type is there?

Edit: As a conclusion I understand why it is useful. But in the category of language features I see it in a bucket with operator overloading - useful in some cases but affecting readability if abused.

Body:
Suppose one sees the code:

someBigLongGenericType variableName = someBigLongGenericType.someFactoryMethod();

If someBigLongGenericType is assignable from the return type of someFactoryMethod, how likely would someone reading the code be to notice if the types don't match precisely, and how readily could someone who did notice the discrepancy recognize whether it was intentional or not?

By allowing inference, a language can suggest to someone who is reading code that when the type of a variable is explicitly stated the person should try to find a a reason for it.  This in turn allows people who are reading code to better focus their efforts.  If, by contrast, the vast majority of the times when a type is specified, it happens to be exactly the same as what would have been inferred, then someone who is reading code may be less prone to notice the times that it is subtly different.


问:
Notifications system with too many subscribers
In my application users can subscribe to other users, like in every social network out there. However I'm experiencing some trouble when a user has too many subscribers. Every time a user posts something all of his subscribers are notified via the notification system. When a user has like 2000 subscribers or even more, this means I have to insert 2000 rows into the notifications table, which may take a second or two. Having many users posting stuff I have the feeling that this table is going to get cluttered really fast and I can't think of another realization.

The current schema is

```<code>CREATE TABLE IF NOT EXISTS `notifications` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `text` text NOT NULL,
  `data` text NOT NULL,
  `time` datetime NOT NULL,
  `seen` enum('0','1') NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
</code>```

How can I overcome this problem?

答:
For a system which can handle >2000 users, adding 2000 records to a table should not be much of a problem, otherwise you have chosen the wrong hardware. If the one or two seconds block your main process for too long, add the records asynchrounously in a separate thread or process.

And if you have concerns about getting too many notification records in that table, think about how long those notifications really need to be stored. Will they really have to be stored once the notification was seen? Do they have to be stored for more than, for example, 60 days? These thoughts should help you finding an appropriate clean-up strategy.


问:
Should I rebuild my read only database every time I launch my server?
I'm getting into web development, and I'm trying to get a grip on databases.

In an app I want to make, there is a read only database that will be filled up with a large amount of data, which will be the heart of the application, and also a lot of work to put in.

I'm uncomfortable with putting all this data into the database, as the database is "separate" from my web app code. I feel like I should rather write my data in code somewhere, and then have my application put the data into the database for me.

This way I would have my entire project written in code, and not an integral part of my software hidden away in the database, which is a bit complicated to work with, and seems difficult to move from computer to computer.

But is this a sensible way to do this, however? Should I write my data in code, and every time I launch the server, make the application drop all the tables and read them in from my code again?

Is this the wrong way to go about it? Would it cause considerable overhead? How do people do this?

答:
Maybe it's not a feasible solution for you.
What we are doing for some cases: We use the dump-features of inmemory-databases.

During the building-process we are building up an inmemory-database
(hsqldb...)

dump the database in a file

add it to the deployment-package

After starting the webapp we load the dumped file
and use the database.

So you

don't deploy the "how do I get the database"-code

you build your database during the automated build and not during the startup of your app, which can last a lot of time.


问:
Should I store x,y coordinates as an array, a class object, or two variables?
I have a MyObject which has an x and y coordinate.

as far as I can see, I can store it in three ways:

```<code>class MyObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class MyObject:
    def __init__(self, x, y):
        self.position = [x, y]

class MyObject:
    def __init__(self, x, y):
        self.position = Coord(x,y) #Coord class created elsewhere
</code>```

Is there a best practise either way for this ?

Where I'm thinking this is relevant, is when passing these coordinates into other methods:

eg.

```<code>myObj = MyObject(0,0)
searchLocation(myObj.x, myObj.y)
searchLocation2(myObj.position)
</code>```

答: I think an answer that gets you all the behavior you want with zero code overhead is to use a Pandas Series. It supports accessing by index, accessing by field name (i.e. .x and .y), and it also supports element-wise operations out of the box, so you'll be able to add and subtract your coordinates without having to overload any operators. </p>


答:
I would take a look at namedtuple* class from the standard library. It's basically a automated way of subclassing a tuple with named proprties for corresponding to each field.

https://docs.python.org/2.7/library/collections.html?highlight=namedtuple#collections.namedtuple

If you need to do vector and matrix operations you might want to look into NumPy instead, which is made of highly functional numeric datatypes:

http://www.numpy.org/

Title: Should I store x,y coordinates as an array, a class object, or two variables?

Body:
I have a MyObject which has an x and y coordinate.

as far as I can see, I can store it in three ways:

```<code>class MyObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class MyObject:
    def __init__(self, x, y):
        self.position = [x, y]

class MyObject:
    def __init__(self, x, y):
        self.position = Coord(x,y) #Coord class created elsewhere
</code>```

Is there a best practise either way for this ?

Where I'm thinking this is relevant, is when passing these coordinates into other methods:

eg.

```<code>myObj = MyObject(0,0)
searchLocation(myObj.x, myObj.y)
searchLocation2(myObj.position)
</code>```


问:
Are there programming languages that allow you to do set arithmetic on types?
Out of curiosity, are there languages that allow you to do set arithmetic on types to create new types? Something like:

```<code>interface A {
  void a();
  void b();
}

interface B {
  void b();
  void c();
}

interface C = A & B; // has b()
interface D = A | B; // has a(), b() and c()
interface E = (A & B) ^ B; // has c()
</code>```

I know that in some languages these ideas can be expressed (i.e., Java has List<Comparable & Serializable> for the union of the interfaces) but I've never heard of a language that supports type arithmetic. Thanks!

答: Java supports intersections of interface types in some contexts, though it does not so far as I can tell allow the creation of variables of intersection types.  Intersection types may come into play, for example, when using the ? : operator.  If the second and third operands to that operator are unrelated interfaces which inherit from overlapping sets of interfaces, the result of the operator will be the set of interfaces which are common to both.


问:
How do web servers deal with issues that arise when a machine has been on for a long time?
It seems to be accepted that computers that have been powered on for a long time and have any sort of complex software (ie and OS) running on them they tend to develop random errors and problems. Turning the device off and back on powers off the machine and destroys all volatile memory, generally fixing the problem.

First, am I just imagining that or is it accepted? Is there a better description or a word/phrase for it?

Second, how do servers deal with this. They are generally 24/7/365 machines. Though multiple machines serving the same page could be turned off individually, is this done in that situation?

答:
Any system that has to be reset/restarted after a while to continue working is faulty. Various faults include simple things like memory leaks to more complex problems like design failures.

Many years of poor software has had the effect of "training" users to accept faulty systems; and to work around the problem by restarting. Note: "working around" a problem is not the same as fixing a problem.

For servers (e.g. 24/7/365 machines) this isn't possible, and you need (e.g.) software that isn't faulty.


问:
Method waits for user action
I have a structural problem for an application I'm working on.  In the interest of full disclosure, it is for a university assignment so I'm not looking for you to code me an answer, just help me think through the best approach.

I'm building a game using an OO approach.  I have an abstract class called Player from which several types derive.  These represent the computer and human players.  So I have a derived HumanPlayer class which must provide an implementation for a method called ChooseCard.  The way the user selects a card is by clicking on a card in a GUI.  So the card will be identified by the user through an event handler.

The relevant part of my code is listed below.  At the moment the Game class loops through each player and calls the PlayCard method on each Player.  I'm just not sure how to program the ChooseCard method in the HumanPlayer class so that it can wait for the user to select a card to play but have the UI remain responsive.   Ideally I want to be able to treat each of the derived player types the same (ie as the base class Player).

This question is asking basically the same thing I am but I don't really like the answers.

The answer to this question is interesting, using the TaskCompletionSource class.

I'm not fixed on this structure if there is a superior solution although I need to keep the class structure.

Edits:
Added a class diagram for the models of my application as well as a screenshot of what the gameboard looks like (currently).

Here is my current thinking:
The user will click on the card they want to play.  The click event will propagate to the bound CardViewModel (At this point the action could be handled at the Model or ViewModel layer).  Now the CardViewModel (or Card) doesn't know who is interested in knowing that the user selected it.  The interested party will be the PlayerViewModel/HumanPlayer to whom the Card belongs, but they will only be interested when they are expecting a response from the user.  I.e. when HumanPlayer.PlayCard() is called.

So I'm thinking that the CardViewModel/Card should raise an event to which the HumanPlayer object can subscribe to when it is interested in the user making a card selection.

I can make HumanPlayer.ChooseCard() subscribe to the CardSelected events of each of the cards.  I'm just not sure how to make the method wait without blocking until one of those events fires.

```<code>abstract public class Player
{
    public IReadOnlyList<Card> Cards { get { return cards.AsReadOnly(); } }

    public Card PlayCard()
    {
        var cardToPlay = ChooseCard();
        // ...
    }

    protected abstract Card ChooseCard();
}

public class HumanPlayer : Player
{
    protected override Card ChooseCard()
    {
        // TODO: request a card from the user.
        throw new NotImplementedException();
    }
}

public class Game
{
    private List<Player> livingPlayers = new List<Player>();

    public void PlayRound()
    {
        var cardsPlayedByPlayers = GetCardsPlayed();
        // ...
    }

    private Dictionary<Player, Card> GetCardsPlayed()
    {
        var cardsPlayedByPlayers = new Dictionary<Player, Card>();

        foreach (var player in livingPlayers.Where(p => !p.IsDead))
        {
            // Player.PlayCard() called here getting chosen card from the player.
            cardsPlayedByPlayers.Add(player, player.PlayCard());
        }

        return cardsPlayedByPlayers;
    }
}
</code>```

Update:

I've put the final code up on GitHub here since the assignment is over.  You can now see the full code clearly and if you would like to critique it, I'd be keen to hear your thoughts.

答:
The way you would do it is by using a delegate. Rather than wait for the user input inside the class, delegates allow you to trigger a custom event and have the GUI manage things for you instead.

Below is an outline for setting one up:

First define a public delegate so that it is accessible by the GUI.

Then in ChooseCard(), add a call to the delegate. This will tell the GUI to handle the specifics of choosing a card.

In the GUI, add a reference to the delegate. This part is similar to adding a reference to an event handler.

Once the reference is made, you can add a code-block to launch a MessageBox or some sort of notification that would ask the user for their input. Again, this part is similar to event handlers.

Finally, when the user makes a selection, pass the data to the Player class.

Title: Method waits for user action


答:
If your database is truly read only then you have no reason to ever rebuild it, because it never changes, then you have no reason to rebuild it every time.

If what you're concerned about is that you may have your database out-of-sync with your application code version, then one way to work around this is to use a file-based database system like SQLite or as a bunch of JSON/XML in a directory. Just check in the SQLite .db file together with the application code.

Title: Should I rebuild my read only database every time I launch my server?

Body:
I'm getting into web development, and I'm trying to get a grip on databases.

In an app I want to make, there is a read only database that will be filled up with a large amount of data, which will be the heart of the application, and also a lot of work to put in.

I'm uncomfortable with putting all this data into the database, as the database is "separate" from my web app code. I feel like I should rather write my data in code somewhere, and then have my application put the data into the database for me.

This way I would have my entire project written in code, and not an integral part of my software hidden away in the database, which is a bit complicated to work with, and seems difficult to move from computer to computer.

But is this a sensible way to do this, however? Should I write my data in code, and every time I launch the server, make the application drop all the tables and read them in from my code again?

Is this the wrong way to go about it? Would it cause considerable overhead? How do people do this?


问:
What's the worst question you were ever asked at interview?
It doesn't have to be programming or software development related, but just asked during an interview for an IT related job.

I know some "left field" questions are meant to see how the candidate copes with unexpected and novel situations, but here I'm looking for a question that appeared to be completely unrelated to the job they were interviewing you for, or something that made you think "what useful information could they possibly get from my answer to that question?".

答:
Here are 38 more questions.

Are you able to work overtime, evenings and weekends?

How do you feel about attending conferences with (men) (women) ?

What child care arrangements have you made?

What type of position does your spouse have?

Do you think that you can supervise (men) (women), and how do you think they will react?

This job has always been handled by a (female) (male). Do you think you can handle it?

Are you willing to put career interests before self-interests?

What are your computer skills? Would you be interested in doing some word processing?

How do you feel about women's liberation?

By the way, would you mind telling me: "Just how old are you?"

How do you respond to authority?

How do you define sexual harassment?

Where were you born?

What's your nationality?

Are you married, divorced, separated, or single?

Are you living with anyone?

What holidays do you celebrate?

Do you have any disabilities that affect your work?

What is your health situation like?

Have you ever been arrested?

Are you on any medications?

Do you ever abuse alcohol or drugs?

How many children do you have?

What church do you attend?

How do you think my older employees would react if I hired you?

Do you have many debts?

Do you own or rent your home?

How much insurance do you have?

How much do you weigh?

Do you plan to have any more children?

What does your spouse think about your career?

Have you ever brought a law suit against an employer?

Have you ever filed for workers' comp?

Where do you usually go on vacation?

What do you think about romance in the office?

Have you ever been sexually harassed?

Do you have plans to get married?

Tell me about your family.

What would your past managers say about you?

How do you feel about working overtime?

ContentLicense: CC BY-SA 2.5


答:
It might be the accepted norm if you are accustomed to running hardware and software that isn't that stable. But I haven't observed a particular trend of servers running poorly after extended uptime in my career. I've run many a Solaris, Linux or BSD server well past 1000 day uptime and more than a handful have made it to the 1400-1500 day mark. I would update Apache or apply other patches without patching the kernel and just keep trucking. (NOTE: I don't advocate that this as a sys-admin practice, but there are systems that customer's don't want rebooted unless there is a problem).

As to how it is done in web servers that just serve pages, you are correct, a page can and is often served by redundant servers and even a content delivery network. Taking down a node shouldn't impact your site if you have redundancy and caches. High availability is all about redundancy. It isn't so important to keep a single node healthy for extended runtimes for a static web site. You really shouldn't need to depend on a single web server today when a Linux VM can be had for $5 a month at Digital Ocean and a 2 node load-balanced Linux setup can be put together for cheap.

The shift for the past 10 years has been toward many cheap servers. Back in the 1998-2000 time frame at IBM we were already running massively distributed web farms with 50-100 nodes serving up a single site (Olympics, Wimbledon, US Open, Masters), and now it is commonplace since companies like Google and Facebook published a lot of literature on this technique.

Title: How do web servers deal with issues that arise when a machine has been on for a long time?

Body:
It seems to be accepted that computers that have been powered on for a long time and have any sort of complex software (ie and OS) running on them they tend to develop random errors and problems. Turning the device off and back on powers off the machine and destroys all volatile memory, generally fixing the problem.

First, am I just imagining that or is it accepted? Is there a better description or a word/phrase for it?

Second, how do servers deal with this. They are generally 24/7/365 machines. Though multiple machines serving the same page could be turned off individually, is this done in that situation?


答:
Well firstly I would expect years of uninterrupted up-time from any modern server OS (even Windows :-) ).

But there are usually external reasons for bringing down a server (often every few months!).
Software upgrades, hardware upgrades, changing dust filters, re-organizing your data center, applying security patches etc. etc.

If the system is critical and expected to run 24*7*365 then there are a few ways to deal with this.

Run a load balanced cluster. You simply re-cycle the servers one at a time.

Have a hot standby. Switch load to the standby machine when applying maintenance.

No real servers -- run only virtual machines. You can shift the image to another physical server quickly will minimal downtime.

In practice a robust setup will probably use a hybrid of all of the above methods.
A cluster of physical servers, running a set of load balanced virtual machine images, with some hot standby servers at a remote site.


答:
I am guessing that there will be plenty of other factors that are coming into play that you might not have considered. They are probably not technical. Eg, time, effort, understandability, simplicity, upcoming future work, previous decisions already made, etc.

There is obviously a lot of conflict around the database. You need to take a step back here, he's obviously very proud of it, and knocking it isn't going to help your case. If it's fast, that's a good thing.

It could well be that your points are quite valid, and s/he might be pushing back because of the way you are suggesting them.

Also, chillax, remember that nobody has ever died because of the mockability of an application :)

Title: Convincing my boss that touching the Database is integration testing

Body:
I am currently working on introducing continuous integration and switching to git, and as part of that, we must also better structure our tests.

We have agreed on splitting the tests in "integration" and "unit" - however he doesn't seem to agree that touching the database is also integration testing.

The code is horrible, everything is coupled to the database, it's hard to mock and stub, and I want to move it on the long term towards a better modularisation and testability.

Getting him to accept and use the proper naming is critical in future arguments.

So how to convince him that every test which touches the database is also integration testing?

At the moment he thinks that exec()-ing an external program or using an external interface (e.g. via SOAP) is an integration test.

He also thinks that everything which is slow belongs to integration testing, while he's in love with his "lightning fast database".


答:
Hard coding your data in the application is considered poor practice for anything but the most trivial data.

If you do decide to do this code the "data" in a separate module!

If I understand your requirements -- you want to distribute the data with the application in  a single cohesive package. Then--

Code up your data in a single JSON/XML file which you can package with the application, and load it into a memcache stype database when the application is initalized.
-or-
Create an sqlite database. An sqlite database consists of a single file which can be deployed alongside your application. Most php/python distributions come with sqlite built in.


答:
I think you are going about this the wrong way. Don't get into an argument over the definitions of words, that's not useful. Trying to argue for changes in development methodology by arguing over the definition of an integration tests, is like try to square a circle by changing the definition of a square.

Instead, argue for what you actually want to change. Do you want the ability to test functionality without hitting the database? Then present a case why that would be useful. Do you want your tests to run faster? Then show how it can be done. Do you want cleaner code by not mixing database logic everywhere? Show the benefits.

Appealing to a definition that says that "database access does not belong in integration tests" is just cargo culting. Instead, gives reasons why we should avoid database access in the primary test suite. I think you'll find the definitions follow.


答:
You can able to greatly increase the speed by putting your inserts inside a transaction. You can also move your prepare and bind statements outside, if you need so.

The idea I generally use when working with transactions looks like this (semi-pseudo-code):

```<code>try {
    // First of all, let's begin a transaction
    $db->beginTransaction();

    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');

    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}
</code>```

Example taken from this link:- https://stackoverflow.com/questions/2708237/php-mysql-transactions-examples

Title: Notifications system with too many subscribers

Body:
In my application users can subscribe to other users, like in every social network out there. However I'm experiencing some trouble when a user has too many subscribers. Every time a user posts something all of his subscribers are notified via the notification system. When a user has like 2000 subscribers or even more, this means I have to insert 2000 rows into the notifications table, which may take a second or two. Having many users posting stuff I have the feeling that this table is going to get cluttered really fast and I can't think of another realization.

The current schema is

```<code>CREATE TABLE IF NOT EXISTS `notifications` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL,
  `text` text NOT NULL,
  `data` text NOT NULL,
  `time` datetime NOT NULL,
  `seen` enum('0','1') NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
</code>```

How can I overcome this problem?

Body:
You can able to greatly increase the speed by putting your inserts inside a transaction. You can also move your prepare and bind statements outside, if you need so.

The idea I generally use when working with transactions looks like this (semi-pseudo-code):

try {
    // First of all, let's begin a transaction
    $db->beginTransaction();

    // A set of queries; if one fails, an exception should be thrown
    $db->query('first query');
    $db->query('second query');
    $db->query('third query');

    // If we arrive here, it means that no exception was thrown
    // i.e. no query has failed, and we can commit the transaction
    $db->commit();
} catch (Exception $e) {
    // An exception has been thrown
    // We must rollback the transaction
    $db->rollback();
}

Example taken from this link:- https://stackoverflow.com/questions/2708237/php-mysql-transactions-examples


问:
Implementation strategies for atomic counter
I basically have a counter variable that is decremented and frequently polled. There are three options to implement that, that I can think of:

Number 1:

```<code>private volatile int count;
public void Finished() {
    Interlocked.Decrement(ref count);
}

public bool Done() {
    return count == 0;
}
</code>```

Number 2:

```<code>private int count;
public void Finished() {
    Interlocked.Decrement(ref count);
}

public bool Done() {
    return Volatile.Read(ref count) == 0;
}
</code>```

Number 3:

```<code>struct AtomicInteger {
    private int value;

    public int Get() {
        return Volatile.Read(ref value);
    }
    // other methods
}
// In actual class:
private AtomicInteger count;
public bool Done() {
     return count.Get() == 0;
}
</code>```

The first one gives a compiler warning because of passing a volatile variable by reference. On the other hand it's clear from the variable definition that the variable is accessed concurrently which is clearly a warning sign to anybody looking at the code.
If I ever decide that I actually need a long, this method does not work at all any more.

The second one doesn't give any warnings, but just from reading private int count it's not clear that the variable is used concurrently, so this has to be explicitly stated with a comment (I actually had a bug where I used a normal read in an assertion instead of Volatile.Read - such an easy thing to overlook.)
Changing the variable to a long on the other hand does not introduce any additional work.

I do like number 3 and it shouldn't result in any performance overhead compared to the other solutions after inlining.
Downside: Code duplication for every primitive. On the other hand the code is simple enough and can be copy-pasted without fear of problems and is unlikely to ever change.

Any comments on advantages/disadvantages of each method that I've overlooked or what would be considered idiomatic in C#?

答:
I would say that number one is idiomatic in C#.

Personally I prefer number two: I like to move the "volatile read" information on the read itself rather than bury it in the fields declaration. Besides the volatile modifier in c# is a strange and misleading thing that is often misunderstood, so I think it is easier for a newbie to just read and understand the Volatile.Read documentation. Finally it is a healthy habit for the more complex cases where you must emphasize the implicit memory fences.

As for number three, it is a matter of coding style. Personally I think it is superfluous unless you use it in many places.

Finally, for those worried about correctness, here is a source (Joe Duffy) that states that the volatile modifier is not needed on fields for mere atomic operations, which means that #1 and #2 are equivalent and correct, and therefore that #3 is. Nevertheless I would replace "== 0" by "<= 0" just in case something goes wrong in two years.


答: Common Lisp allows you do define new type using not, and, and  or  operators (see Type specifiers That Combine).

Title: Are there programming languages that allow you to do set arithmetic on types?

Body:
Out of curiosity, are there languages that allow you to do set arithmetic on types to create new types? Something like:

```<code>interface A {
  void a();
  void b();
}

interface B {
  void b();
  void c();
}

interface C = A & B; // has b()
interface D = A | B; // has a(), b() and c()
interface E = (A & B) ^ B; // has c()
</code>```

I know that in some languages these ideas can be expressed (i.e., Java has List<Comparable & Serializable> for the union of the interfaces) but I've never heard of a language that supports type arithmetic. Thanks!


问:
What kinds of non-source artifacts are vital to your development process?
The "classic" development artifacts are requirements documents and design specifications. But the development process includes many other non-source code artifacts: bug tracking databases, emails, wikis.

What kinds of non-source code artifacts do you think are most vital to your development process? And how do you keep these documents up to date?

Also, are there any artifacts that you don't necessarily find useful, but have to use because it's required by the contractor or management?

答:
In my first job out of university, there were two significant non-code artifacts.

The payroll reindeer was a little stuffed toy that sat on the desk partition of the person currently responsible for maintenance of the payroll system.

The project management tool was a wooden rod, 1/2 inch square and about a foot long.

Nuff said, I think.


问:
Should an ASP.NET MVC application directly use Entity Framework as the model?
I'm building my first MVC application in Visual Studio 2013 (MVC 5) and I'm a bit unclear on the best way to setup my model.

I've generated an entity framework model using code-first from an existing database. My first instinct was to create some intermediary classes that would be the model used by the views and have those classes work with the entity framework classes.

As I was writing the intermediary classes I realized that I was mostly just re-implementing a lot of the things that the EF classes already did just with the occasional private setter or cast from one datatype to another. So that seemed like a waste.

Is the general rule to directly use the entity framework classes as the Model for an MVC application? Or is there some benefit I'm missing for building these intermediary classes?

答:
In my applications I have always separated things out, with different models for the database (Entity Framework) and MVC. I have separated these out into different projects too:

Example.Entities - contains my entities for EF and the DB context for accessing them.

Example.Models - contains MVC models.

Example.Web - web application. Depends on both Example.Domain and Example.Models.

Instead of holding references to other objects like the domain entities do, the MVC models hold IDs as integers.

When a GET request for a page comes in, the MVC controller performs the database query, which returns an entity. I have written "Converter" methods that take a domain entity and convert it to an MVC model. There are other methods that do the opposite (from an MVC model to a domain entity). The model then gets passed to the view, and thus to the client.

When a POST request comes in, the MVC controller gets an MVC model. A converter method converts this to a domain entity. This method also performs any validations that can't be expressed as attributes, and makes sure that if the domain entity already exists that we are updating it rather than getting a new one. The methods usually look something like this:

```<code>public class PersonConverter
{
    public MyDatabaseContext _db;

    public PersonEntity Convert(PersonModel source)
    {
         PersonEntity destination = _db.People.Find(source.ID);

         if(destination == null)
             destination = new PersonEntity();

         destination.Name = source.Name;
         destination.Organisation = _db.Organisations.Find(source.OrganisationID);
         //etc

         return destination;
    }

    public PersonModel Convert(PersonEntity source)
    {
         PersonModel destination = new PersonModel()
         {
             Name = source.Name,
             OrganisationID = source.Organisation.ID,
             //etc
         };

         return destination;
    }
}
</code>```

By using these methods I take the duplication out that would otherwise occur in each controller. The use of generics can deduplicate things even further.

Doing things this way provides multiple benefits:

You can customise a model to a specific view or action. Say you have a signup form for a person that when submitted, creates many different entities (person, organisation, address). Without seperate MVC models this will be very difficult.

If I need to pass more information to the view than would otherwise be available just in the entity, or combine two entities into a single model, then my precious database models are never touched.

If you ever serialise an MVC model as JSON or XML, you only get the immediate model being serialised, not every other entity linked to this one.

Body:
In my applications I have always separated things out, with different models for the database (Entity Framework) and MVC. I have separated these out into different projects too:

Example.Entities - contains my entities for EF and the DB context for accessing them.

Example.Models - contains MVC models.

Example.Web - web application. Depends on both Example.Domain and Example.Models.

Instead of holding references to other objects like the domain entities do, the MVC models hold IDs as integers.

When a GET request for a page comes in, the MVC controller performs the database query, which returns an entity. I have written "Converter" methods that take a domain entity and convert it to an MVC model. There are other methods that do the opposite (from an MVC model to a domain entity). The model then gets passed to the view, and thus to the client.

When a POST request comes in, the MVC controller gets an MVC model. A converter method converts this to a domain entity. This method also performs any validations that can't be expressed as attributes, and makes sure that if the domain entity already exists that we are updating it rather than getting a new one. The methods usually look something like this:

public class PersonConverter
{
    public MyDatabaseContext _db;

    public PersonEntity Convert(PersonModel source)
    {
         PersonEntity destination = _db.People.Find(source.ID);

         if(destination == null)
             destination = new PersonEntity();

         destination.Name = source.Name;
         destination.Organisation = _db.Organisations.Find(source.OrganisationID);
         //etc

         return destination;
    }

    public PersonModel Convert(PersonEntity source)
    {
         PersonModel destination = new PersonModel()
         {
             Name = source.Name,
             OrganisationID = source.Organisation.ID,
             //etc
         };

         return destination;
    }
}

By using these methods I take the duplication out that would otherwise occur in each controller. The use of generics can deduplicate things even further.

Doing things this way provides multiple benefits:

You can customise a model to a specific view or action. Say you have a signup form for a person that when submitted, creates many different entities (person, organisation, address). Without seperate MVC models this will be very difficult.

If I need to pass more information to the view than would otherwise be available just in the entity, or combine two entities into a single model, then my precious database models are never touched.

If you ever serialise an MVC model as JSON or XML, you only get the immediate model being serialised, not every other entity linked to this one.


问:
confusion regarding handling of new smart pointers on stack frames?
Let me try to elaborate it.

Stack Frame: When we execute any function it create stack where all local variables and instructions reside.

 And Smart Pointer: smart pointer like std::unique_ptr allows to change ownership of object inside of smart pointer.

Now my confusion is: suppose we pass a unique_ptr from a source function to a target function, the rvalue will be assigned to target pointer by std::move. Now if the function exits, the stack frame will deallocated. So will unique_ptr in target function be a dangling pointer, since unique_ptr is pointing to same memory location that resides in source function's stack frame?

One thing I thought is, since target function lifetime will be over before source function's lifetime. So that wont cause any such side effects. But in more complex applications with multi threaded environment, how does it go? Or what do we need to take care of?

答:
You're conflating two things: scope, which governs the lifetime of objects, and stack frames, which are an implementation detail, and aren't relevant here.

Now my confusion is suppose we pass unique_ptr from source function to target function, The rvalue will be assigned to target pointer by std::move

So you've explicitly moved ownership from the caller's unique_ptr object (in the source function) to the callee's unique_ptr (in the target function). The source's unique_ptr object no longer owns anything, and you can't dereference it.

Now, when the target function returns (or throws an exception - anything that causes its scope to exit), and the target's unique_ptr object is destroyed, it will delete the object previously owned by the caller's unique_ptr.

Control then returns to the source function, whose unique_ptr is still in scope but no longer owns anything. There's nothing you can usefully do with this object except assign it a new pointer to control.


问:
Legalities of modifying Ubuntu MOTD
I made few modifications to few specific Ubuntu files for showing my own custom messages in place of Ubuntu specific messages. For this, I have made changes to following files:

```<code>/etc/update-motd.d/00-header
/etc/update-motd.d/10-help-text
/etc/legal
/etc/os-release
/etc/lsb-release
/etc/dpkg/origins/default
/etc/issue
/etc/issue.net
/proc/version
</code>```

According to my research, there should not be any issue in modifying the /etc/update-motd.d/* files. However, I am not sure about rest of the files, especially /etc/legal file.

My question is that whether it is permissible to modify the above files? Is there any legal obligations which I need to respect? Any help will be highly appreciated :).

答:
Different parts of Ubuntu are licensed under different conditions. But according to the Ubuntu licensing page, one condition for being included into Ubuntu is a free license which allows the end-user to make modifications.

However, when you redistribute your changed version to other people, you need to follow the license conditions of each component. This usually means that you must not change any copyright messages and license files.

Title: Legalities of modifying Ubuntu MOTD


问:
Are the concept of database driven website and the CMS made website same?
I'm having little difficult time of understanding the few logics of web development.

Should I call home page, about page (or any other pages of a website whose contents change very rarely and no user interaction with them) etc the static pages? If yes then why should I put the contents inside a database and pull the data using a scripting language (php) instead of just put the content directly inside html so that the processing time of fetching data from database would be eliminated? why do people use database in this situation?

Suppose all of my web pages' contents never change, and I decide to put data in a database and made the website using CodeIgniter. Should the website be called a CMS made website or just a database driven website?

答:
Sometimes you simply make minor tradeoffs to gain simplicity. If your whole site is done using a certain technology then you just continue using it even for static pages where it would not always be mandatory (the processing time in this case is negligible).

Also many projects are done by larger teams, where the people doing the content do not even have much knowledge of how to write a static page in html. Just giving them a way to handle things like "about" pages as everything else will be simpler.

Then there is the issue of translations. Most good CMS can handle this in some way, most frameworks have some feature for this or at least there are plugins. With static pages this becomes difficult to handle. So if you need several languages or plan to do so some time in the future the option for static pages is mostly gone.

So as a conclusion I think if nothing else, then it's mostly about simplicity of the project as a whole. Have everything work the same way with the additional advantage of getting some extra flexibility for future improvements.


答:
A CMS means more than just storing your content in a database. The usual purpose of a CMS is to allow users to make changes to a website without requiring any technical expertise. It allows these users to log into a friendly user-interface which allows them to write, modify and publish content without any knowledge of HTML or any additional tools like an FTP client.

Also, not every CMS uses a database. It is completely possible to create a CMS which is backed only by flatfiles. I once wrote such a system myself.

To answer your question: When you use a CMS backed by a database, your website is both database-driven and CMS-built. But you can have a database-driven website which is not using a CMS, or a CMS-built website which doesn't use a database because the CMS doesn't use one.

Title: Are the concept of database driven website and the CMS made website same?

Body:
I'm having little difficult time of understanding the few logics of web development.

Should I call home page, about page (or any other pages of a website whose contents change very rarely and no user interaction with them) etc the static pages? If yes then why should I put the contents inside a database and pull the data using a scripting language (php) instead of just put the content directly inside html so that the processing time of fetching data from database would be eliminated? why do people use database in this situation?

Suppose all of my web pages' contents never change, and I decide to put data in a database and made the website using CodeIgniter. Should the website be called a CMS made website or just a database driven website?


答:
Don't insert the 2000 rows when the user posts something.

Instead, send a message thru a a message que saying "New post, ID is x". Then have a background process take the message off the que and process it, including generating notifications.

Basically, you return a web page to the user ASAP by only doing the essentials and then do all the heavy work on a background task that the user doesn't see, and thus can take as long as it wants (with in reason).


问:
How to measure his own skill in a programming language?

Possible Duplicate:

  How Can I Know Whether I Am a Good Programmer?

As many programmers I have worked in several languages. While of course there are some that I am more at ease than other, I do not have a real way to precisely measure my skill in a specific language.

So I thought of a system which allows me to help me with that. I am looking for 5 common criteria in programming languages, to which I will have a value from 1 (junior) to 4 ( Senior) to represent my skill.

I however have no real idea of the criteria I should choose for that.

Does anybody have suggestion ?

Thanks.

答:
I can't imagine of a system that will allow to measure someone's skills definitely even for a particular programming language. What may you need it for? Data structures and algorithms are common, and it takes half an hour to find the appropriate data structure implementation in the standard libraries (not always true, of course). So if you know what is a linked-list, you will probably use it correctly.

Moreover, criteria depend on the language, and cannot be common. Some programming languages provide more freedom to do everything you want (to shoot yourself in the foot) and some of them set boundaries you cannot go out from. So criteria vary from language to language.

If I need a developer to work on a web-service I want to implement using Java, I will probably hire someone who has built a complex system using django (Python) than someone how knows Java but have no experience on web-services. So here I measure the knowledge in a particular domain, not a programming language, because for this task I consider the domain knowledge more important than the implementation language.


问:
Illustrate Meaning of : gcc -g programName.c
To debug a C program using gdb effectively it is required to compile it first using the command:

```<code>gcc -g programName.c
</code>```

otherwise on using simply

```<code>gcc programName.c
</code>```

and running we are unable to provide gdb the Source Code i.e.programName.c
resulting in an error message -

```<code>dl-debug.c: No such file or directory.
</code>```

on demand for command like list in gdb.

Please Explain the Cause, Why it is like this.

答:
A debugger needs:

to refer to variable and function names, not their addresses (e.g. i not 0xdeadbeef and main() not 0x4B1D).

to associate the address of machine code with a line in the source code.

To this purpose the compiler builds (-g) a (augmented) symbol table (it may be embedded into the program or stored as a separate file). Sometimes other ancillary information are generated.

There are different formats to store these information (stabs, coff, dwarf...).

Contrarily to popular beliefs, many compilers (GCC for sure) write some symbols to an object file even in release mode (with the -O3 switch).
That's why even with a release binary, you can do:

```<code>$ gcc -O3 programName.c
$ gdb a.out
[...]
Reading symbols from a.out...(no debugging symbols found)...done.
</code>```

Of course this isn't enough for a good debugging experience.

Symbols can be removed from the binary using the strip command:

```<code>$ strip -s a.out
$ nm a.out
nm: a.out: no symbols
</code>```

and now:

```<code>$ gdb a.out
[...]
(gdb) b main
Function "main" not defined.
</code>```

Also consider that there is an interaction between code optimization and debugging:

some variables you declared may not exist at all;

the flow of control may briefly move where you did not expect it;

some statements may not be executed because they compute constant results or their values were already at hand

some statements may execute in different places because they were moved out of loops

...

So, with many compilers, you cannot turn on both optimization and debugging (GCC has the -Og switch for debugging optimized code).

Further details:

Preparing An Executable For Debugging

Options for Debugging Your Program

Body:
A debugger needs:

to refer to variable and function names, not their addresses (e.g. i not 0xdeadbeef and main() not 0x4B1D).

to associate the address of machine code with a line in the source code.

To this purpose the compiler builds (-g) a (augmented) symbol table (it may be embedded into the program or stored as a separate file). Sometimes other ancillary information are generated.

There are different formats to store these information (stabs, coff, dwarf...).

Contrarily to popular beliefs, many compilers (GCC for sure) write some symbols to an object file even in release mode (with the -O3 switch).
That's why even with a release binary, you can do:

$ gcc -O3 programName.c
$ gdb a.out
[...]
Reading symbols from a.out...(no debugging symbols found)...done.

Of course this isn't enough for a good debugging experience.

Symbols can be removed from the binary using the strip command:

$ strip -s a.out
$ nm a.out
nm: a.out: no symbols

and now:

$ gdb a.out
[...]
(gdb) b main
Function "main" not defined.

Also consider that there is an interaction between code optimization and debugging:

some variables you declared may not exist at all;

the flow of control may briefly move where you did not expect it;

some statements may not be executed because they compute constant results or their values were already at hand

some statements may execute in different places because they were moved out of loops

...

So, with many compilers, you cannot turn on both optimization and debugging (GCC has the -Og switch for debugging optimized code).

Further details:

Preparing An Executable For Debugging

Options for Debugging Your Program


问:
how to deal with different formats of 'time/date format'?
Different systems accepts different formats of formating time. E.g.

java, jquery: yyyy-MM-dd HH:mm

some jquery plugins: yy-mm-dd HH:MM

momentjs: YYYY-MM-DD HH:mm

ISO-8601: YYYY-MM-DD hh:mm

etc

On server I store time as Epoch time. And like to store some timeformat for user, so he see same format everywhere. But I just can't save and pass format string as it will be used differently. I saw various solutions, like restricting choice to 3-5 predefined options, and having list of these options in every system.

How to store time format and show formatted time-date to user in cost-effective way?

---- Example ----

I store time on server as 1412063513 value.  In browser  user want to see it as 2014-09-30 10:51. So he provide desired timeformat as 'YYYY-MM-DD HH:mm'. I save that format to server, but if i need to use it on server side (java) I got problems, as it is not valid due to capitalized letters. And when other systems trying to query data and format it, same problem arise.

答:
The more formats you support the more problems that will inevitably arise when dealing with datetime formats.

If you intend to validate the inbound value then (I'm sure I'm stating the obvious here but) I wouldn't recommend trying to create your own process to do this, as its often a minefield of problems. DateTime object in PHP is a good at handling a variety of input date formats simply, allowing you to validate and define the output format, therefore allowing you to store the value in a single format, as anom suggests in his comments above. momentjs.com also has similar capabilities. I'm sure lots of others also exist!

If you need to display the date-time again in the original format in which it was received, the only option I can see would be to identify the inbound format in the first place, store this format alongside the original value, and then use the DateTime object format method again using the stored format when building the output content.

Personally I would question carefully if users really need to see the output date in the original format. A standard format would be more consistent and much less of a headache for you in the long term dealing with new formats and bugs etc.


答:
Accept

There is no single or simple answer to this issue (I've been dealing with it for 30 years...) and your local solution will just depend on the technology, locale and tools that you have.

Storage

Use a storage mechanism that support date and datetime data types.  This will save you from re-inventing the wheel when it comes to validations and will provide you with a consistent internal storage and format you can rely on.  This will mean that in your storage you have addressed different date format by choosing one.

Display

Display according to local preferences and consider using the users locale to determine the format.  You will need to use a format that is accepted by either the users or the language or library(s) being used.

Input

Use a variety of mechanisms to tell the user the format they should use, including instructions, labels, input field autoprompt text, etc.  Consider using a 'word' for the month so that you can avoid, for example, the 12-01-2014 or 01-12-2014 issue (in the UK Dec 1st is 1/12, in the US it is 12/1) by using formats with month, e.g. dd-mon-yyyy which would use 01-dec-2014 for December 1st  This addresses the problems of different format in different libraries by defining the format to use.

Title: how to deal with different formats of 'time/date format'?

Body:
Different systems accepts different formats of formating time. E.g.

java, jquery: yyyy-MM-dd HH:mm

some jquery plugins: yy-mm-dd HH:MM

momentjs: YYYY-MM-DD HH:mm

ISO-8601: YYYY-MM-DD hh:mm

etc

On server I store time as Epoch time. And like to store some timeformat for user, so he see same format everywhere. But I just can't save and pass format string as it will be used differently. I saw various solutions, like restricting choice to 3-5 predefined options, and having list of these options in every system.

How to store time format and show formatted time-date to user in cost-effective way?

---- Example ----

I store time on server as 1412063513 value.  In browser  user want to see it as 2014-09-30 10:51. So he provide desired timeformat as 'YYYY-MM-DD HH:mm'. I save that format to server, but if i need to use it on server side (java) I got problems, as it is not valid due to capitalized letters. And when other systems trying to query data and format it, same problem arise.


答:
Your use case is this (please correct me if this is wrong):

Users post updates. Users can have subscribers. Subscribers see the
  updates, and can filter based on which ones they have not seen before.

Your data model then should not contain a notifications table listing the notifications per recipient.

The data model would look like this:

Users (user_id, name): the list of users

Subscriptions (from_user_id, to_user_id): the subscriber/author relationship

Posts (post_id, user_id, text): the authored posts, one record per post (linked to the user who wrote the message)

Visits (post_id, user_id, date): the date the post was first visited by a specific user

The set of posts that a user has not yet seen is then the set of posts from authors they are subscribed to, subtracted with the set of posts found in the visits table.

Both sending and reading a notification is then a single-row update.


问:
Application layer vs domain layer?
I am reading Domain-Driven Design by Evans and I am at the part discussing the layered architecture. I just realized that application and domain layers are different and should be separate. In the project I am working on, they are kind of blended and I can't tell the difference until I read the book (and I can't say it's very clear to me now), really.

My questions, since both of them concerns the logic of the application and are supposed to be clean of technical and presentation aspects, what are the advantages of drawing a boundary these two?

答:
The domain layer models the business of your application. This should be your clear interpretation of it's rules, it's component dynamics and contains it's state at any given moment.

The application layer is concerned with defining the jobs needed to be done to accomplish a certain application task. Mainly, it is responsible for mandate the necessary domain work and interacts with other (external or not) services.

For example, my financial software application has a user operation for changing the state of a model entity (entity as defined in DDD [89]):

"The Chief of operations can approve a financial proposal".

But, as an application process, besides all the model consequences of this operation, I have to send an internal communication to other users of the application. This kind of work is "orchestrated" in the application layer. I would not want my domain layer thinking about directing a messaging service. (and certainly this is not a presentation layer responsibility). Whatever way, one thing is for sure: I need a new layer as my domain layer is all about the core business and my presentation layer is all about interpreting user commands and presenting results.

Notes:

Business is one of those words that frequently lead to multiple interpretations of it's meaning but for sure you can find lots of examples and talk-about in DDD;

DDD stands for Domain-Driven Design book by Eric Evans and number inside square brackets for page number.

Title: Application layer vs domain layer?

ContentLicense: CC BY-SA 4.0


问:
Separating Code into Smaller Files in C
I am in the process of cleaning up my code and making it easier to maintain. I am doing this by turning my 5000+ line file into separate smaller files.

I have successfully created separate source and header files for obvious things like utilities and other components that are not tightly integrated with the application.

I am now thinking it would be good to break up the rest of my application into smaller files also. But the issue mostly concerning me is that everything that is left uses a bunch of Structs that are Globally declared.

So this is the choice moving forward (happy to hear other suggestions also):

1) I could leave everything in the same file and that way I could just define all functions as static (which has its benefits, and is often recommended). It is then a simple choice to leave the Globals at the top of this large source file.

OR

2) I could separate into smaller files. It is relatively simple to work out which parts should go into which new files. It is also not too difficult to work out the structural hierarchy (which parts call which parts). But I am uncertain on how best to deal with all these Globals. Where should they be placed, since every function uses them in some way?

NOTE: I am aware that the use of Globals should be avoided. However this is an embedded device with limited memory. Globals are the best way to reduce memory usage, and the more memory I save, the more I can perform a certain task.

答:
There is a third, hybrid alternative, which is to put each global into its own module and write functions to support it.  This gives you the OOP-y benefit of all code relating to the variable being isolated in one place and much easier to re-use elsewhere if needed.  Putting the support functions in the header so they can be inlined instead of forcing calls gives you the benefits of having everything in one big file.

For example:

```<code>// foo.h

typedef int FooType;

extern FooType foo_global_do_not_use_directly;

static inline void foo_init() {
    foo_global_do_not_use_directly = 0;
}

static inline void foo_set(FooType new_foo) {
    foo_global_do_not_use_directly = new_foo;
}

static inline FooType foo() {
    return foo_global_do_not_use_directly;
}
</code>```

.

```<code>// foo.c

// Always include the header even if you're not using a
// typedef so it gets compiled at least once.
#include "foo.h"

FooType foo_global_do_not_use_directly;
</code>```

You will, of course, have to go through the rest of your source and adjust every use of your globals to use the functions instead of referring to the symbols directly.  In the process, you may find other things that are done repeatedly and deserve to be their own functions, which may have benefits down the road if you ever need to change how those operations work.

Title: Separating Code into Smaller Files in C

Body:
There is a third, hybrid alternative, which is to put each global into its own module and write functions to support it.  This gives you the OOP-y benefit of all code relating to the variable being isolated in one place and much easier to re-use elsewhere if needed.  Putting the support functions in the header so they can be inlined instead of forcing calls gives you the benefits of having everything in one big file.

For example:

// foo.h

typedef int FooType;

extern FooType foo_global_do_not_use_directly;

static inline void foo_init() {
    foo_global_do_not_use_directly = 0;
}

static inline void foo_set(FooType new_foo) {
    foo_global_do_not_use_directly = new_foo;
}

static inline FooType foo() {
    return foo_global_do_not_use_directly;
}

.

// foo.c

// Always include the header even if you're not using a
// typedef so it gets compiled at least once.
#include "foo.h"

FooType foo_global_do_not_use_directly;

You will, of course, have to go through the rest of your source and adjust every use of your globals to use the functions instead of referring to the symbols directly.  In the process, you may find other things that are done repeatedly and deserve to be their own functions, which may have benefits down the road if you ever need to change how those operations work.


问:
How did you become a const correctness convert?
After 15 years of C++, I've still haven't learn to love using const. I understand it's use, but I've never actually been in situation where being const correct would have avoided the problem I was facing.

So how did you come to love benefits of consts?

答:
I was a convert as soon as I knew it was possible. It made sense to me from a 'good programming style' standpoint. There are various reasons for why it is good practice to be const correct:

Readability and understanding. If I'm reading someone else's code and a function takes a const reference as a parameter I know that the parameter is only meant to be used as a read-only variable. This is a massive win especially if the code is multi-threaded environment.

The compiler can make use of the const qualifier to aid its optimization passes.

Say I have an object of class A in a situation where I don't want it to change. Then the only member functions that can be called for that object are those that are const.


问:
translating a list of words (word1, word2 and word3)
We are trying to globalize an application and we have run into a situation where I'm not sure how (of if) we would go about formatting the string for globalization.  It's a paragraph explaining something with a list of names within it.  For example:

"Bob, Sue and Michael each received a point."

"Bob, Sue and Michael" is the string in question and can be one to many people.  What is the correct approach to translating the comma and "and" word?

答:
I'd say this is one of many localization scenarios where you'll have to admit a simple "key/language/value" storing pattern isn't enough. :)

I'd personally create a localization engine class with a method that'd take a list of words and a language as parameters. This method would build the "list" segment of your string. Once you have this, concatenate the result to the rest of your sentence and you'll have your complete, final string.

UPDATE:

Although IMHO this is a bit outside your question's scope, you might want to give some thoughts to Konrad's comment below. Depending on how many / which languages you have to support, it might be necessary for your localization engine to be in a higher layer of your app. It might have to know about the context and produce your complete string.

Not to say you cannot still process the "list" part at a lower level, though. But then it would likely be for a limited set of languages only.


问:
Decision making and maintenance
I'm trying to find an elegant way to implement a decision making algorithm that allow easy maintenance because the conditions for the decision making might change often.

I'm going to try and be more specific with an example here :

Let's say I'm trying to manage a team of Cooking chefs in a restaurant kitchen.

Every chef knows how to cook 3 types of pies : Apple pie, pumpkin pie and raspberry pie and 2 types of pizza : cheese pizza and bacon pizza. They all know how to cook everything.

Now, I would like to send orders to these chief regarding what's coming for the clients.

The conditions are :

A chief can only cook one pie at a time. If I order a chef to cook an apple pie for example, I cannot order him to cook a raspberry pie or a pumpkin pie unless the apple pie is done or I send an cancel request for the apple pie.

I can ask a chef to cook up to 5 pizzas at a time, given it's for different clients.

I woud like to create an algorithm that returns the set of orders I'm allowed to send to a specific chef, regarding what he already is cooking.

I'm working with c++. I could write a simple switch/case statement, but the maintenance would not be easy if conditions change or new pies are added, and so...

I'm kinda stuck and really don't see how I could encapsulate the conditions and decision making to decrease couplign beetween conditions and to allow easy maintenance on the conditions of pie cooking.

How would you handle complexe decision making algorithm implementation?

答:
I can't see this needing a switch statement. Here's how I would design this. I would have some sort of controller or manager object, that assigns tasks. This object would know

a list of chefs

a method you can call on a chef, like "are you free?"

a method you can call on a check to ask if it's capable of cooking something, assuming it's free

You ask this object "get me someone to do a raspberry pie" and it loops through the chefs till it finds a free one, asks if it can do raspberry pie, and if so, assigns that to it.

Meanwhile in the chef object you need to know what you can cook, your capacity of each thing, and what you're cooking right now. You're not cooking anything, you get asked if you're free, you say yes, you get given something to cook so you track that, and if you're asked again before it's finished, you say no.

With your complication of one pie but five pizzas, you might combine the "are you free" and "can you cook" questions into "are you free to cook X?" which you would say no to whether it's because you don't know how or because you're busy. That way someone with two pizzas on the go will say yes to a pizza but no to a pie.

The assigner object also needs to figure out what it will do if all the chefs say they are busy. Probably wait and ask again since chefs will finish what they're doing and become free. You might do this with pause-and-poll, or by having chefs signal the assigner once they're free.

The key to me is that the chefs know what and how much a time they can cook, not the assigner. The assigner knows how many chefs there are. Adding new pies means updating the chef class (possibly just a recompile if the list of pies is an enum and all chefs can always cook all kinds of pie) and whatever code decides that it's time to make raspberry pie now. Generally the assigner code won't need to change under these circumstances - it's still looping through the chefs asking "can you do a cheese pizza yes or no?" and if it gets yes, assigning that to the chef and returning.

Title: Decision making and maintenance


问:
Converting from AppHarbor to Azure
I'm thinking of switching my cloud provider from AppHarbor to Azure. Main reason, I love the ability of being able to scale up the number of workers as traffic/cpu usage gets really high.

My question is, how to coordinate this transition for users that still point to *.apphb.com instead of www.{mycustomdomain}.com.

I saw in a "SEO Friendly URLs" blog post that the proper response code when navigating to old URL paths is to do:

```<code>return RedirectToActionPermanent("{actionname}", "{controllername}", new { int? param1, string param1 } );
</code>```

Where the "Permanent" is added. I guess it returns a 301 instead of a 302 which tells google-bot crawlers to permanently redirect their mappings/indexes to the new URL.

So, in my code, do I add a line that checks to see what URL is processing the request (this is assuming that I leave the app harbor site running, but without the custom domain pointing to it), and if it's app harbor, then issue a 301 to the corresponding crawler to go to the new URL, but how to notify the "human" user?

Is there a better way to do this?

答:
You could use the simple meta refresh method - http://en.wikipedia.org/wiki/Meta_refresh

Or you can use as you have stated a 302 Redirect - http://en.wikipedia.org/wiki/HTTP_302

With the 302, you can perform this in your server side code, or if the AppHarbour web server allows, you can configure it to perform this task.

As for performing different tasks depending on whether it is a bot or a human loading the page. You can do this with your server side code by looking at the GET request header, where is will identify its self with HTTP_USER_AGENT header.

Title: Converting from AppHarbor to Azure


问:
How do I compile my software for all platforms from Ubuntu Linux 64 bit?
I write a lot of open source software that I make available on my website.   How do I get my software compiled for all relevant platforms including:

Windows

OS X

Linux 32 bit deb

Linux 64 bit deb

Linux 32 bit rpm

Linux 64 bit rpm

etc

I currently only have Linux 64 bit boxes, so I can only compile the 64 bit deb and rpm myself.   I'm relying on users contributing other versions.   That isn't ideal because the versions are not all available right after a new release.  Indeed the Windows binary is several versions behind at this point.

Edit: My software is QQWing. It is written in C++. I would love to have a build system that can generate binaries for all platforms, or have a place to run builds for multiple systems.

答:
Any professional organisation would have not just build machines but test environments for all those platforms they support.

And that's why most professional organisations won't support such a plethora of platforms, it's just too expensive for the small return that each of them yields except the few big ones like for example Windows, Mac, and RedHat based Linux.

So you'll have to get the hardware to run all those operating systems, the compilers and other tooling for all of them as well. Or maybe you can get away with running all those OSs in virtual machines, if your hardware is up to the task.


问:
Are there any actual examples of profitable programmer's "worker's cooperatives"?
http://en.wikipedia.org/wiki/Worker_cooperative

I'm curious whether there are, anywhere in the world, worker's cooperatives that center on a technology business that involves either programming, IT, or some sort of IT or programming related consulting or services.

The wikipedia link above is an overview of the concept. The short form explanation is that a co-op is a worker-owned business. Also there is the notion that every worker owns shares in the business.

I am interested in knowing whether an example of a "programmer's/IT co-op" even exists.

Note: I am not talking about nor asking about a government-funded incubator nor any other socialized, state supported group. I also don't mean "co-working", which is renting an office with other self employed people doing their own thing.

I mean a going, profitable IT business operating in a competitive environment that is worker-owned and run.

答:
software.coop

We're a tech worker co-op providing web design, system administration, software development and other computer-related services.


答:
I'd go with your Option 1: leave the globals in a single file where it's easy to find them.

As you've noted in the comments, this is not OOP.  The "rules of OOP" (while very good in the general sense) don't necessarily apply to a smallish project on an embedded device.

5000 lines in one file is a pain to work with.  5000 lines in a solution is pretty small.  If you've already moved the other stuff out, chances are what's left isn't all that big.  If you split it up you'll just spend a lot of time searching for the one global you want to change.

Remember, the goal is to keep the code organized so you can clearly follow the structure, make needed changes (and understand their impact) and separate "stuff that changes" from "stuff that doesn't".

OOP is the common way of meeting that goal on modern general purpose computers.  It's not the only way to do things, and it may not be the best way on a memory-limited embedded device.

Title: Separating Code into Smaller Files in C

Body:
I am in the process of cleaning up my code and making it easier to maintain. I am doing this by turning my 5000+ line file into separate smaller files.

I have successfully created separate source and header files for obvious things like utilities and other components that are not tightly integrated with the application.

I am now thinking it would be good to break up the rest of my application into smaller files also. But the issue mostly concerning me is that everything that is left uses a bunch of Structs that are Globally declared.

So this is the choice moving forward (happy to hear other suggestions also):

1) I could leave everything in the same file and that way I could just define all functions as static (which has its benefits, and is often recommended). It is then a simple choice to leave the Globals at the top of this large source file.

OR

2) I could separate into smaller files. It is relatively simple to work out which parts should go into which new files. It is also not too difficult to work out the structural hierarchy (which parts call which parts). But I am uncertain on how best to deal with all these Globals. Where should they be placed, since every function uses them in some way?

NOTE: I am aware that the use of Globals should be avoided. However this is an embedded device with limited memory. Globals are the best way to reduce memory usage, and the more memory I save, the more I can perform a certain task.