WPF Binding.StringFormat: C vs. '{}{0:C}' - wpf

I am trying to globalize a simple WPF app. In several questions and/or answers on SO I see one of the following two settings on the binding:
StringFormat=C
StringFormat='{}{0:C}'
What is the difference between these? Are there certain conditions where you would use one over the other?

My understanding is that there is no difference, one is just shorthand and the other explicit. The only condition I can think of where being explicit is beneficial is when you want more control over the format. For example:
StringFormat=Total: {0:C}
Other than that, I'd say keep it simple; XAML is already verbose and shorthand syntax is welcome.

Maybe read up string formatting?
http://msdn.microsoft.com/en-us/library/dd465121.aspx
You can use {0:C} in a format string where you are filling in a value:
decimal value = 123.456;
Console.WriteLine("Your account balance is {0:C2}.", value);
while, you use the C as a plain format:
Console.WriteLine(("Your account balance is " + decimal.Parse("24.3200").ToString("C"));
they are functionally equivalent as far as the output. It's just a different way to format the data based on the context of how your using it.
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#CFormatString

Related

Ruby: Hash, Arrays and Objects for storage information

I am learning Ruby, reading few books, tutorials, foruns and so one... so, I am brand new to this.
I am trying to develop a stock system so I can learn doing.
My questions are the following:
I created the following to store transactions: (just few parts of the code)
transactions.push type: "BUY", date: Date.strptime(date.to_s, '%d/%m/%Y'), quantity: quantity, price: price.to_money(:BRL), fees: fees.to_money(:BRL)
And one colleague here suggested to create a Transaction class to store this.
So, for the next storage information that I had, I did:
#dividends_from_stock << DividendsFromStock.new(row["Approved"], row["Value"], row["Type"], row["Last Day With"], row["Payment Day"])
Now, FIRST question: which way is better? Hash in Array or Object in Array? And why?
This #dividends_from_stock is returned by the method 'dividends'.
I want to find all the dividends that were paid above a specific date:
puts ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('12/05/2014')}
I get the following:
#<DividendsFromStock:0x2785e60>
#<DividendsFromStock:0x2785410>
#<DividendsFromStock:0x2784a68>
#<DividendsFromStock:0x27840c0>
#<DividendsFromStock:0x1ec91f8>
#<DividendsFromStock:0x2797ce0>
#<DividendsFromStock:0x2797338>
#<DividendsFromStock:0x2796990>
Ok with this I am able to spot (I think) all the objects that has date higher than the 12/05/2014. But (SECOND question) how can I get the information regarding the 'value' (or other information) stored inside the objects?
Generally it is always better to define classes. Classes have names. They will help you understand what is going on when your program gets big. You can always see the class of each variable like this: var.class. If you use hashes everywhere, you will be confused because these calls will always return Hash. But if you define classes for things, you will see your class names.
Define methods in your classes that return the information you need. If you define a method called to_s, Ruby will call it behind the scenes on the object when you print it or use it in an interpolation (puts "Some #{var} here").
You probably want a first-class model of some kind to represent the concept of a trade/transaction and a list of transactions that serves as a ledger.
I'd advise steering closer to a database for this instead of manipulating toy objects in memory. Sequel can be a pretty simple ORM if used minimally, but ActiveRecord is often a lot more beginner friendly and has fewer sharp edges.
Using naked hashes or arrays is good for prototyping and seeing if something works in principle. Beyond that it's important to give things proper classes so you can relate them properly and start to refine how these things fit together.
I'd even start with TransactionHistory being a class derived from Array where you get all that functionality for free, then can go and add on custom things as necessary.
For example, you have a pretty gnarly interface to DividendsFromStock which could be cleaned up by having that format of row be accepted to the initialize function as-is.
Don't forget to write a to_s or inspect method for any custom classes you want to be able to print or have a look at. These are usually super simple to write and come in very handy when debugging.
thank you!
I will answer my question, based on the information provided by tadman and Ilya Vassilevsky (and also B. Seven).
1- It is better to create a class, and the objects. It will help me organize my code, and debug. Localize who is who and doing what. Also seems better to use with DB.
2- I am a little bit shamed with my question after figure out the solution. It is far simpler than I was thinking. Just needed two steps:
willpay = ciel3.dividends.find_all {|dividend| Date.parse(dividend.last_day_with) > Date.parse('10/09/2015')}
willpay.each do |dividend|
puts "#{ciel3.code} has approved #{dividend.type} on #{dividend.approved} and will pay by #{dividend.payment_day} the value of #{dividend.value.format} per share, for those that had the asset on #{dividend.last_day_with}"
puts
end

