问:
Call the database every time, or create an object in memory, and if so, how and how often to update?
I'm creating an app in javascript/nodejs and using neo4j as database.

Let's say I have an entity User in my database. It has a bunch of properties, like boxes_collected and places_visited, which keep updating independently of one another throughout the course of running my app.

So far I have functions that talk to the database to update these properties directly. But it's getting a bit messy and I'm thinking of making a single high level object/class that handles everything in a much cleaner, nicer, and eloquent way.

Here's a tiny version of my "model" to better explain what I mean:

Suppose I have a function like this

```<code>function UpdateUserValue_plants(number) {// update database}
</code>```

But then if were to create a User object and incorporate the above into it,

```<code>var User = function User(plants, other...) {
    this.plants= plants;
}

User.prototype.updateValue_plants = function(number) {
    this.plants += number; // first update the model itself
}
</code>```

Then when am I supposed to update the database? And wouldn't I be doing the updatation twice that way: first the object's property, then the database?

Is there an elegant solution to this?

答:
There's no easy way to tell you when your application should update the database. That's what designing programs is about and only you can decide that.

For DB connection management though, one thing you'll find is that most DB connections support pooling. When you get a connection only the first time will it take the expensive step of making the connection, after that when you release it, it will not be torn down immediately but will go into a pool where you can retrieve it later, very quickly.
This means you do not have to store a single DB connection in your code as a global or similar to use, you can 'create' a new connection as needed.

You might want to look into an ORM to give you more of an object view of your database which seems to be what you're asking for.


