Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
C#:
var articles = Article
.OrderBy(x=> x.Name)
.Where(x=> x.Name.Contains(pattern))
.Select(x=>new {x.Name + " (article)"})
.ToList();
It's good to write this way in C# and it's called "methods concatenation". In fact, I don't remember exactly how they are called, I read it in Jon Skeet's book. The idea is that each method is on a new line, and it's normal in C#.
What about Ruby? Is it normal to write:
articles = Article
.order(:name)
.where("name like ?","%#{pattern}%")
.map(&:name)
.map {|c| c << " (article)"}
Method chaining is a staple in many languages, Ruby included. Its use is largely a matter of personal taste – some, like tokland, don't like the large expressions that can result, whereas I will gladly expand an expression to eliminate temporary variables.
Subjective question, so her's a subjective answer (as Ruby programmer):
I prefer not to create "holes", in my code I wouldn't insert that level of indentation.
You can also insert the dots at the end of the line. Which is more readable? hard to say, I prefer the latter (although I don't mind at the beginning of the line, it's not a big deal). So I'd probably write (note that those two maps could be joined):
article_names = Article.
order(:name).
where("name LIKE ?", "%#{pattern}%").
map(&:name).
map { |name| name + " (article)"}
In my experience, long chains make code harder to follow. When the chain grows too much (5, 6 elements?) I tend to break it creating intermediate variables with meaningful names, this helps me to further describe the expression:
filtered_articles = Article.order(:name).where("name LIKE ?", "%#{pattern}%")
names = filtered_articles.map { |article| "#{article.name} (article)" }
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
In C#, how can I sort strings that separated by special character, like ","
For example I have string like this
string sStates="IA,KY,CT,ME,AZ";
How can I re-sort them alphabetically like
"AZ,CT,IA,KY"
Split them in an Array will work.
But is there a more effective way?
Thanks in advance for help.
This can be done within a single line of code using linq:
var result = string.Join(",", source.Split(",").OrderBy(s => s));
Efficiency considerations should not apply here unless you're doing this for huge strings (or a hugh number of strings) under a tight timeline, or having an actual performance problem.
Readable code is far better then fast code.
As a rule - You should design your code for clarity, not for performance. Write code that conveys the algorithm it is implementing in the clearest way possible. Set performance goals and measure your code's performance against them. If your code doesn't measure to your performance goals, Find the bottle necks and treat them. Don't go wasting your time on nano-optimizations when you design the code.
You can achieve it in this simple way
var orderedString = source.Split(",").OrderBy(p => p);
var result = string.Join(",", orderedString);
I'm a fan of using Lists in .Net personally.
using System.Linq;
var sStates = "IA,KY,CT,ME,AZ";
var orderedList = sStates.Split(',').ToList().OrderBy(o => o);
var orderedString = string.Join(",", orderedList.ToArray());
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am very sure that there is a technical term for this problem, but unfortunately I do not know it.
I have an alphabetical charset and the requirement is to create the combination of all the chars with a maximum length
The idea is (sample):
Generate a collection of A, AA, AAA, AAAA, AAAAA, AAAAAA
Next: A, AB, ABA, ABAA, ABAAA
Next A, AB, ABB, ABBA, ABBAA
The reason:
We have to query an API that delivers search results.
But if I don't get search hits from the API on AAA, I don't need to search for AAAA anymore, because it can't get search hits either. I can then move on to AAB.
The question:
My problem is that I'm not sure how the code has to be built to achieve this goal. I lack the structural approach.
I've already tried nested loops, but unfortunately I don't get the result.
I also used Combination Libraries, but they focus on other problems.
Many thanks for hints!
What you're looking for is a particular data structure called a Tree, but probably more specifically in your case, a Trie.
Trie data structures are commonly used in things like Autocomplete. With the image below, if someone typed "te", I can traverse the Trie and see what options would come after that (tea, ted, ten).
It looks like this would also fit your use case from what I can tell.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Is this "better", faster or easier to read:
var viewsOnSheet = templateSheet.GetAllViewports()
.Select(x => doc.GetElement(x))
.Cast<Viewport>()
.Select(x => doc.GetElement(x.ViewId))
.Cast<View>();
...than this:
foreach (ElementId id in templateSheet.GetAllViewports())
{
Viewport vp = doc.GetElement(id) as Viewport;
View v = doc.GetElement(vp.ViewId) as View;
}
They both work, I am just curious if there is some programming standard that I would be violating with so many nested Linq calls. What's easier to understand? I am personally leaning towards the foreach loop.
Thanks!
For Linq-to-objects, code with foreach is always marginally faster that equivalent LINQ call just because at the end LINQ end up with similar foreach after several method calls. For Linq-to-SQL/Linq-to-XML equivalent code with less function calls would be faster too just because you execute less code.
Note that proper matching code for more complex LINQ expressions may not be easy to write (try writing GroupBy yourself correctly) and definitely will not be shorter than LINQ.
Whether this performance different matters for your application - measure yourself against your particular performance goals.
Style of code is strictly personal preference - pick whatever works for you/your team.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I need to extract some words out of a paragraph of text if the word starts with %! and ends with !%
I'd imagine regex would be good for this but unfortunately my regex isn't that great...OK its pretty bad...OK its non existent :(.
EXAMPLE TEXT
You don't want no %!beef!%, boy
Know I run the streets, boy
Better follow me towards
Downtown
What you see is what you get %!girl!%
Don't ever forget girl
Ain't seen nothing yet until you're
%!Downtown!%
EXPECTED RESULT
beef, girl, Downtown
How can I achieve this in C# with or without regex?
Like this:
var reg = new Regex(#"%!(?<word>\w+)!%");
var inStr = #"You don't want no %!beef!%, boy
Know I run the streets, boy
Better follow me towards
Downtown
What you see is what you get %!girl!%
Don't ever forget girl
Ain't seen nothing yet until you're
%!Downtown!%";
var results = reg.Matches(inStr).Cast<Match>().Select(m => m.Groups["word"].Value);
This will give you a list of matched words. Converting it to a comma-separated string is an exercise I'll leave up to you..
Also, next time you should probably do some quick research, you're eventually going to have to learn simple regexes..
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a FASTA file containing several protein sequences. The format is like
----------------------
>protein1
MYRALRLLARSRPLVRAPAAALASAPGLGGAAVPSFWPPNAAR
MASQNSFRIEYDTFGELKVPNDKYYGAQTVRSTMNFKIGGVTE
RMPTPVIKAFGILKRAAAEVNQDYGLDPKIANAIMKAADEVAE
GKLNDHFPLVVWQTGSGTQTNMNVNEVISNRAIEMLGGELGSK
IPVHPNDHVNKSQ
>protein2
MRSRPAGPALLLLLLFLGAAESVRRAQPPRRYTPDWPSLDSRP
LPAWFDEAKFGVFIHWGVFSVPAWGSEWFWWHWQGEGRPYQRF
MRDNYPPGFSYADFGPQFTARFFHPEEWADLFQAAGAKYVVLT
TKHHEGFTNW*
>protein3
MKTLLLLAVIMIFGLLQAHGNLVNFHRMIKLTTGKEAALSYGF
CHCGVGGRGSPKDATDRCCVTHDCCYKRLEKRGCGTKFLSYKF
SNSGSRITCAKQDSCRSQLCECDKAAATCFARNKTTY`
-----------------------------------
Is there a good way to read in this file and store the sequences separately?
Thanks
To do this one way is to:
Create a vector where each location
holds a name and the sequence
Go through the file line by line
If the line starts with > then add
an element to the end of the vector
and save the line.substring(1) to
the element as the protein name.
Initialize the sequence in the
element to equal "".
If the line.length == 0 then it is
blank and do nothing
Else the line doesn't start with >
then it is part of the sequence so
go current vector element.sequence
+= line. Thus way each line between >protein2 and >protein3 is
concatenated and saved to the
sequence of protein2
I think maybe a little more detail about the exact file structure could be helpful. Just looking at what you have (and a quick peek at the samples on wikipedia) suggest that the name of the protein is prepended with a >, followed by at least one line break, so that would be a good place to start.
You could split the file on newline, and look for a > character to determine the name.
From there it is a little less clear because I'm not sure if the sequence data is all in one line (no linebreaks) or if it could have linebreaks. If there are none, then you should be able to just store that sequence information, and move on to the next protein name. Something like this:
var reader = new StreamReader("C:\myfile.fasta");
while(true)
{
var line = reader.ReadLine();
if(string.IsNullOrEmpty(line))
break;
if(line.StartsWith(">"))
StoreProteinName(line);
else
StoreSequence(line);
}
If it were me, I would probably use TDD and some sample data to build out a simple parser, and then keep plugging in samples until I felt I had covered all of major variances in the format.
Can you use a language other than C#? There are excellent libraries for dealing with FASTA files and other biological sequence in Perl, Python, Ruby, Java, and R (off the top of my head). They're usually branded Bio* (i.e. BioPerl, BioJava, etc)
If you're interested in C or C++, check out the answers to this question over at Biostar:
http://biostar.stackexchange.com/questions/1516/c-c-libraries-for-bioinformatics
Do yourself a favor, and don't reinvent the wheel if you don't have to.