Adding new data types (and arithmetic operators for new data types) in picoc

I have just stumbled across picoc and I am very impressed with what it can do - especially the fact that it can be extended by adding new functions etc. It saves me from going down the route of trying to "roll my own" interpreter.
However, I am wondering if there is anyway I can extend picoc by:
Adding new data types (for example, MySimpleDataType, MyPointerDataType)
Adding simple arithmetic operator functions (+,-,/, * etc) for my new data types.
Does anyone have any experience of doing this, or can someone provide pointers on how to go about adding new data types and their operator functions to picoc?
[[Edit]]
On further inspection of the code, I believe I have found how to add new data types (by modifying type.c). However, it is still not clear to me how to add arithmetic operators for new data types in picoc. Any help appreciated,
In general, C does not have operators overloading (while C++ does). Picoc is positioned as very tiny and having only the essentials, so I don't think it provides any extensions for it.
Adding new types can be done in the same manner that you can add new functions. A simple example of this can be had by examining picoc's source stdbool.c, where you'll find a typedef int bool; in the StdboolDefs element. You have to look elsewhere, include.c, to find the element in use; you'll find it as the "SetupCSource" parameter to an IncludeRegister() call.
Regarding adding new operators -- of course it's possible but only with a rather invasive change to the picoc library. As #yeputons said, the C language doesn't allow you to change or add operators, so there's no reason for picoc to directly support that.

What is the comprehension expression in AngularJS?