问:
What are my options for using a C++11 library in a C# WPF application?
I am writing a cross-platform (OS X and Windows) desktop application in C++11. I intend to use the same C++11 core on both platforms, utilizing native frameworks for the UI (Cocoa and Objective-C on OS X and WPF and C# on Windows) as I believe the best UX experience is a native one.

Currently the application runs as a console app on both platforms. The application performs some CPU-intensive work and provides callbacks for progress reporting and, when complete, instantiates a collection of Items (std::vector<std::unique_ptr<Item>>) representing the results of the processing.

My goal is for the C++11 library to act as a model for the UI in a manner compatible with the MVC and MVVM patterns.

The UI must:

Allow the user to choose a file to process (open a file dialog and send the file path to the C++ library)

Display progress (handle callbacks from the C++ library to update a progress bar)

Display the results in a WPF form (access the Item class and display information it provides)

I've looked at WinRT and it seems there isn't a lot of information out there for use in desktop applications.  I'm also not fond of the idea of creating the UI itself in C++.  My goal is to get data in and out of the C++ app and use C# to handle the UI as I believe that's a more efficient way of working with WPF.

I'm aware of P/Invoke but my understanding is that it only works with a C interface. Creating such an interface around the C++11 seems cumbersome.

I'm also aware of C++/CLI but I'm not sure if that will meet my needs or if it is compatible with C++11.

I took a look at CppSharp but it seems to be a work-in-progress and I doubt I'd know how to work around any issues that may arise.

I have a lot of experience with C++ and a little with C# but I'm not sure if I'm missing better options or which of the above is a sound approach.

答:
What is a native UI on Windows any more? WPF doesn't look 'standard', winforms and MFC are dead, like Silverlight. It could be said the most native of apps are now HTML, especially if you're writing Windows8 tiles.

So my suggestion would be to use wxWidgets which uses native controls to render. Your UI will look like a traditional Windows program rather than a "Modern" one, but that's what you were after isn't it?

If you do still need to use WPF for the GUI, you can write a C++/CLI interface wrapper that calls your C++ dll, or you could expose your dll as a service and let the WPF make socket (or other RPC) calls into it. If its very chatty, this would not be the best solution, but if it makes few, long-running calls then its ideal. A service would also be the best solution to bind a web front-end to your dll as well, though I'd expose the service as a WWS web service in this case.

ContentLicense: CC BY-SA 3.0


答:
You're going to have to connect to the server once for each update anyway, so I wouldn't worry to much about updating the property.  It depends on your architecture but it's probably not best to have your database communication code mixing with your BL code SOC and all.  If you're worried about making multiple database connections though you can paint the cached objects after they are updated and have a manager persist them to a database at some other time. However, it can get a bit mucky dealing with a cached object and the DB you need to make sure you know what is Synced and what isn't.

I would recommend as @gbjbaanb suggested, looking into an ORM.  An ORM is basically doing what your talking about right now, it updates an object in code then persists that data to the database on save.

Title: Call the database every time, or create an object in memory, and if so, how and how often to update?

Body:
I'm creating an app in javascript/nodejs and using neo4j as database.

Let's say I have an entity User in my database. It has a bunch of properties, like boxes_collected and places_visited, which keep updating independently of one another throughout the course of running my app.

So far I have functions that talk to the database to update these properties directly. But it's getting a bit messy and I'm thinking of making a single high level object/class that handles everything in a much cleaner, nicer, and eloquent way.

Here's a tiny version of my "model" to better explain what I mean:

Suppose I have a function like this

```<code>function UpdateUserValue_plants(number) {// update database}
</code>```

But then if were to create a User object and incorporate the above into it,

```<code>var User = function User(plants, other...) {
    this.plants= plants;
}

User.prototype.updateValue_plants = function(number) {
    this.plants += number; // first update the model itself
}
</code>```

Then when am I supposed to update the database? And wouldn't I be doing the updatation twice that way: first the object's property, then the database?

Is there an elegant solution to this?


问:
What is the difference between requirements and specifications?
I've been tasked with developing requirements and specifications for a project our group is starting.

I realized that I don't know the difference; a Google search just confused me more -- it seems some people say that specifications are requirements, but at a lower level.

答:
One way, maybe not the right way, to look at it:

Requirements are things (capabilities, features, behaviours, etc) that yield value to the user. Not concerned with internals; only the box's inputs and outputs (and maybe size, shape, and colour) are important here.

Specifications are things (capabilities, features, behaviours, etc) that enable that value for the user. Here the box internals are important, because along with the external interfaces and characteristics mentioned above they define the entire system.


问:
Should front-end integration tests make HTTP requests?
I am developing a single-page web application using AngularJS. Data for this application is consumed over a REST API which is well tested in its own right.

The Angular application has a bunch of unit tests that test e.g. individual controllers and their methods. It also has a bunch of integration tests that currently verify that those controllers behave correctly when applied to a view.

Both the unit and integration tests are currently sharing a set of stubbed JSON data that is returned when certain HTTP requests are about to be made (by way of the $httpBackend Angular service). No actual HTTP requests are sent to the API server during testing.

Is this a good approach for front-end integration testing? The way I see it, the unit tests are testing small units of code (such as individual methods in controllers) and the integration tests are testing the way those units behave in the wider context of a view or template. The setup allows the front-end application to be tested completely independently.

However, the developers of Protractor (the integration testing framework I'm using) have stated on numerous occasion that they believe integration tests should make HTTP requests to a real server (see this GitHub issue):

Protractor is intended for end to end tests, so the primary use case is when you have an actual backend hooked up.

Assuming the answer to the above question is "yes" (or "maybe"), should there be a third set of tests that do actually test the communication between front-end application and REST API?

答:
It is useful to have automated functional tests that test the front-end while mocking away the server, but they are not integration tests. They still test a component in isolation, nothing is integrated. They are functional tests of the component.

To qualify as integration test, the test should test that all the components of the final solution integrate, that is work together. For this it needs the complete setup. With the real server and real database loaded with realistic sample data and no mocks at all. You do want to have such test.

The integration tests (of the complete setup) are the most important. They test all the code that will be involved and you should do that before you put any trust in the application. What other tests you want is a matter of balancing the effort to create them with the benefit they bring. The main benefit of tests of individual components is that they allow easier debugging than the integration tests, so write those tests that help you in debugging. Which they are depends on complexity of setting up the various components and is therefore specific to the project.


问:
Pythonic design for controlling multiple devices through an I2C bus
I'm writing a piece of software in python that will communicate with a bunch of devices via an I2C bus. Each of these devices are going to need some sort of a module or class to handle the communication and data conversion in some sensible way. The operations that each of the device modules perform are drastically different.

My main concern is the I2C bus control. I fear that sharing the bus, by for example having each of the device modules instantiate a new I2C bus control object results in code that is hard to follow and I'm not sure how these objects would communicate if the there's an interrupt in the bus. However, not sharing it, I fear I'll end up with a huge control class that is hard to maintain and extend.

If I lean towards the control class, each of the device modules would hold a map of operations, like an OrderedDict or a list of tuples of functions with expected result values or ranges. The I2C control object could then iterate that dictionary, write and read the results from the bus and move to the next function if the result is in the expected range. This sounds like a state machine design, but I'm not sure if I can really generalize all operations enough.

I suppose my question boils down to does anyone have a good suggestion for a design pattern?

答:
Not as pythonic as you want it, but I think you just want to have the i2c control object only be a bus arbiter, not a device controller; each different device object can instantiate its own copy of the i2c bus object and communicate to the bus as if it has exclusive access to the bus.  This greatly simplifies the device object programming.  I don't see how this results in code that is hard to follow. Think of this as just the device driver logic.  The layer one level up from this will be your system logic layer, which instantiates devices and communicates to the devices via their object interfaces.

Your i2c bus object can have class methods and class attributes (such as mutexes, read queues, write queues, etc) that the users of the class don't need to know about. The users of the class , which are instances of the device objects, simply call read and write methods of the i2c class.

Your device objects would then present an attribute and method interface that makes sense for the underlying physical device on the bus. For example, only your device object for the left arm of your robot knows that the method of its class "setPowerLevel(x)" results in any particular i2c bus operation. Data conversion to or from a BCD value as needed by the device on the i2c bus would be done by your device object, perhaps with the help of helper functions on the i2c bus object.

I wasn't sure where you were headed with the OrderedDict. It seems like you wanted to somehow give all the devices's possible operations and data values/expected data into some iterable object, and have some uber-controller iterate and send/receive data that way. To be honest I think that just makes the code harder to read, actually. I think devices are devices, you can create an object model for devices but you shouldn't try to objectify them so much to squeeze them into a one-size-fits all interface. You can still have classes (in the conceptual way) of different objects grouped together under several different base classes, where each base class represents similar types of devices (i.e. memory, motor control, displays, etc)...


问:
should I store common data between two tables in a third separate table in my database?
If I have 2 tables in my database, let's say for instance 'buyers' and 'sellers' but I collect a common set of data for both for instance telephone number, email address, address etc. Is it  better practice to have one common table for 'contact_details' with a reference to the table and row that the contact details are for, or as they are seperate entities are they better off in seperate tables entirely?</p>

答:
Impossible to say in general.

The more fields your contact data have, the bigger the risk that maintaining these data requires duplicated code. But the more often you retrieve buyer and seller records, the bigger the risk that the JOIN required by having a separate table becomes a performance bottleneck.

As you see, the decision has both run-time and development time consequences, and the thing to do is to estimate what your typical usage pattern will be. Then you will know whether normalizing your schema is an overall advantage or not. (When in doubt, measure - performance trade-offs are notoriously hard to predict.)


答:
If 'buyers' and 'sellers' share a lot of data, maybe they're actually just 'contacts', with associated contact information. Whether each contact is a buyer or seller would depend how they were used.

For example, you might have both 'sales' and a 'purchases' table. Each would have a 'contact_id' column, that linked to the primary key in the 'contacts' table.

Title: should I store common data between two tables in a third separate table in my database?

Body: If I have 2 tables in my database, let's say for instance 'buyers' and 'sellers' but I collect a common set of data for both for instance telephone number, email address, address etc. Is it  better practice to have one common table for 'contact_details' with a reference to the table and row that the contact details are for, or as they are seperate entities are they better off in seperate tables entirely?</p>


问:
Fetching instructions from memory
So, I am a noob in assembly language and machine instructions.

When the discussion came up as to how funtion calls are implemented at the processor level, someone said that the CALL instruction pushes the address of the next instruction to be executed on the stack before updating the EIP and then someone asked how do we know the address of the next instruction.

And then someone asked while EIP points to the current instruction in memory how does the processor know how many bytes from EIP need to be read so that the whole instruction is read.

I assumed that all instructions are fixed length so the processor would read those many bytes as would constitute the instruction and then the decoding process would determine how many more bytes need to be read to fetch the operands.  However when searching about the instructions I came to know that the instruction sizes vary.

So we are back to the same question:
How does the processor know the number of bytes to read to get the instruction from memory to the instruction cache?

答: In most CPUs, the next-instruction-pointer is updated as the first part of executing the instruction.  The CPU, of course, can determine the length of the instruction from its opcode and/or modifier bits.  Every architecture has a different way of indicating this, but it is always well defined.</p>

Title: Fetching instructions from memory


答:
I would suggest three tables: contacts, buyers and sellers. All of the common data are kept in contacts and anything specific to being a buyer and/or a seller would be contained in those tables with some sort of 1:1 relationship. The fact the relationship exists categorizes them as a buyer and/or a seller.

If you never needed a combined list of the two (of course you can union two tables) or the ability to maintain a single contact that may belong two both, you wouldn't have to worry about it.


问:
How to support the sales team and avoid the "Often the sales team gets us into trouble just to get a commission" problem
With reference to this answer:

At the end of the day, we are delivering a product to a paying customer. This customer has needs and expectations, realistic or not. Often the sales team gets us into trouble just to get a commission.

I realise there are processes (mainly with communication and project managment) that can help minimise risk (these seem to have minimal impact, mainly due to being ignored by anyone other than dev) and believe a percentage of the problem is their complete lack of technical understanding rather than greed (though this does play a part). But when it isn't possible to get rid of commissions (very good article), get (train) better salesmen, or increase dev resources, how can you minimise the impact on developer moral, timelines and generally development department being held responsible?

How common is this damaging to the business (and no one higher up will believe how much better it could be - they don't see any problem now, but wonder why sales fall through and customers aren't happy) and how do others mitigate the risk, prove development is not the issue and handle such situations where the marketing is too aggressive and overselling is normal (which all propagates from the top)?

How can you support the sales team and upper management to improve the root cause of this situation and what changes can be implemented in dev department to help with this?

Additional information: the is only one product we create and as such is sold with additional functionality as required or work to let it integrate with existing systems.

I was worried about close votes, but this is a very real problem (and I have tried to word it objectively)- if you can comment on how to improve this question, please let me know.

答: I would change the structure so that the sales people get their commissions not when the contract is signed, but when the product ships. That way if they sell stuff that you can't build they don't get paid.</p>


答:
Are you sure these requests aren't deal killers? i.e. the customer will not buy your product at all if they are not met. You'll be in no position to argue otherwise.

complete lack of technical understanding

Sorry, the dev team or someone with more technical knowledge may need to get involved with these requests. Just ask to try it with one client and see how it works. Maybe there are workarounds? You may discover this was a "nice" to have instead of a "must" have. Sales people are taught to never say no. Programmer morale may improve if they see themselves as part of the sales process. They may not get commissions, but bonuses and raises are affected by company sales. Show you're part of the solution.

Start putting together internal time quotes to upper-management so they know how much this is costing the company. If bug fixes and enhancements are on a tight schedule, what is the priority? They may discover they are leaving money on the table and could be charging customers to add these features at the customer's request. Otherwise, offer to consider adding it for the next release if it is a good idea for the app.

At least start asking "why" a request is being made. The goal is for you to have the most comprehensive understanding of the problem so you can provide the best solution (I should be a salesman!). This is NOT a form of pushback. You might be surprised at the answers and make a better product.

Title: How to support the sales team and avoid the "Often the sales team gets us into trouble just to get a commission" problem

Body:
With reference to this answer:

At the end of the day, we are delivering a product to a paying customer. This customer has needs and expectations, realistic or not. Often the sales team gets us into trouble just to get a commission.

I realise there are processes (mainly with communication and project managment) that can help minimise risk (these seem to have minimal impact, mainly due to being ignored by anyone other than dev) and believe a percentage of the problem is their complete lack of technical understanding rather than greed (though this does play a part). But when it isn't possible to get rid of commissions (very good article), get (train) better salesmen, or increase dev resources, how can you minimise the impact on developer moral, timelines and generally development department being held responsible?

How common is this damaging to the business (and no one higher up will believe how much better it could be - they don't see any problem now, but wonder why sales fall through and customers aren't happy) and how do others mitigate the risk, prove development is not the issue and handle such situations where the marketing is too aggressive and overselling is normal (which all propagates from the top)?

How can you support the sales team and upper management to improve the root cause of this situation and what changes can be implemented in dev department to help with this?

Additional information: the is only one product we create and as such is sold with additional functionality as required or work to let it integrate with existing systems.

I was worried about close votes, but this is a very real problem (and I have tried to word it objectively)- if you can comment on how to improve this question, please let me know.


问:
How to avoid too much html in JQuery?
I'm not liking how my JQuery is after making some dynamic buttons, or other dynamic things. For example, when I have checkboxes marked, I add a button that is called "Download Selected" and "Remove Selected". Of course, there are many more JQuery + HTML things in my site.

I'd like to know how I can make my code better, not spaghetti looking.

Thanks a lot!

```<code>  $(document).on('change', '.docListCheckbox', function(event){
    if( $('#resultsContainer').find('.docListCheckbox:checked').length > 0 )
    {
      if( ! $('#download-sel').length > 0 )
      {
        var downSelectionBtn = '<button id="download-sel" class="button-small button-blue" type="button">DESCARGAR MARCADOS</button>';
        var delSelectionBtn = '<button id="delete-sel" class="button-small button-red" type="button">ELIMINAR MARCADOS</button>';
        $('#selection-controls').append(downSelectionBtn);
        <?php if( SwHelper::checkAccess('Docusearch.Documento.Eliminar') ): ?>
        $('#selection-controls').append(delSelectionBtn);
        <?php endif; ?>
      }
    }
    else
    {
      if( $('#download-sel').length > 0 )
      {
        $('#download-sel').remove();
        <?php if( SwHelper::checkAccess('Docusearch.Documento.Eliminar') ): ?>
        $('#delete-sel').remove();
        <?php endif; ?>
      }
    }
  });

 $(document).on('click', '#docActionEdit', function() {
    var button = $(this);
    var isToggled = button.data('toggled');
    $('#docDataEditor').slideToggle({
      duration: 1000,
      easing: 'easeOutBounce',
      start: function(){
        if(isToggled == 'false') {
          button.html('EDITAR');
          button.data('toggled', 'true');
          $('#docActionSave').remove();
        }
        else {
          button.html('CANCELAR');
          button.data('toggled', 'false');
          $('#docAvailableActions').prepend('<button id="docActionSave" class="button-small button-green">GUARDAR</button>');
        }
      }
    });
  });
</code>```

答:
Note: I would be more worried about mixing PHP and JavaScript, like you do in your example.

Typically, it is bad practice to use language X to generate code in language Y.

It also reminds me of this The Daily WTF article: Client-side PHP.

To answer your question:

The easiest way would be to keep HTML inside HTML. Why are buttons added dynamically, and don't exist in the version which is shown to people with no JavaScript? If they can be used only with a feature which requires JavaScript, shouldn't it be possible to have the buttons directly in HTML, hidden by default, and then shown with JavaScript on demand?

If there are large pieces of HTML (not the case in your example), generate them server-side and then load them on demand through AJAX.

If there are pieces of HTML which are duplicates of HTML generated server-side (not the case in your example, I imagine), generate them server-side and then load them on demand through AJAX, avoiding code duplication (which is, in the case where two languages are involved, particularly difficult to detect later).

If you just need to add short amounts of HTML code, the comment by superM already gives you the answer: just put the HTML in a variable you'll treat as a constant in your code.

When relevant, don't forget to use templates. Google Closure Templates is one example of templating with JavaScript.

Title: How to avoid too much html in JQuery?


问:
Why is the json format necessary over the normal javascript object format?
Before you answer, yes I know that other languages have no native javascript object support, but neither do they have native support for json.

So wouldn't it make much more sense to modify the json spec to allow identifiers without "" and allow comments? Very sensible things because you don't have to serialize/deserialize when working in javascript, no?

答:
JSON is a data interchange/serialization format. It's not code intended to be written by humans, but human-readability is important. Given these requirements, JSON is the simplest subset of JavaScript that could possibly work.

For example, we need to allow quoted keys in objects. But if we already have a quoted syntax, there is no need to support unquoted keys as well. Likewise, JSON knows only "..." double quoted strings, single quoted strings '...' do not exist.

The result is that it's really easy to implement a JSON parser (maybe 20 lines with a nice parser generator). We wouldn't want to throw that advantage away (which helped become JSON so accepted. Contrast with the complexities of parsing XML). Of course, a production-ready implementation should be lenient in what it accepts.

Could a change like this be retro-fitted into the standard? No, because backwards compatibility. Feel free to write a JSON implementation that accepts unquoted keys, but you can never emit such a string, in case the receiver uses a stricter implementation. And because you generate all your JSON via a library instead of writing it per hand, adding those quotes isn't any extra burden.


问:
How do I manage a very large set of rules and magic numbers in my program?
I'm somewhat new to programming (I'm a mechanical engineer by trade), and I'm developing a small program during my downtime that generates a (solidworks) part based on input from various people from around the plant.

Based on only a few inputs (6 to be exact), I need to make hundreds of API calls that can take up to a dozen parameters each; all generated by a set of rules I've gathered after interviewing everyone that handles the part. The rules and parameters section of my code is 250 lines and growing.

So, what is the best way to keep my code readable and manageable? How do I compartmentalize all my magic numbers, all the rules, algorithms, and procedural parts of the code? How do I deal with a very verbose and granular API?

My main goal is to be able to hand someone my source and have them understand what I was doing, without my input.

答:
I'm not sure I got the question correctly, but it sounds like you should group things in some structures. Say if you are using C++, you can define things like:

```<code>struct SomeParametersClass
{
    int   p1;  // this is for that
    float p2;  // this is a different parameter
    ...
    SomeParametersClass() // constructor, assigns default values
    {
        p1 = 42; // the best value that some guy told me
        p2 = 3.14; // looks like a know value, but isn't
    {
};

struct SomeOtherParametersClass
{
    int   v1;  // this is for ...
    float v2;  // this is for ...
    ...
    SomeOtherParametersClass() // constructor, assigns default values
    {
        v1 = 24; // the best value
        v2 = 1.23; // also the best value
    }
};
</code>```

You can instanciate these at beginning of program:

```<code>int main()
{
    SomeParametersClass params1;
    SomeOtherParametersClass params2;
    ...
</code>```

Then your API calls will look like (assuming you can't change the signature):

```<code> SomeAPICall( params1.p1, params1.p2 );
</code>```

If you can change the signature of API, then you can pass the whole structure:

```<code> SomeAPICall( params1 );
</code>```

You can also group all the parameters into a larger wrapper:

```<code>struct AllTheParameters
{
    SomeParametersClass      SPC;
    SomeOtherParametersClass SOPC;
};
</code>```

Body:
I'm not sure I got the question correctly, but it sounds like you should group things in some structures. Say if you are using C++, you can define things like:

struct SomeParametersClass
{
    int   p1;  // this is for that
    float p2;  // this is a different parameter
    ...
    SomeParametersClass() // constructor, assigns default values
    {
        p1 = 42; // the best value that some guy told me
        p2 = 3.14; // looks like a know value, but isn't
    {
};

struct SomeOtherParametersClass
{
    int   v1;  // this is for ...
    float v2;  // this is for ...
    ...
    SomeOtherParametersClass() // constructor, assigns default values
    {
        v1 = 24; // the best value
        v2 = 1.23; // also the best value
    }
};

You can instanciate these at beginning of program:

int main()
{
    SomeParametersClass params1;
    SomeOtherParametersClass params2;
    ...

Then your API calls will look like (assuming you can't change the signature):

 SomeAPICall( params1.p1, params1.p2 );

If you can change the signature of API, then you can pass the whole structure:

 SomeAPICall( params1 );

You can also group all the parameters into a larger wrapper:

struct AllTheParameters
{
    SomeParametersClass      SPC;
    SomeOtherParametersClass SOPC;
};


问:
How does assembly relate to machine/binary code
How does assembly relate to machine/binary code.

For example here is how to print to the screen in mikeOS(a small pure assembly OS), mikeOS it uses NASM to assemble.

```<code>BITS 16
    ORG 32768
    %INCLUDE 'mikedev.inc'

start:
    mov si, mystring
    call os_print_string

    call os_wait_for_key

    ret

    mystring db 'My first MikeOS program!', 0
</code>```

Where os_print_string and os_wait_for_key are defined as

```<code>os_print_string     equ 0003h   ; SI = zero-terminated string
</code>```

and

```<code>os_wait_for_key     equ 0012h   ; Returns AL = key pressed
</code>```

in mikedev.inc respectively and defined as

```<code>os_call_vectors:
    jmp os_print_string     ; 0003h
</code>```

in kernal.asm

Now nasm must do a lot more work under the scene when assembling, I have no idea what.

In other words assembly language is a wrapper to some degree to machine code just as say C is a wrapper to assembly. If I said cout >> "Hello World" for example in C++, this is then compiled into it's assembly equivalent and them assembled into machine code.

So I am trying to understand out how 0003h and 0012h seem to dictate everything that is going on when printing to the screen. How do these two values,

a) Tell the CPU/PC system which bus to send the corresponding bytes that represent the required string to the monitor bus and not say to the sound card.

b) In this case the string is sent to the monitor, obviously, now my understanding is that you have a frame buffer that can store a maximum number of bytes. So say the resolution of your screen is set at 1024 x 768 which is 786432 pixels and a refresh rate of 60hz on the screen, therefore the FB will contain this number of byte values and hence will be sending this many bytes to the monitor every 1/60 sec. The first byte in the FB corresponding to the first pixel on the screen and the last to the last on the screen etc.

So how does the CPU/GPU know which byte to put in which position in the FB. It's like saying to the GPU 'ok I need this pixel at coord (245,232) green so I will leave it to you to put this pixels value in the correct position in the FB' etc.

How does this work.

答:
Assembly language translates almost directly to machine code. mov becomes a mov instruction. call becomes a call instruction. The arguments on the same line become the argument fields for those instructions. There's a bit of assistance in computing addresses, but not a lot beyond that.

The operating system can be treated much like a subroutine library. The "magic numbers" you're asking about are operating system entry points; the call instruction, like a function call in higher level languages, invokes them; they run until they return, at which point your program picks up where it left off. Your OS's user manual will tell you which entry point to invoke to do what, how to set up any arguments required (such as putting the address of the string to be printed in the si register before calling os_print_string, though some may involve pushing values onto the stack rather than putting them in registers), and how to read their returned results if any (again, which registers will have the result or what to pop off the stack).

As far as question (b) goes -- That's all stuff the OS and its device drivers, or a function library linked with your assembly code, will normally handle for you. If you really need to know it (eg because you're writing an OS or device drivers), you'll need to study the documentation for your specific hardware to understand how to communicate with it... but what you'll wind up doing is writing a library of functions which do the necessary work, and packaging it so main programs just invoke those functions. In other words, for most programs I/O is much like working in a higher-level language; the runtime library does all the work and all you need to know is how to use it. (Sane assembler code is critically dependent upon writing good functions so you don't spend time endlessly reinventing wheels!)


问:
What is the point of a Gantt Chart, and will it help me?
My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>

答: A well-produced and maintained Gantt chart can be a great tool.  The main benefits are showing which tasks depend on other tasks, predicting how the project can be affected by delays, and highlighting wasted hours because you were waiting on something else.</p>

ContentLicense: CC BY-SA 2.5


答:
if THIS:

and generally development department being held responsible

is always the case, I don't see there is anything you can do. If you cannot change that part of the company then you will always be swimming against the tide.

The way this company does business (sales promising the moon on a stick) is actually quite common, but always blaming the dev team for not meeting targets set by sales is massively incorrect.

If this fundamental thing cannot be changed you have no chance of saving morale etc.

The sales people often have no idea what it is they are actually selling. Well, they know what a website means. They know it might have a database.... you keep stuff in there right?

To try and describe this to non-technical people, I often make the distinction between physical "real" things and computer software.

I knock my hand on the table (assuming we're at a table) and talk about how the table is a real, physical thing. It's got 4 legs, a smooth wooden/whatever surface. It is a tangible, real thing. Change the colour? Yeah, no worries, that's easy, 2 min fix (or whatever).

Huh, you want me to add wheels to the legs so the table can be moved around easily? And add a device that will raise the level of the desk? Not so easy.

Software, to non-techies, is this woolly, amorphous blob that lives inside their monitor (not their computer, their actual monitor). They can't touch it. They cannot comprehend how it works, or how it is built. They might have heard of computer code, or seen it scrolling across the screen in an episode of 24, but they have no idea that it is NOT trivial to just throw things together, or change them on the fly.


答:
I think your question reduces to: how do I structure a computation? Please notice you want to manage "a set of rules", which are code, and "a set of magic numbers", which are data. (You can see them as "data embedded in your code", but they are data nonetheless).

Furthermore, making your code "understandable to others" is in fact the general goal of all programming paradigms (see e.g. "Implementation Patterns" by Kent Beck, or "Clean Code" by Robert C. Martin for authors on software who state the same goal as you, for any program).

All hints in these books would apply to your question. Let me extract some hints specifically for "magic numbers" and "sets of rules":

Use named constants and Enumerations to replace magic numbers

Example of constants:

```<code>if (partWidth > 0.625) {
    // doSomeApiCall ...
}
return (partWidth - 0.625)
</code>```

should be replaced with a named constant so that no later changes can introduce a typo and break your code, e.g. by changing the first 0.625 but not the second.

```<code>const double MAX_PART_WIDTH = 0.625;

if (partWidth > MAX_PART_WIDTH) {
    // doSomeApiCall ...
}
return (partWidth - MAX_PART_WIDTH)
</code>```

Example of Enumerations:

Enumerations can help you put together data that belong together. If you are using Java, remember that Enums are objects; their elements can hold data, and you can define methods that return all elements, or check some property. Here an Enum is used in constructing another Enum:

```<code>public enum EnginePart {
    CYLINDER (100, Materials.STEEL),
    FLYWHEEL (120, Materials.STEEL),
    CRANKSHAFT (200, Materials.CARBON);

    private final double maxTemperature;
    private final Materials composition;
    private EnginePart(double maxTemperature, Materials composition) {
        this.maxTemperature = maxTemperature;
        this.composition = composition;
    }
}

public enum Materials {
    STEEL,
    CARBON
}
</code>```

The advantage being: now nobody can wrongly define an EnginePart that is not made out of steel or carbon, and nobody can introduce an EnginePart called "asdfasdf", as would be the case if it was a string that would be checked on content.

The Strategy pattern and the Factory method pattern describe how to encapsulate "rules" and pass them to another object that makes use of them (in the case of the Factory pattern, the usage is building something; in the case of the Strategy pattern, the usage is whatever you want).

Example of Factory method pattern:

Imagine you have two types of Engines: one where each part has to be connected to the Compressor, and one where each part can be freely connected to whatever other parts. Adapted from Wikipedia

```<code>public class EngineAssemblyLine {
    public EngineAssemblyLine() {
        EnginePart enginePart1 = makeEnginePart();
        EnginePart enginePart2 = makeEnginePart();
        enginePart1.connect(enginePart2);
        this.addEngine(engine1);
        this.addEngine(engine2);
    }

    protected Room makeEngine() {
        return new NormalEngine();
    }
}
</code>```

And then in another class:

```<code>public class CompressedEngineAssemblyLine extends EngineAssemblyLine {
    @Override
    protected Room makeRoom() {
        return new CompressedEngine();
    }
}
</code>```

The interesting part is: now your AssemblyLine constructor is separated of what type of Engine it is handling. Maybe the addEngine methods are calling a remote API...

Example of Strategy pattern:

The Strategy pattern describes how to introduce a function into an object in order to change its behavior. Let us imagine you sometimes want to polish a part, sometimes you want to paint it, and by default you want to review its quality. This is a Python example, adapted from Stack Overflow

```<code>class PartWithStrategy:

    def __init__(self, func=None) :
        if func:
            self.execute = func

    def execute(self):
        # ... call API of quality review ...
        print "Part will be reviewed"

def polish():
    # ... call API of polishing department ...
    print "Part will be polished"

def paint():
    # ... call API of painting department ...
    print "Part will be painted"

if __name__ == "__main__" :
    strat0 = PartWithStrategy()
    strat1 = PartWithStrategy(polish)
    strat2 = PartWithStrategy(paint)

    strat0.execute()  # output is "Part will be reviewed"
    strat1.execute()  # output is "Part will be polished"
    strat2.execute()  # output is "Part will be painted"
</code>```

You may expand this to holding a list of Actions you want performed, and then calling them in turn from the execute method. Maybe this generalization could be better described as a Builder pattern, but hey, we don't want to get picky, do we? :)

Title: How do I manage a very large set of rules and magic numbers in my program?

Body:
I'm somewhat new to programming (I'm a mechanical engineer by trade), and I'm developing a small program during my downtime that generates a (solidworks) part based on input from various people from around the plant.

Based on only a few inputs (6 to be exact), I need to make hundreds of API calls that can take up to a dozen parameters each; all generated by a set of rules I've gathered after interviewing everyone that handles the part. The rules and parameters section of my code is 250 lines and growing.

So, what is the best way to keep my code readable and manageable? How do I compartmentalize all my magic numbers, all the rules, algorithms, and procedural parts of the code? How do I deal with a very verbose and granular API?

My main goal is to be able to hand someone my source and have them understand what I was doing, without my input.

Body:
I think your question reduces to: how do I structure a computation? Please notice you want to manage "a set of rules", which are code, and "a set of magic numbers", which are data. (You can see them as "data embedded in your code", but they are data nonetheless).

Furthermore, making your code "understandable to others" is in fact the general goal of all programming paradigms (see e.g. "Implementation Patterns" by Kent Beck, or "Clean Code" by Robert C. Martin for authors on software who state the same goal as you, for any program).

All hints in these books would apply to your question. Let me extract some hints specifically for "magic numbers" and "sets of rules":

Use named constants and Enumerations to replace magic numbers

Example of constants:

if (partWidth > 0.625) {
    // doSomeApiCall ...
}
return (partWidth - 0.625)

should be replaced with a named constant so that no later changes can introduce a typo and break your code, e.g. by changing the first 0.625 but not the second.

const double MAX_PART_WIDTH = 0.625;

if (partWidth > MAX_PART_WIDTH) {
    // doSomeApiCall ...
}
return (partWidth - MAX_PART_WIDTH)

Example of Enumerations:

Enumerations can help you put together data that belong together. If you are using Java, remember that Enums are objects; their elements can hold data, and you can define methods that return all elements, or check some property. Here an Enum is used in constructing another Enum:

public enum EnginePart {
    CYLINDER (100, Materials.STEEL),
    FLYWHEEL (120, Materials.STEEL),
    CRANKSHAFT (200, Materials.CARBON);

    private final double maxTemperature;
    private final Materials composition;
    private EnginePart(double maxTemperature, Materials composition) {
        this.maxTemperature = maxTemperature;
        this.composition = composition;
    }
}

public enum Materials {
    STEEL,
    CARBON
}

The advantage being: now nobody can wrongly define an EnginePart that is not made out of steel or carbon, and nobody can introduce an EnginePart called "asdfasdf", as would be the case if it was a string that would be checked on content.

The Strategy pattern and the Factory method pattern describe how to encapsulate "rules" and pass them to another object that makes use of them (in the case of the Factory pattern, the usage is building something; in the case of the Strategy pattern, the usage is whatever you want).

Example of Factory method pattern:

Imagine you have two types of Engines: one where each part has to be connected to the Compressor, and one where each part can be freely connected to whatever other parts. Adapted from Wikipedia

public class EngineAssemblyLine {
    public EngineAssemblyLine() {
        EnginePart enginePart1 = makeEnginePart();
        EnginePart enginePart2 = makeEnginePart();
        enginePart1.connect(enginePart2);
        this.addEngine(engine1);
        this.addEngine(engine2);
    }

    protected Room makeEngine() {
        return new NormalEngine();
    }
}

And then in another class:

public class CompressedEngineAssemblyLine extends EngineAssemblyLine {
    @Override
    protected Room makeRoom() {
        return new CompressedEngine();
    }
}

The interesting part is: now your AssemblyLine constructor is separated of what type of Engine it is handling. Maybe the addEngine methods are calling a remote API...

Example of Strategy pattern:

The Strategy pattern describes how to introduce a function into an object in order to change its behavior. Let us imagine you sometimes want to polish a part, sometimes you want to paint it, and by default you want to review its quality. This is a Python example, adapted from Stack Overflow

class PartWithStrategy:

    def __init__(self, func=None) :
        if func:
            self.execute = func

    def execute(self):
        # ... call API of quality review ...
        print "Part will be reviewed"

def polish():
    # ... call API of polishing department ...
    print "Part will be polished"

def paint():
    # ... call API of painting department ...
    print "Part will be painted"

if __name__ == "__main__" :
    strat0 = PartWithStrategy()
    strat1 = PartWithStrategy(polish)
    strat2 = PartWithStrategy(paint)

    strat0.execute()  # output is "Part will be reviewed"
    strat1.execute()  # output is "Part will be polished"
    strat2.execute()  # output is "Part will be painted"

You may expand this to holding a list of Actions you want performed, and then calling them in turn from the execute method. Maybe this generalization could be better described as a Builder pattern, but hey, we don't want to get picky, do we? :)


答:
My solution to this problem is quite different: layers, settings, and LOP.

First wrap the API in a layer. Find sequences of API calls that are used together and combine them into your own API calls. Eventually there should be no direct calls to the underlying API, just calls to your wrappers. The wrapper calls should start to look like a mini language.

Second, implement a 'settings manager'. This is a way to associate names with values dynamically. Something like this. Another mini language.

```<code>Baseplate.name="Base plate"
Baseplate.length=1032.5
Baseplate.width=587.3
</code>```

Finally, implement your own mini language in which to express designs (this is Language Oriented Programming). This language should be understandable to the engineers and designers who contribute the rules and settings. The first example of such a product that comes to mind is Gnuplot, but there are many others. You could use Python, although personally I wouldn't.

I understand that this is a complex approach, and may be overkill for your problem, or requiring skills you have yet to acquire. It's just how I would do it.

Body:
My solution to this problem is quite different: layers, settings, and LOP.

First wrap the API in a layer. Find sequences of API calls that are used together and combine them into your own API calls. Eventually there should be no direct calls to the underlying API, just calls to your wrappers. The wrapper calls should start to look like a mini language.

Second, implement a 'settings manager'. This is a way to associate names with values dynamically. Something like this. Another mini language.

Baseplate.name="Base plate"
Baseplate.length=1032.5
Baseplate.width=587.3

Finally, implement your own mini language in which to express designs (this is Language Oriented Programming). This language should be understandable to the engineers and designers who contribute the rules and settings. The first example of such a product that comes to mind is Gnuplot, but there are many others. You could use Python, although personally I wouldn't.

I understand that this is a complex approach, and may be overkill for your problem, or requiring skills you have yet to acquire. It's just how I would do it.


问:
Storing user uploaded images / files in multi server env
In a multi server system, e.g. a load balancer, multiple web servers and a database server, where do you store the files / images users upload when each web server will need access?

Before now I've just used a single web server, or maybe one web server and a MySQL database server.
But if you have multiple web servers I guess you have a range of options for making sure resources like images and other user files are shared, such as:

Storing them on the database server

Or a server specifically for them

Maybe mounting the same directory

Or using a tool like rsync to synchronize the user uploads directories on each web server

Or maybe you have a different solution? or there's a de-facto way of doing this that I'm not aware of?

答:
I would consider a few options, depending on several factors:

If it's not a huge volume of images, then a single fileserver accessible by all the webservers is the easiest route.

If the images are very small (much less than a megabyte...), a Key-value storage can be considered. (but note that a file system is a great and efficient key-value when the values are more than a few kilobytes)

If the content is read much more than modified (at least 100 or 1000 times more frequently), then replicated (via rsync or unison) can reduce lag time.  But this advantage is unlikely to be significant.  A fileserver is still a great option.

If the amount of images is more than what's convenient to store on a single server, then a distributed storage system allows for near-infinite growth. (ceph RADOS, moosefs, glusterFS, etc.)


答:
They might have a better technical understanding and ability to estimate than you think, maybe even getting most of their estimates from engineering.  What typically happens is estimates are made without regard to all the other commitments you've made.  Sure, a feature might take two weeks if you didn't have anything else to work on.  A schedule must take into account your entire capacity.  If sales doesn't ask for this, then engineering should take the lead.

I wasn't in the meeting when we first tried this at my company, but I'm told it was quite painful.  Basically, they put a list on a whiteboard of everything product management wanted us to do over the next 10 weeks, then engineering put a red line under what we could realistically accomplish.  We wouldn't move the line, but a huge negotiation ensued about what would end up above or below that line.

What happened is they decided certain things weren't so urgent after all.  Some lower-paying customers had to be disappointed.  Some products were consolidated to meet more than one customers' needs.  Some features they asked for a limited version that would be quicker to implement.  They found ways to reuse and improve products they previously decided to abandon.

Like I said, it was painful for a while, but I think now they are much more confident in a commitment being a commitment.  They don't have to spend as much time explaining why features are slipping, and trying to get customers to believe the next ship date is the real one.  They know when they ask for something new that something else must be sacrificed.  They are getting their top features completely finished, rather than getting everything they want, but each feature only 80% complete at the deadline.


问:
Avoiding Packages with High Efferent Coupling
I use java language to develop android application, after static analysis, the tool warns about high efferent coupling.

What is the reason of this warning? Is it about AComModel which is extended by other class?

There are 4 classes below which the tool warns us about them. I hope I asked logical question, but I really don't understand what is the problem?

```<code>public class AComModel {
    public String GetComBusinessKey() {
        return "none";
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
public class StepOneCom extends AComModel {

    public View vi;
    public ArrayList<SummaryViewModel> lstSmr;

    @Override
    public String GetComBusinessKey() {
        return "shvi";
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
public class StepTwoCom extends AComModel {

    public ArrayList<AccViewModel> lstAcc;
    public SummaryViewModel c1;

    @Override
    public String GetComBusinessKey() {
        return "shvi";
    }

}

@JsonIgnoreProperties(ignoreUnknown = true)
public class StepThreeStepTwoCom extends AComModel {

    public StepFourCom stepFourCom;

    @Override
    public String GetComBusinessKey() {
        return "cashadvi";
    }
}
</code>```

答:
Without seeing full code in your project, it is impossible to tell with 100% certainty, but given that tool was performing static code analysis, this warning indicates either of:

StepOneCom doesn't use specific methods and fields of either of classes View, ArrayList, SummaryViewModel

StepTwoCom doesn't use specific methods and fields of either of classes AccViewModel, ArrayList, SummaryViewModel

StepThreeCom doesn't use specific methods and fields of class StepFourCom

or some subset of what is listed above, or even all of the above together.

Probably simplest way to verify exactly what it is complaining about would be to replace (where it doesn't break compilation) specialized classes mentioned above with most general Object, and check whether warnings disappear.

This is based on explanation of efferent coupling given in Wikipedia:

a metric in software development. It measures the number of data types a class knows about.

This includes inheritance, interface implementation, parameter types, variable types, and exceptions.

A large efferent coupling can indicate that a class is unfocused. It may also indicate brittleness, since it depends on the stability of all the types to which it is coupled.

In simpler terms, if you are able to replace some specialized type with a standard one, like Object, without breaking compilation, this means that there is no real need for your class to be aware of that specialized type, and that introducing this "useless knowledge" you only make the code harder to maintain.

Reader of your code would have to break their mind trying to guess why did you involve View, ArrayList, SummaryViewModel, AccViewModel, StepFourCom where compiler apparently tells them that plain standard Object would do just as good.

While we're at it, I would like to also point out that the way presented in the snippet, code appear to make a probably even worse violation of the principles suggested in basic language tutorial:

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.

Avoid public fields except for constants... Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Unless you are 200% sure that you need fields to be public and can give a bullet proof justification for this, think of public access modifiers in code like this as a source of your worst future headaches and nightmares:

```<code>public View vi;
public ArrayList<SummaryViewModel> lstSmr;
</code>```

Guidance given in tutorial is there for a reason, it is based on a painful experience of multiple programmers who tried this way and discovered that it's a dead end.

A less blatant, but still quite slippery part of the design in your code snippet is unjustified use of inheritance. Inheritance puts certain extra obligations and risks on classes using it, and you better be sure that it's exactly what you need.

I mention this because the way how code is written in your code snippet, it can be equally as well do if AComModel to be an interface instead of class and just declare GetComBusinessKey instead of providing default implementation, so that StepOneCom, StepTwoCom, StepThreeCom would implement that interface, instead of extending a class.

Body:
Without seeing full code in your project, it is impossible to tell with 100% certainty, but given that tool was performing static code analysis, this warning indicates either of:

StepOneCom doesn't use specific methods and fields of either of classes View, ArrayList, SummaryViewModel

StepTwoCom doesn't use specific methods and fields of either of classes AccViewModel, ArrayList, SummaryViewModel

StepThreeCom doesn't use specific methods and fields of class StepFourCom

or some subset of what is listed above, or even all of the above together.

Probably simplest way to verify exactly what it is complaining about would be to replace (where it doesn't break compilation) specialized classes mentioned above with most general Object, and check whether warnings disappear.

This is based on explanation of efferent coupling given in Wikipedia:

a metric in software development. It measures the number of data types a class knows about.

This includes inheritance, interface implementation, parameter types, variable types, and exceptions.

A large efferent coupling can indicate that a class is unfocused. It may also indicate brittleness, since it depends on the stability of all the types to which it is coupled.

In simpler terms, if you are able to replace some specialized type with a standard one, like Object, without breaking compilation, this means that there is no real need for your class to be aware of that specialized type, and that introducing this "useless knowledge" you only make the code harder to maintain.

Reader of your code would have to break their mind trying to guess why did you involve View, ArrayList, SummaryViewModel, AccViewModel, StepFourCom where compiler apparently tells them that plain standard Object would do just as good.

While we're at it, I would like to also point out that the way presented in the snippet, code appear to make a probably even worse violation of the principles suggested in basic language tutorial:

Use the most restrictive access level that makes sense for a particular member. Use private unless you have a good reason not to.

Avoid public fields except for constants... Public fields tend to link you to a particular implementation and limit your flexibility in changing your code.

Unless you are 200% sure that you need fields to be public and can give a bullet proof justification for this, think of public access modifiers in code like this as a source of your worst future headaches and nightmares:

public View vi;
public ArrayList<SummaryViewModel> lstSmr;

Guidance given in tutorial is there for a reason, it is based on a painful experience of multiple programmers who tried this way and discovered that it's a dead end.

A less blatant, but still quite slippery part of the design in your code snippet is unjustified use of inheritance. Inheritance puts certain extra obligations and risks on classes using it, and you better be sure that it's exactly what you need.

I mention this because the way how code is written in your code snippet, it can be equally as well do if AComModel to be an interface instead of class and just declare GetComBusinessKey instead of providing default implementation, so that StepOneCom, StepTwoCom, StepThreeCom would implement that interface, instead of extending a class.


答: The reason for this is because you would still have to do an eval for deserialization and you would still have to somehow deserialize the javascript object into a string, which it doesnt just to by default. Also there is a general argument against using eval - particularly for an exchange format, since javascript objects are also functions.</p>

Title: Why is the json format necessary over the normal javascript object format?

Body:
Before you answer, yes I know that other languages have no native javascript object support, but neither do they have native support for json.

So wouldn't it make much more sense to modify the json spec to allow identifiers without "" and allow comments? Very sensible things because you don't have to serialize/deserialize when working in javascript, no?


问:
does anyone know how to use the PyQt 'uic' module method 'compileUiDir'?
I don't find the docstring to be very clear:

```<code>def compileUiDir(dir, recurse=False, map=None, **compileUi_args):
    """compileUiDir(dir, recurse=False, map=None, **compileUi_args)

    Creates Python modules from Qt Designer .ui files in a directory or
    directory tree.

    dir is the name of the directory to scan for files whose name ends with
    '.ui'.  By default the generated Python module is created in the same
    directory ending with '.py'.
    recurse is set if any sub-directories should be scanned.  The default is
    False.
    map is an optional callable that is passed the name of the directory
    containing the '.ui' file and the name of the Python module that will be
    created.  The callable should return a tuple of the name of the directory
    in which the Python module will be created and the (possibly modified)
    name of the module.  The default is None.
    compileUi_args are any additional keyword arguments that are passed to
    the compileUi() function that is called to create each Python module.
    """
</code>```

with regards to the map keyword argument and there is no simple example to go with it.

Is it expecting a map argument? as in:

```<code>uic.compileUiDir("ui/", map=("ui/", "../widget/test.py"))
</code>```

and how is it formed?

I basically have a few .ui files in the ui directory and wish to compile them and place the resulting .py files in another directory called widget.

They have names like test1Widget.ui, test2Widget.ui, etc. and I would like for them to be renamed to test1.py, test2.py, etc.

Can anyone give me some pointers please?

答:
ok, so I misunderstood the docstring.

It states that a callable is required (had to read up on callables!) taking in the original directory with the name of the .ui file and spitting back out the target directory with the target file name.

Here is the code for this and it works swimmingly well! :)

```<code>    def rename_and_move_callable(directory, file_name):
        return directory.replace("ui/", "widget/"), file_name.replace("Widget.py", ".py")

    uic.compileUiDir("ui/", map=rename_and_move_callable)
</code>```

Hence, I have the output naming and directory structure I required.

I certainly learnt something new today and hope it helps someone else out with the same problem!

Peace

Body:
ok, so I misunderstood the docstring.

It states that a callable is required (had to read up on callables!) taking in the original directory with the name of the .ui file and spitting back out the target directory with the target file name.

Here is the code for this and it works swimmingly well! :)

    def rename_and_move_callable(directory, file_name):
        return directory.replace("ui/", "widget/"), file_name.replace("Widget.py", ".py")

    uic.compileUiDir("ui/", map=rename_and_move_callable)

Hence, I have the output naming and directory structure I required.

I certainly learnt something new today and hope it helps someone else out with the same problem!

Peace


问:
Do validate non-input data from a client?
One of our developers has an opinion that all client data should be validated before using it. Even non-input data.

Say, our web service has an internal protection against database injections.

Examples: machine generated codes, various integers, indexes, calculated values.

We use ORM (Django). As I know there is a next approach in Django: validate only values entered as primary strings (usually via web forms).

For example: is there any reason to create validation rules to validate numbers if we know that there is 500th error (if the data are wrong) in the beginning of handling request? I think no. But probably I'm wrong.

Do my position requires to be changed?

答:
You should ALWAYS validate ANY data that is inserted to your database, either before or after it is actually inserted into your database program.  Preferably both, if practical.

Of course, we should write software correctly the first time, everyone should pay their taxes on time, and no one should ever cheat on their spouse.  Just because something's a good rule doesn't mean you need to blindly follow it.

Your other developer is right, in that client data should be validated, if it's given as an XML or JSON or CSV file or as a database vendor's binary backup format.  Some of these will make the validation easier (XML + binary backup), but you should always have a plan for "what if this data is corrupted or given entirely wrongly."

At the very least:

Have a backup of your database you can smoothly restore to if you find the database corrupt post-import.

Don't import into production right away.  Run the import in your development or test environment first.

Check record counts in the imported file, pre-import database, and post-import database.  If they do not clearly match, rollback the import until you can explain the discrepancy.

For bonus credit, teach whomever's sending you data how to run a CRC on a file, and have them provide that via separate cover.


答:
The client can temper with any data they send you, so you have no guarantee that your own client-side code has generated the non-input data. However, you should not be obligated to stop a client from burning themselves when they try to hack your system.

Ask yourself this - is invalid data in those non-input fields a problem only for the client, or is it a problem for your system and/or other clients?

If it's a problem for the system and/or other clients, then by all means validate it. You don't want other clients to suffer from hacking mistakes, and you don't want your server to get hacked.

However, if it's a problem only for your client, you don't have to go out of your way to solve it. After all - they are hacking your system. You want to protect your clients from mistakes when they use the UI or web service you provide them, but if they try to find backdoors and make mistakes it should be their own problem.

For example, if you client-side code collects locale data from the clients machine so your server can correctly generate time&number formats and convert to the proper units when rendering the pages. The client hacks your registration form and send the registration data directly via HTTP request, but they got the locale format wrong and now they get dates in the Gibberishian calendar and lengths are displayed in Pounds.

I say - it's their own freaking problem for hacking your system!

You can be extra nice and validate that data for them, but nobody should blame you for poor hacking-support...

That being said - you should really make sure that this is the case before deciding not to validate that data. For example, if the client posts data that is being parsed based on his locale and displayed to other clients, you'll want to validate that locale so you won't ruin that data for the other users.

Title: Do validate non-input data from a client?

Body:
One of our developers has an opinion that all client data should be validated before using it. Even non-input data.

Say, our web service has an internal protection against database injections.

Examples: machine generated codes, various integers, indexes, calculated values.

We use ORM (Django). As I know there is a next approach in Django: validate only values entered as primary strings (usually via web forms).

For example: is there any reason to create validation rules to validate numbers if we know that there is 500th error (if the data are wrong) in the beginning of handling request? I think no. But probably I'm wrong.

Do my position requires to be changed?


问:
Long vs short scripts? Big vs small scripts?
As a programmer, I have always wondered whether it is preferable to write (a) short modular functions that are each stored in their own script (i.e., file) or (b) long comprehensive scripts that contain all of their relevant functions.

For example, if I code a data analysis stream that includes a variety of operations performed on the same data (e.g., data cleaning, feature selection, clustering, supervised learning, etc.), should I write a single file even if it runs for hundreds of lines?

I have heard many opinions on the matter and I wonder what this community thinks. I understand that the answer may depend on the type of project, but, if this is the case, then it would be great to hear your thoughts on what factors one should consider in deciding between options (a) and (b).

I am currently coding in Python and I've wondered whether Python programmers have a preference to multiple functions in the same file or one file per function, but I imagine that this question is broader and applies to all programming languages.

答:
Things that belong together should be kept together. Don't have me open another file just to find some _internal_helper_function() that can't be reused in another context. This re-usability is another important point: If the code you've written could be useful in future projects, structure it as a reusable library. Separate it both logically (dependencies) and physically (files, directories) from the project-specific code.

Most importantly, the code should be easy to read. Shorter files with only a few related definitions each tend to be easier to understand. Beyond 1K lines, you'll have a hard time navigating the source code without search tools, in which case you should refactor.

There is no universal recipe how to find a good balance between the factors reuseability, locality, and ease of understanding. Don't decide for one extreme or the other, rather choose a middle path that does justice to the specifics of the project, and the preferences of the involved programmers.


问:
How to manage accidental complexity in software projects
When Murray Gell-Mann was asked how Richard Feynman managed to solve so many hard problems Gell-Mann responded that Feynman had an algorithm:

Write down the problem.

Think real hard.

Write down the solution.

Gell-Mann was trying to explain that Feynman was a different kind of problem solver and there were no insights to be gained from studying his methods. I kinda feel the same way about managing complexity in medium/large software projects. The people that are good are just inherently good at it and somehow manage to layer and stack various abstractions to make the whole thing manageable without introducing any extraneous cruft.

So is the Feynman algorithm the only way to manage accidental complexity or are there actual methods that software engineers can consistently apply to tame accidental complexity?

答:
"Everything should be made as simple as possible, but no simpler."

    — attributed to Albert Einstein

Let me sketch my personal algorithm for dealing with accidental complexity.

Write a user story or use case. Review with the product owner.

Write an integration test that fails because the feature is not there. Review with QA, or lead engineer, if there is such thing in your team.

Write unit tests for some classes that could pass the integration test.

Write the minimal implementation for those classes that passes the unit tests.

Review unit tests and implementation with a fellow developer. Go to Step 3.

The whole design magic would be on Step 3: how do you set up those classes? This turns to be the same question as: how do you imagine that you have a solution for your problem before you have a solution to your problem?

Remarkably, just imagining you have the solution seems to be one of the main recommendations of people who write on problem-solving (called "wishful thinking" by Abelson and Sussman in Structure and Interpretation of Computer Programs and "working backward" in Polya's How to Solve It)

On the other hand, not everyone has the same "taste for imagined solutions": there are solutions that only you find elegant, and there are others more understandable by a wider audience. That is why you need to peer-review your code with fellow developers: not so much to tune performance, but to agree on understood solutions. Usually this leads to a re-design and, after some iterations, to a much better code.

If you stick with writing minimal implementations to pass your tests, and write tests that are understood by many people, you should end with a code base where only irreducible complexity remains.


问:
Problems with Facades and then evolution in software
I initially started a project with Facades and Polymorphism as a way to create simple extensible design following SOLID Principles.
Here is a sample code:

```<code>public interface IInterface
{
    void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects);
}

public class SampleClass : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //some data layer code
        //and a for loop to fill OutputPocoObject object and add it to list
    }
}
</code>```

I have number of classes such as above which are created in runtime with the help of factory( not shown here for the sake of simplicity)

Recently after couple of months I see that there are different requirements emerging in my project, which I attempted to solve by the help of Polymorphism and I see that I am stuck with violating DRY principles.

Here is a sample code of this situation:

```<code>public class SampleClass2 : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //some data layer code
        //and a for loop to fill OutputPocoObject object and add it to list
        // there is a property in OutputPocoObject which is set to 1
    }
}

public class SampleClass3 : IInterface
{

    public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
    {
        //same code as above
        //with only one difference that  property in OutputPocoObject is set to 5 here
    }
}
</code>```

One Simple solution will be to add a control parameter to interface such as:

```<code>public interface IInterface
{
    void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects, int controlParameter);
}
</code>```

but I don't know whether this is such a better idea? Or whether it might introduce some complexity in my design?

答:
In addition to Konrad's answer.

I have created a new class encapsulation the common part of SampleClass2, SampleClass3...

```<code>    public class CommonClass
    {
        public void CommonMapper_FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
        {
            //some data layer code
        }
    }
</code>```

Then with the help of Composition I have removed duplication in SampleClass2, SampleClass3...

```<code>    public class SampleClass2 : IInterface
    {
        private readonly CommonClass _commonClassInstance;
        public SampleClass2()
        {
            _commonClassInstance=new CommonClass();
        }
        public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
        {
            //for loop to fill OutputPocoObject object and add it to list
            //_commonClassInstance.CommonMapper_FillList method to fill common functionality
            // set property in which is different OutputPocoObject to 1
        }
    }
</code>```

Body:
In addition to Konrad's answer.

I have created a new class encapsulation the common part of SampleClass2, SampleClass3...

    public class CommonClass
    {
        public void CommonMapper_FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
        {
            //some data layer code
        }
    }

Then with the help of Composition I have removed duplication in SampleClass2, SampleClass3...

    public class SampleClass2 : IInterface
    {
        private readonly CommonClass _commonClassInstance;
        public SampleClass2()
        {
            _commonClassInstance=new CommonClass();
        }
        public void FillList(List<InputPocoObject> listOfInputObjects, out List<OutputPocoObject> ListOfOutputObjects)
        {
            //for loop to fill OutputPocoObject object and add it to list
            //_commonClassInstance.CommonMapper_FillList method to fill common functionality
            // set property in which is different OutputPocoObject to 1
        }
    }


问:
How to enrich a simple two endpoint SOAP application to become enterprise level?
Imagine you have some exchange of data between two endpoints (webservices or let's call URL).
Data can travel in any way (Xml, Json, GET, POST) it doesn't matter.

I've got the source code of the first endpoint (I drawed it on the left).
The second one is from a third party and will call back my infrastructure on a third endpoint (which is also part of my infrastructure).

I would like to implement some session / state to relate the first call to their callback.
And I would also like to add distributed logging, support for problem solving in a production environment, configuration, performance monitoring, a dashboard, and so on.

What kind of consideration should I do in facing the design of this kind of architecture?

Let me clarify with an example (which answers to @SparKotॐ comment)

I should log the first call and understand if the third party is calling me back or not.

I can do this only if my "3rd party" caller Class (the white box higher on the lef) and the Class called from the "3rd party" (the white box lower on the lef) shares some logging infrastructure. How would you implement this?

Possibilities are:

Share a database

Share a message queue

Share a WCF service

Share some AppFabric cache

What else?

Pipeline?

Which consideration would you make about this tracking service? Should both my class being hosted on the same server? What kind of question would drive you to design the architecture which transform two simple WebClient.Open request into something which is more traceable and fault tolerant?

答:
I would look at a shared logging infrastructure something like loggly (https://www.loggly.com/) or logstash (http://logstash.net/).  </p>

<p>If you have every call generating a requestId for each call and have a conversationId for the whole conversation. Pass these in the headers of each call, each component can log metrics, info, errors etc using these ids. And you can then extract useful information out of your logging platform that will let you drill into each call in detail on both sides of the call (client and server). </p>

Body:
I would look at a shared logging infrastructure something like loggly (https://www.loggly.com/) or logstash (http://logstash.net/).

If you have every call generating a requestId for each call and have a conversationId for the whole conversation. Pass these in the headers of each call, each component can log metrics, info, errors etc using these ids. And you can then extract useful information out of your logging platform that will let you drill into each call in detail on both sides of the call (client and server).


问:
Should we create a story for vacation?
We have had a situation with a scrum sprint where a team member went on vacation for a few days at the beginning of the sprint. This led to us being behind the ideal trend on the burndown chart at the beginning of the sprint, although we caught up later since we knew we had slightly less resource and as a result had committed to deliver slightly less.

In our retrospective it was suggested by the Product Owner that we create a vacation story. The time remaining would be reduced down as the vacation was completed. As a result the burndown chart would be corrected for the "hole" that would appear in effort when the team resource was lower, which would otherwise falsely indicate a problem.

Is this a good idea?

答:
I don't think it is a good idea.

Such a story would deliver no business value to the Product Owner.  It's just a hack to get your burndown chart to work.

We don't like hacks :)

Why not simply adjust your burndown chart's projected completion date by adjusting the expected velocity?

Title: Should we create a story for vacation?


答:
It's not a standard approach, no.

But your team is having a problem with tracking / recording / identifying hours since the Product Owner has requested making a change.  So it may make sense in your case.

Generally, team members bid for projects based upon the number of points they believe they'll have within that sprint.  That means each team member needs to be aware of any commitments that would keep them from taking a full sprint's worth of points.

You may also need to consider other "blanket" story types for ad-hoc meetings, customer support, administrivia, etc... if the Product Owner doesn't feel like they are seeing all of the time that should be reflected within a sprint.

Title: Should we create a story for vacation?

Body:
We have had a situation with a scrum sprint where a team member went on vacation for a few days at the beginning of the sprint. This led to us being behind the ideal trend on the burndown chart at the beginning of the sprint, although we caught up later since we knew we had slightly less resource and as a result had committed to deliver slightly less.

In our retrospective it was suggested by the Product Owner that we create a vacation story. The time remaining would be reduced down as the vacation was completed. As a result the burndown chart would be corrected for the "hole" that would appear in effort when the team resource was lower, which would otherwise falsely indicate a problem.

Is this a good idea?


答:
You may want to use a rules engine. A rules engine gives you a DSL (Domain Specific Language) that is designed to model the criteria needed for a certain outcome in an understandable way, as explained in this question.

Depending on the implementation of the rules engine, the rules may even be changed without recompiling the code. And because the rules are written in their own, simple language, they can be changed by the users as well.

If you're lucky there is a ready-to-use rules engine for the programming language you are using.

The downside is that you have to get acquainted with a rules engine which may be hard if you're a programming beginner.


问:
How to deal tasks that are probably not user stories but still need to get done?
We have a number of tasks that need to be completed, but are probably not real user stories, or if they are, they are very developer-centric user stories which will never be visible to the end-users. The problem is that because they do not get estimated as a part of a sprint and very little gets done on them. Eventually, it becomes enough of a problem that someone takes time out of a sprint to deal with them, but that affects progress on "official" sprint work, which makes some people a wee bit unhappy.

I've been pushing for making these tasks into official user stories, but no one else seems to like this. How else could I request official recognition for these tasks, so I can allocate full days on them without feeling like I'm affecting the rest of the sprint?

Some examples of the tasks, just to give you an idea:

Write small, custom maven plugins to simplify specific (and widely used, within the organization) build configurations.

Refactor old project(s) to build with Maven and newer tool set.

Refactor redundant (across multiple projects) code into independent libraries - could potentially be used by many projects.

答:
The way I've solved this issue in the past is to just have fun with it.  Make them user stories.  Who's to say what user is actually defined as in that sense?

As an old-timer project, I want to build with Maven, so that I can be built in a single step and better manage my dependencies.

I think this is the best way to solve them.  A huge benefit is that this way it still makes you ask, why?

Why do you need to refactor those old projects?

The why is important for the POs / PMs to actually justify these tasks, and in my opinion, gives your team a valuable insight into these tasks.

YMMV, but I like this approach, and it has worked for my past teams.


答:
No.

First off, vacation isn't a problem, it's a reality. The burn-down chart is supposed to reflect the reality of the project's progress, and if the project progressed less during one sprint compared to another due to vacation, a proper sprint burn-down chart will reflect that.

Secondly, vacation (along with other administrative functions) is expected to happen over the course of a project. The impact that such interruptions have on the project's average sprint velocity will even out over time. The resulting average velocity will be a more realistic indicator of available development effort per sprint than some calculation like #OfDevelopers * SomeStandard#OfHours per Sprint.

If you corrupt your sprint velocity by adding stories that aren't really stories, you'll never get this realistic view of your project's progress.

Title: Should we create a story for vacation?


答:
As Wikipedia says it Gannt chart is a type of a bar chart (more often a "line type") that helps with project planning. It is often drawn manually on the wall on a big (really big) piece of paper, since it is easily modified in that format.

It is a very simple type of planning tool; you can produce it in Excel or some equivalent; and rather effective, as long as the time required for certain phases of project can be roughly estimated. If there is a delay - no problem - one line get lengtened, the others stay the same and you have a new end-of-project-date.

Overlapping phases (time-wise) are easily seen on it, as easily as dependencies of starting one phase relying on the end of another.

'tis all there is to it really.

Of course, the problem with the Gannt (or the "time chart" as it is usually called in my part of the world) is that, that at the beginning of a project you have it all drawn up nicely on the wall, feeling enthusiastic and happy, ... then one delay occurs, and you change it on the chart, and you're still felling happy ... then another delay occurs, you draw it up again, and you're still feeling pretty good ... 100x delays occur ... you're feeling like _______ (censored).

Meaning, it is only a good project planning tool if you're actually sticking to those little deadlines. So stop wasting time in here and get to work!

Title: What is the point of a Gantt Chart, and will it help me?

Body: My (non-technical) colleague has threatened me with a Gantt chart for a new project that we are currently planning.  What is this likely to provide for us, and will it be a helpful tool?</p>


答:
Your burndown chart is there to help the team, including the product owner, determine if you are on track or not to making your commitments for the sprint.  You should do whatever it takes to make it useful for that purpose.  If you can look at it and quickly explain away any deviations, and still be able to tell if you're on track, then there's no need for things like vacation stories.

On the other hand, I've had stretches where because of the way we used the tool, the burndown chart was made completely useless, so people stopped looking at it and caring about it.  If that's your situation frequently, then something like a vacation story can be very useful.

I would personally prefer if the tool could change the ideal line to be something other than a linear progression, but since most can't, then using a story to adjust the burndown to give a linear progression is certainly okay, as long as it preserves the chart as a faithful representation of your actual progress.  If you're manipulating it to make your burndown look pretty even when the people still in the office aren't making real progress, then you're doing it wrong.

Note that you want such a story to affect only your burndown, not your velocity, for the reasons other answers have pointed out.  That means I wouldn't assign story points to a vacation story, just hours.

Title: Should we create a story for vacation?


答:
In respect to what those os_print_string = 0003h and other "magic numbers" are, they're entry point addresses, not to the actual subroutine, but to a jump table which in turn jumps to the actual location of the OS subroutine.

When I first started learning assembly language it was on a system which did not have much organization in the ROM layout. If you wanted to make use of the ROM routines you had to set up the CPU registers and directly CALL the address of the routine.

All well and good until the ROM is updated and all the addresses change...luckily, the ROM in question never did get any updates which would break those calls. If it had, a great many software titles would have stopped working.

Jump tables solve this problem by ensuring that the published entry point for an OS routine never changes, even if the machine code itself moves around between different OS versions. In this case the jump table entries are at 3 byte increments so the table will look a lot like:

```<code>0000h    JP someaddr           C3 LL HH
0003h    JP print_string       C3 LL HH
0006h    JP yetanotheraddr     C3 LL HH
0009h    JP yetanotheraddr     C3 LL HH
000Ch    JP yetanotheraddr     C3 LL HH
000Fh    JP yetanotheraddr     C3 LL HH
0012h    JP wait_key           C3 LL HH
...
...
</code>```

LL and HH may be switched depending on the endian-ness of the CPU, C3 happens to be the opcode for JP on a Z80.

No RET is needed between these because the JP does NOT save the current execution address on a stack (whereas the CALL which got you there does) so the last RET in the OS routine will cause execution to continue right after your call to the jump table.

As to how the system knows which addresses in the framebuffer to manipulate, that's all taken care of by os_print_string (and whatever other display related OS routines are available to you; there may well be something like os_set_point). The framebuffer address, hardware, implementation etc can all change, but your code only cares that there is an OS routine which prints characters to the display (or sets points, or draws lines, or...)

Body:
How does assembly relate to machine/binary code.

For example here is how to print to the screen in mikeOS(a small pure assembly OS), mikeOS it uses NASM to assemble.

```<code>BITS 16
    ORG 32768
    %INCLUDE 'mikedev.inc'

start:
    mov si, mystring
    call os_print_string

    call os_wait_for_key

    ret

    mystring db 'My first MikeOS program!', 0
</code>```

Where os_print_string and os_wait_for_key are defined as

```<code>os_print_string     equ 0003h   ; SI = zero-terminated string
</code>```

and

```<code>os_wait_for_key     equ 0012h   ; Returns AL = key pressed
</code>```

in mikedev.inc respectively and defined as

```<code>os_call_vectors:
    jmp os_print_string     ; 0003h
</code>```

in kernal.asm

Now nasm must do a lot more work under the scene when assembling, I have no idea what.

In other words assembly language is a wrapper to some degree to machine code just as say C is a wrapper to assembly. If I said cout >> "Hello World" for example in C++, this is then compiled into it's assembly equivalent and them assembled into machine code.

So I am trying to understand out how 0003h and 0012h seem to dictate everything that is going on when printing to the screen. How do these two values,

a) Tell the CPU/PC system which bus to send the corresponding bytes that represent the required string to the monitor bus and not say to the sound card.

b) In this case the string is sent to the monitor, obviously, now my understanding is that you have a frame buffer that can store a maximum number of bytes. So say the resolution of your screen is set at 1024 x 768 which is 786432 pixels and a refresh rate of 60hz on the screen, therefore the FB will contain this number of byte values and hence will be sending this many bytes to the monitor every 1/60 sec. The first byte in the FB corresponding to the first pixel on the screen and the last to the last on the screen etc.

So how does the CPU/GPU know which byte to put in which position in the FB. It's like saying to the GPU 'ok I need this pixel at coord (245,232) green so I will leave it to you to put this pixels value in the correct position in the FB' etc.

How does this work.

Body:
In respect to what those os_print_string = 0003h and other "magic numbers" are, they're entry point addresses, not to the actual subroutine, but to a jump table which in turn jumps to the actual location of the OS subroutine.

When I first started learning assembly language it was on a system which did not have much organization in the ROM layout. If you wanted to make use of the ROM routines you had to set up the CPU registers and directly CALL the address of the routine.

All well and good until the ROM is updated and all the addresses change...luckily, the ROM in question never did get any updates which would break those calls. If it had, a great many software titles would have stopped working.

Jump tables solve this problem by ensuring that the published entry point for an OS routine never changes, even if the machine code itself moves around between different OS versions. In this case the jump table entries are at 3 byte increments so the table will look a lot like:

0000h    JP someaddr           C3 LL HH
0003h    JP print_string       C3 LL HH
0006h    JP yetanotheraddr     C3 LL HH
0009h    JP yetanotheraddr     C3 LL HH
000Ch    JP yetanotheraddr     C3 LL HH
000Fh    JP yetanotheraddr     C3 LL HH
0012h    JP wait_key           C3 LL HH
...
...

LL and HH may be switched depending on the endian-ness of the CPU, C3 happens to be the opcode for JP on a Z80.

No RET is needed between these because the JP does NOT save the current execution address on a stack (whereas the CALL which got you there does) so the last RET in the OS routine will cause execution to continue right after your call to the jump table.

As to how the system knows which addresses in the framebuffer to manipulate, that's all taken care of by os_print_string (and whatever other display related OS routines are available to you; there may well be something like os_set_point). The framebuffer address, hardware, implementation etc can all change, but your code only cares that there is an OS routine which prints characters to the display (or sets points, or draws lines, or...)