Is there any possibility to decode Morse code to text if the code is in following format(without any white spaces):
-.-..--.....-...--..----.
Normally it looks like that,
- .-. .- -. ... .-.. .- - .. --- -.
t r a n s l a t i o n
but is it possible, to get the same text from Morse code without white spaces?
This is possible to do, but it becomes problematic as you end up generating a large number of possible options.
First start with a Morse mapping:
private Dictionary<string, string> map = new Dictionary<string, string>()
{
{ ".-", "a" },
{ "-...", "b" },
{ "-.-.", "c" },
{ "-..", "d" },
{ ".", "e" },
{ "..-.", "f" },
{ "--.", "g" },
{ "....", "h" },
{ "..", "i" },
{ ".---", "j" },
{ "-.-", "k" },
{ ".-..", "l" },
{ "--", "m" },
{ "-.", "n" },
{ "---", "o" },
{ ".--.", "p" },
{ "--.-", "q" },
{ ".-.", "r" },
{ "...", "s" },
{ "-", "t" },
{ "..-", "u" },
{ "...-", "v" },
{ ".--", "x" },
{ "-..-", "y" },
{ "-.--", "z" },
{ "--..", " " },
};
Then this function can produce the possible decodings:
public IEnumerable<string> DecodeMorse(string morse)
{
var letters =
map
.Where(kvp => morse.StartsWith(kvp.Key))
.Select(kvp => new
{
letter = kvp.Value,
remainder = morse.Substring(kvp.Key.Length)
})
.ToArray();
if (letters.Any())
{
var query =
from l in letters
from x in DecodeMorse(l.remainder)
select l.letter + x;
return query.ToArray();
}
else
{
return new [] { "" };
}
}
Now, given a shorter version of your input morse, "-.-..--....", I got 741 possible strings. Here's the cut down version:
cabe
cadee
cadi
…
tranie
trans
trateeee
…
trxii
trxse
It includes "trans" so it seems to be working.
Running on the full string produces 5,914,901 possible with "translation" as one of the possibilities.
Incidentally, there were 4,519 possible strings that simply started with "trans". How humans could do this on the fly is amazing!
What you are proposing isn't really possible.
You will not be able to tell where one letter ends and the next begins. How will you be able to tell the difference between letters? Will the first letter be -, -., or -.-?
There is no doubt in my mind that given a sufficiently advanced algorithm, and sufficient context around each letter, that it is possible to get a high level of accuracy. However the problem approaches AGI-level difficulty the greater accuracy that you require, because this is one of the skills (fast pattern matching in language) that humans are particularly good at and machines are nowhere near as good at (yet). The reason for that, is that broader context that makes pattern matching possible for humans includes not just possible words, but semantics and the overall meaning of the story, and mapping that to model of the world that makes sense. This is something that is extremely difficult to program a computer to do. Also the human brain is massively parallel.
Also, it is fairly trivial to prove that a general perfect solution is impossible (perfect accurate translation for every possible input string). For example, consider simply the short string ".--", that could mean "at" or "em", both valid English words.
You need to know where the characters start and end. Take, for instance:
...---...
If you divide it one way, you get:
... --- ... = SOS
However, if you divide it differently, you may get:
. .. - -- . .. = EITMEI
So, is it possible? Technically, yes, it's possible. However, you would have a huge number of possible solutions that would take a long time to identify and translate. With a database of commonly seen words, you might be able to make this a bit smarter, but it would still be a best-effort.
Related
The question is in title.
What does comma mean as a length of array in C#?
How it is called, how to find it on the Internet?
I searched for "how to initialize array in C#" in google but there is no information about this comma.
If I remove comma VS shows an error: "array initializers can only be used in a variable".
Even after assigning it to variable it still shows error.
EntityFramework generates the following code:
migrationBuilder.InsertData(
table: "Test",
columns: new[] { "Name" },
values: new object[,]
{
{ "Test" },
{ "Test1" }
});
The coma does not represent a length, it represent a dimension. In your case, it can be called a 2d array. It allows you to do this:
values: new object[,]
{
{ "Testa", "Testb", "Testc" },
{ "Test1a", "Test1b", "Test1c" }
}
I'm using ASP.NET Core 2.1. I have settings in appsettings.json and I bind them to classes using the options pattern. I want to override some of them in appsettings.Production.json.
Overriding is supported according to the docs, and works for me generally.
But it doesn't work for arrays.
appsettings.json:
"MySectionOuter": {
"MySectionInner": [
{
"foo": "1",
"bar": "2",
"baz": "3"
},
{
"foo": "a",
"bar": "b",
"baz": "c"
}
]
}
My overrides in appsettings.Production.json
"MySectionOuter": {
"MySectionInner": [
{
"bar": "4",
},
{
"baz": "d"
}
]
}
However that doesn't work - it adds rather than replaces.
I read that the array is syntactic sugar for a key-value store. So I also tried this:
"MySectionOuter": {
"MySection:1": {
"bar": "4",
},
"MySection:2": {
"baz": "b",
}
}
But that also doesn't work.
What is the correct syntax?
UPDATE
The comments show I haven't explained properly. What I want is like this:
During development:
element1: foo=1
element1: bar=2
element1: baz=3
element2: foo=a
element2: bar=b
element2: baz=c
During production:
element1: foo=1
element1: bar=2
element1: baz=4 // this was changed
element2: foo=a
element2: bar=b
element2: baz=d // this was changed
In fact, there are no arrays there when the configuration is built. It's just a key-value pair dictionary. So you end up with string keys, something like
"mysectionouter:mysectioninner:0:foo" = 1.
So when in your config you define an array, the following happens:
appsettings.json:
"mysectionouter:mysectioninner:0:foo" = 1
"mysectionouter:mysectioninner:0:bar" = 2
appsettings.production.json:
"mysectionouter:mysectioninner:0:bar" = new1
result:
foo = 1
bar = new1
So it's just index-based, and next configuration just overrides a key. In your second example, you achieve nothing but changing the index. Representation would be:
"mysectionouter:mysectioninner:1:bar" = new1
So back to your question: arrays are tricky in appsettings, and though supported, are generally hard and not intuitive to use.
By index you may get a weird merge of two not related objects, if you define different sets of settings in your files, like settings A and B in the first config, and C in second, you will get C and B in the result, and you likely don't want to have B at all. Worse still, you can get a mix of A and C if you define only some fields of each object.
I'd recommend using some other files for storing this kind of information. You can also break in the debugger just where the configuration is loaded and see for yourself how these keys are build to get more insight.
According to this blog post: https://www.paraesthesia.com/archive/2018/06/20/microsoft-extensions-configuration-deep-dive/
It's not possible to remove configuration items with a provider.
You can add configuration at override time, but you can’t remove things. The best you can do is override a value with an empty string.
Instead you should only fill as little information as needed in the appsettings.config and fill the appropriate settings in a more specialized settings file. E.g. appsettings.Development.config or your appsettings.Production.config. Or as suggested in the blog post:
Since you can’t remove things, specify as little configuration as possible and behave correctly using defaults in your code when configuration isn’t there.
I was actually having a similar issue in dotnet 6, when trying to merge arrays from multiple appsettings, when I stumbled across this thread.
The solution was actually way simpler then thought.
Microsoft.Extensions.Configuration merges arrays through the index:
{ foo: [1, 2, 3] } + { foo: [4, 5] } = { foo: 4, 5, 3 }
But we want to be able to declare which entries override others and which ones should be added to the list. And we do this by declaring a GUID as dictionary key instead of an array.
{
"foo": {
"870622cb-0372-49f3-a46e-07a1bd0db769": 1,
"cbb3af55-94ea-41a5-bbb5-cb936ac47249": 2,
"9410fcdc-28b3-4bff-bfed-4d7286b33294": 3
}
}
+
{
"foo": {
"cbb3af55-94ea-41a5-bbb5-cb936ac47249": 4,
"1c43fa78-b8db-41f8-809d-759a4bc35ee2": 5,
}
}
=
{
"foo": {
"870622cb-0372-49f3-a46e-07a1bd0db769": 1,
"cbb3af55-94ea-41a5-bbb5-cb936ac47249": 4, /*2 changed to 4 because key equals*/
"9410fcdc-28b3-4bff-bfed-4d7286b33294": 3
"1c43fa78-b8db-41f8-809d-759a4bc35ee2": 5, /*while 5 added to the list*/
}
}
This may seem inconventient at first, because one would think, that
((IConfiguration)config).GetSection("foo").Get<int[]>();
Throws some kind of invalid type exception, since a Guid is not what we know as array index.
But it can actually (implicitly!) return the merged "foo" section above as int[].
I'm a beginner in c# and I am working with text exercises. I made a method to filter vehicle's plate numbers. It should consist of 3 letters and 3 integers ( AAA:152 ). My method sends the wrong plate numbers to a file, but also it adds that bad number to a good ones list.
private static string[] InvalidPlates(string[] csvLines, int fieldToCorrect)
{
var toReturn = new List<string>();
var toSend = new List<string>();
int wrongCount = 0;
for (int i = 0; i < csvLines.Length; i++)
{
string[] stringFields = csvLines[i].Split(csvSeparator[0]);
string[] values = stringFields[fieldToCorrect].Split(':');
if(Regex.IsMatch(values[0], #"^[a-zA-Z]+$") && Regex.IsMatch(values[1], "^[0-9]+$"))
{
toReturn.Add(string.Join(csvSeparator, stringFields));
}
else
{
toSend.Add(string.Join(csvSeparator, stringFields));
wrongCount++;
}
}
WriteLinesToFile(OutputFile, toSend.ToArray(), wrongCount);
return toReturn.ToArray();
}
Can somebody help me to fix that?
You need to constrain the possible length using quantifiers:
^[a-zA-Z]{3}\:\d{3}$
which literally means the following, in the strict order:
the strings begins from exactly 3 lowercase or uppercase English alphabet letters, continues with semicolon (:), and ends with exactly three digits
Remember that \ should be escaped in C#.
Also, there is no need to join stringFields back into a string, when you can use non-splitted csvLines[i]:
if (Regex.IsMatch(stringFields, #"^[a-zA-Z]{3}\\:\\d{3}$"))
toReturn.Add(csvLines[i]);
}
else
{
toSend.Add(csvLines[i]);
wrongCount++;
}
Another important thing is that your code is incorrect in terms of OOP. It is pretty inobvious that your method called InvalidPlates will save something to a file. It may confuse you after some time or other developers. There should be no "hidden" functionality, and all methods should actually do only the one thing.
Here is how I would do this using LINQ:
private static bool IsACorrectPlate(string p) => Regex.IsMatch(p, #"^[a-zA-Z]{3}\:\d{3}$");
private static void SortPlatesOut(string[] csvLines, int column, out string[] correct, out string[] incorrect)
{
var isCorrect = csvLines
.GroupBy(l => IsACorrectPlate(l.Split(';')[column]))
.ToDictionary(g => g.Key, g => g.ToArray());
correct = isCorrect[true];
incorrect = isCorrect[false];
}
// Usage:
string[] incorrect, correct;
SortPlatesOut(csvLines, 1, out correct, out incorrect);
File.WriteAllLines("", incorrect);
// do whatever you need with correct
Now, SortPlatesOut method has an expectable behavior without side effects. The code has also become two times shorter. At the same time, it looks more readable for me. If it looks non-readable for you, you can unpack LINQ and split some things other things up.
I would like to sort an array in JavaScript as asc. After I used sort method, the result is like below.
[ '123, '12', '1A1', '1A', '1a', 'A1', 'A2', 'AB', 'A', 'Ab', 'a1', 'a2', 'aB', 'ab' ]
When I'm using sort Array.Sort() by C#, the result is like below.
{ "12", "123", "1a", "1A", "1A1", "A", "a1", "A1", "a2", "A2", "ab", "aB", "Ab", "AB" }
Actually the C# sort way is what I want, so how to implement it in JavaScript? Has anyone completed this task before? A comparator function is really appreciate.
Array.prototype.sort uses string comparison by default. It seems you want to compare case insensitive - you could pass in a comparator function that uses toLowerCase (but beware of the difference with .toLocaleLowerCase!):
a.sort(function(a, b) {
a = a.toLowerCase(); b = b.toLowerCase();
return a > b ? 1 : a < b ? -1 : 0;
});
Why is this .NET enumeration allowed to have a comma in the last field?
Does this have any special meaning?
[FlagsAttribute]
public enum DependencyPropertyOptions : byte
{
Default = 1,
ReadOnly = 2,
Optional = 4,
DelegateProperty = 32,
Metadata = 8,
NonSerialized = 16,
}
It has no special meaning, just the way the compiler works, it's mainly for this reason:
[FlagsAttribute]
public enum DependencyPropertyOptions : byte
{
Default = 1,
ReadOnly = 2,
Optional = 4,
DelegateProperty = 32,
Metadata = 8,
NonSerialized = 16,
//EnumPropertyIWantToCommentOutEasily = 32
}
By comment request: This info comes straight out of the C# Specification (Page 355/Section 17.7)
Like Standard C++, C# allows a trailing comma at the end of an array-initializer. This syntax provides flexibility in adding or deleting members from such a list, and simplifies machine generation of such lists.
Also (to Nick Craver post) its much easier to add new enumerations.
This behaviour appropriate not uniquely to enums. Consider following:
var list = new int[] { 1, 2, 3, };
One other reason: It makes it easier to code gen.
I know that it is an old topic but, another approach that would make sense for this issue is for code versioning systems.
Consider the following example:
//version 1
var myArray = {
"item 1",
"item 2"
};
//version 2
var myArray = {
"item 1",
"item 2", //will be considered a change, it may be considered an erroneous approach
"item 3"
}
Now consider this approach:
//version 1
var myArray = {
"item 1",
"item 2",
};
//version 2
var myArray = {
"item 1",
"item 2", //will not be considered a change, it may be considered an erroneous approach too, but, means that the code wasn't changed intrinsically
"item 3",
};
Anyhow, both approaches may be considered incorrect or correct depending on the situation. I particularly prefer the second approach that makes much more sense when dealing with code versioning systems.
Anyway hope this helps.
Why add trailing commas
Why you should take advantage of this feature when writing code manually?
The resultant patches have less lines affected. This makes them easier to read and review.
Automatic merge and conflict resolution are more accurate because there isn't extra noise to confuse the algorithm.
Examples
Without trailing comma (okay)
Example of adding a line when the previous developer didn't leave a trailing comma:
## -119,7 +119,8 ## namespace SomeApp.Example
{
NameTitle = contact.NameTitle,
GivenName = contact.GivenName,
- FamilyName = contact.FamilyName
+ FamilyName = contact.FamilyName,
+ ProperName = contact.ProperName
},
ContactTelephone1 = contact.ContactTelephone1,
ContactType = contact.ContactType,
Without trailing comma (better)
Example of adding a line when the previous developer left a trailing comma:
## -122,2 +122,3 ## namespace SomeApp.Example
FamilyName = contact.FamilyName,
+ ProperName = contact.ProperName,
},
Note there is one line added in the latter vs one removed and two added. This is much easier for human and machine alike to deal with.
Why did they add it to C#?
As for why it is allowed, as per other answers:
The C# Specification (Page 355/Section 17.7) states:
Like Standard C++, C# allows a trailing comma at the end of an array-initializer. This syntax provides flexibility in adding or deleting members from such a list, and simplifies machine generation of such lists.
This applies to array initializers, object initializers and enums.