I have a few questions buzzing in my head about the comprehension expression:
What is the data structure which it defines?
Was it adapted from some other language?
Where is it used in AngularJS? Does this API exist for select elements only?
From the docs:
ngOptions - comprehension_expression - in one of the following forms:
for array data sources:
label for value in array
select as label for value in array
label group by group for value in array
select as label group by group for value in array track by trackexpr
for object data sources:
label for (key , value) in object
select as label for (key , value) in object
label group by group for (key, value) in object
select as label group by group for (key, value) in object
Comprehension expression is just a string formatted in a special way to be recognized by select directive.
There's no magic behind it, just several formats of it because there are quite a few ways to process and represent your collection (data structure of your model, item/item property selection as scope's model, some other options regarding labels, grouping etc.). When you consider all these options it is not that strange for allowing complex expressions.
Let's say you have such code:
<select
ng-model="color"
ng-options="c.name group by c.shade for c in colors"></select>
In order to ditch the comprehension expression and use attributes, you would write something like this:
<select
ng-model="color"
ng-data-type="object"
ng-data="colors"
ng-select="c"
ng-label="c.name"
ng-group-by="c.shade"></select>
The attribute approach might get ugly once you expand your API. Besides, with comprehension expression it's much easier to use filters.
While in one way it's true to say that a "comprehension_expression" is "just a string" as package says, on the other hand, source code is just a string. Programming languages are just strings.
A SQL SELECT statement
– which could very well be part of the inspiration for the syntax and features of the "comprehension_expression" (but it's not obvious that it is, because it's not mentioned in the docs– perhaps if I dug into some developer conversations I might be able to find out) –
is just a string.
Sure they're just strings, but they have structure, which relates to the problem they are trying to solve. And the question is, is the structure adequately described? Is its pattern, how it relates to the problem at hand, made clear? Is its relationship to other structures that other people have designed apparent?
While the "comprehension_expression" is just a string, on the other hand, its complexity almost comes to it being a sort of sub-language in its own right.
But the way it is portrayed in the docs (https://docs.angularjs.org/api/ng/directive/ngOptions) does reflect the attitude that it is "just a string with some formatting". It is tucked away in the documentation for ng-options as the type of the ng-options directive. To some extent, it is not an entity in its own right, it is a second-class citizen.
The way the different formats are listed can give one a strange feeling, like it's sort of ad-hoc, without any pattern relating the different possible formats (although there is a pattern if you look closely). Without a formal grammar with a regular structure, it makes you wonder if they really covered all the possible options. Compared to, say, the MySQL documentation for the SQL SELECT statement: https://dev.mysql.com/doc/refman/5.7/en/select.html
Obviously such formal syntax can be quite intimidating and is maybe not necessary for the case of the "comprehension_expression", on the other hand it can be reassuring to know it is precisely defined.
I suspect the asker of the question was somewhat unsettled by how casually the "comprehension_expression" was mentioned in the docs; it can seem like a sort of floating, ghost-like entity, just mentioned briefly but not given its own page etc.
It might be worth it having its own page, being treated as an entity in its own right, because then that invites discussion as to the design of this "sub-language". How did it come about? What are the reasons for the different features of the "sub-language"? Which features, and thus syntaxes, conflict with each other? Why can this feature be used together with that feature but not another feature? Are there inspirations from e.g. SQL, in the design of this "sub-language"?
Otherwise it seems to be an invention out of the blue, unrelated to other DSLs of its kind.
In a blog post on ng-options,
https://www.undefinednull.com/2014/08/11/a-brief-walk-through-of-the-ng-options-in-angularjs/
Mr. Shidhin links to a little discussion
https://groups.google.com/forum/#!topic/angular/4EDe8xIbjLU
Where just this issue is discussed. "Matt Hughes" also expresses the opinion that "Seems like a lot of additional complexity for one directive."
Perhaps this is not that big a deal. I just wanted to put it out there though.

Calling functions from plain text descriptions

I have an app which has common maths functions behind the scenes:
add(x, y)
multiply(x, y)
square(x)
The interface is a simple google- style text field. I want the user to be able to enter a plain text description -
'2*3'
'2 times 3'
'multiply 2 and 3'
'take the product of 2 and 3'
and get a answer mathematical answer
Question is, how should I map the text descriptions to the functions ? I'm guessing I need to
tokenise the text
identify key tokens (function names, arguments)
try and map token combinations to function signatures
However I'm guessing this is already a 'solved problem' in the machine learning space. Should I be using Natural Language Processing ? Plain text search ? Something else ?
All ideas gratefully received, plus implementation suggestions [I'm using Python/AppEngine; I know about NLTK and Whoosh]
[PS I understand Google does this already, at least for the first two queries on the list. I'm guessing they also go it statistically, having a very large amount of search data. I don't have a large amount of data available, so will need an alternative approach].
After you tokenise the text, you need parsing to get a syntax tree of your natural language phrase. Once you have this, you can map the parse tree to a mathematical expression, and then evaluate the expression. I do not think this is a solved problem. I would start with several templates, say the first two, and experiment. The larger the domain of possible descriptions, the harder the task is.
I would recommend some tool for provide grammar/patterns on text like SimpleParse for python http://www.ibm.com/developerworks/linux/library/l-simple.html. As java programmer I would prefer GATE or graph-expression.

Specific functions vs many Arguments vs context dependent

An Example
Suppose we have a text to write and could be converted to "uppercase or lowercase", and can be printed "at left, center or right".
Specific case implementation (too many functions)
writeInUpperCaseAndCentered(char *str){//..}
writeInLowerCaseAndCentered(char *str){//..}
writeInUpperCaseAndLeft(char *str){//..}
and so on...
vs
Many Argument function (bad readability and even hard to code without a nice autocompletion IDE)
write( char *str , int toUpper, int centered ){//..}
vs
Context dependent (hard to reuse, hard to code, use of ugly globals, and sometimes even impossible to "detect" a context)
writeComplex (char *str)
{
// analize str and perhaps some global variables and
// (under who knows what rules) put it center/left/right and upper/lowercase
}
And perhaps there are others options..(and are welcome)
The question is:
Is there is any good practice or experience/academic advice for this (recurrent) trilemma ?
EDIT:
What I usually do is to combine "specific case" implementation, with an internal (I mean not in header) general common many-argument function, implementing only used cases, and hiding the ugly code, but I don't know if there is a better way that I don't know. This kind of things make me realize of why OOP was invented.
I'd avoid your first option because as you say the number of function you end up having to implement (though possibly only as macros) can grow out of control. The count doubles when you decide to add italic support, and doubles again for underline.
I'd probably avoid the second option as well. Againg consider what happens when you find it necessary to add support for italics or underlines. Now you need to add another parameter to the function, find all of the cases where you called the function and updated those calls. In short, anoying, though once again you could probably simplify the process with appropriate use of macros.
That leaves the third option. You can actually get some of the benefits of the other alternatives with this using bitflags. For example
#define WRITE_FORMAT_LEFT 1
#define WRITE_FORMAT_RIGHT 2
#define WRITE_FORMAT_CENTER 4
#define WRITE_FORMAT_BOLD 8
#define WRITE_FORMAT_ITALIC 16
....
write(char *string, unsigned int format)
{
if (format & WRITE_FORMAT_LEFT)
{
// write left
}
...
}
EDIT: To answer Greg S.
I think that the biggest improvement is that it means that if I decide, at this point, to add support for underlined text I it takes two steps
Add #define WRITE_FORMAT_UNDERLINE 32 to the header
Add the support for underlines in write().
At this point it can call write(..., ... | WRITE_FORMAT_UNLDERINE) where ever I like. More to the point I don't need to modify pre-existing calls to write, which I would have to do if I added a parameter to its signature.
Another potential benefit is that it allows you do something like the following:
#define WRITE_ALERT_FORMAT (WRITE_FORMAT_CENTER | \
WRITE_FORMAT_BOLD | \
WRITE_FORMAT_ITALIC)
I prefer the argument way.
Because there's going to be some code that all the different scenarios need to use. Making a function out of each scenario will produce code duplication, which is bad.
Instead of using an argument for each different case (toUpper, centered etc..), use a struct. If you need to add more cases then you only need to alter the struct:
typedef struct {
int toUpper;
int centered;
// etc...
} cases;
write( char *str , cases c ){//..}
I'd go for a combination of methods 1 and 2.
Code a method (A) that has all the arguments you need/can think of right now and a "bare" version (B) with no extra arguments. This version can call the first method with the default values. If your language supports it add default arguments. I'd also recommend that you use meaningful names for your arguments and, where possible, enumerations rather than magic numbers or a series of true/false flags. This will make it far easier to read your code and what values are actually being passed without having to look up the method definition.
This gives you a limited set of methods to maintain and 90% of your usages will be the basic method.
If you need to extend the functionality later add a new method with the new arguments and modify (A) to call this. You might want to modify (B) to call this as well, but it's not necessary.
I've run into exactly this situation a number of times -- my preference is none of the above, but instead to use a single formatter object. I can supply it with the number of arguments necessary to specify a particular format.
One major advantage of this is that I can create objects that specify logical formats instead of physical formats. This allows, for example, something like:
Format title = {upper_case, centered, bold};
Format body = {lower_case, left, normal};
write(title, "This is the title");
write(body, "This is some plain text");
Decoupling the logical format from the physical format gives you roughly the same kind of capabilities as a style sheet. If you want to change all your titles from italic to bold-face, change your body style from left justified to fully justified, etc., it becomes relatively easy to do that. With your current code, you're likely to end up searching through all your code and examining "by hand" to figure out whether a particular lower-case, left-justified item is body-text that you want to re-format, or a foot-note that you want to leave alone...
As you already mentioned, one striking point is readability: writeInUpperCaseAndCentered("Foobar!") is much easier to understand than write("Foobar!", true, true), although you could eliminate that problem by using enumerations. On the other hand, having arguments avoids awkward constructions like:
if(foo)
writeInUpperCaseAndCentered("Foobar!");
else if(bar)
writeInLowerCaseAndCentered("Foobar!");
else
...
In my humble opinion, this is a very strong argument (no pun intended) for the argument way.
I suggest more cohesive functions as opposed to superfunctions that can do all kinds of things unless a superfunction is really called for (printf would have been quite awkward if it only printed one type at a time). Signature redundancy should generally not be considered redundant code. Technically speaking it is more code, but you should focus more on eliminating logical redundancies in your code. The result is code that's much easier to maintain with very concise, well-defined behavior. Think of this as the ideal when it seems redundant to write/use multiple functions.

Resources