VueJS and UTF-8 encoding issue: Correctly formatting user copy and pasted text - vuejs2

I am using a data api that is returning text like so (from an archaic database):
I’m attaching a couple of our “quick look� cards covering the process
Notice the ’ symbols in the text. It appears that perhaps the user had copy and pasted text from an email message (outlook) or Microsoft Word and it appears to be a replacement for a comma or apostrophe (or who knows what else)?
Looks like this is what needs to be replaced:
[{broken: '–', fixed: "—"}
{broken: "—", fixed: "–"}
{broken: "‘", fixed: "‘"}
{broken: "’", fixed: "’"}
{broken: "“", fixed: "“"}
{broken: "â€", fixed: "”"}, ...]
Is there something I can do on the front end to replace those symbols with the correct character?

This sounds like an encoding problem and is described here and is, as you also described, reduced to a few characters:
The following characters fail, while other characters display
correctly:
€ ‚ ƒ „ … † ‡ ˆ ‰ Š ‹ Œ Ž ‘ ’ “ ” • – — ˜ ™ š › œ ž Ÿ.
There is also a debug sheet to find out the expected characters in UTF-8.
So maybe a solution would be to replace these list of characters after getting the data from the API or handling it with a function.
I made a fiddle with replaces that chars with the function replaceEncodingErrorCharsInString() :
new Vue({
el: "#app",
data: {
encodingReplacement: [
{
broken: '–',
fixed: "—"
},
{
broken: "—",
fixed: "–"
}, {
broken: "‘",
fixed: "‘"
}, {
broken: "’",
fixed: "’"
}, {
broken: "“",
fixed: "“"
}, {
broken: "â€",
fixed: "”"
}],
exampleTexts: [
"This is – !",
"This is — !",
"This is ‘ !",
"This is ’ !",
"This is “ !",
"This is – !"
]
},
methods: {
replaceEncodingErrorCharsInString: function(text){
for(let i=0; i < this.encodingReplacement.length; i++) {
// string contains "broken" chars
if(text.includes(this.encodingReplacement[i].broken)) {
text = text.replace(this.encodingReplacement[i].broken, this.encodingReplacement[i].fixed)
}
}
// string is fine, just return it
return text
}
}
})

Related

Karate Api : check if a phrase is available response object array

I've a response
{ errors: [
{
code: 123,
reason: "this is the cause for a random problem where the last part of this string is dynamically generated"
} ,
{
code: 234,
reason: "Some other error for another random reason"
}
...
...
}
Now when I validate this response
I use following
...
...
And match response.errors[*].reason contains "this is the cause"
This validation fails, because there is an equality check for complete String for every reason ,
I all I want is, to validate that inside the errors array, if there is any error object, which has a reason string type property, starting with this is the cause phrase.
I tried few wild cards but didn't work either, how to do it ?
For complex things like this, just switch to JS.
* def found = response.errors.find(x => x.reason.startsWith('this is the cause'))
* match found == { code: 123, reason: '#string' }
# you can also do
* if (found) karate.log('found')
Any questions :)

Reduce duplications (save complicated transforms for later use) in VScode snippets

Is there a way to create custom variables inside a VScode snippet?
I have these kind of snippets where I create a singleton, based on the name of a file and a folder.
Here's the snippet:
"Service": {
"prefix": "singletonByPath",
"body": [
"class ${TM_DIRECTORY/.*[^\\w]([a-z])(\\w+)$/${1:/upcase}$2/g}${TM_FILENAME_BASE/([a-z])(\\w+)/${1:/upcase}$2/g} {",
" $0",
"}",
"",
"export const ${TM_DIRECTORY/.*[^\\w]([a-z])(\\w+)$/${1:/downcase}$2/g}${TM_FILENAME_BASE/([a-z])(\\w+)/${1:/upcase}$2/g} = new ${TM_DIRECTORY/.*[^\\w]([a-z])(\\w+)$/${1:/upcase}$2/g}${TM_FILENAME_BASE/([a-z])(\\w+)/${1:/upcase}$2/g}();",
""
],
"description": "Create an exported singleton instance and a class based on the filename and path"
},
So, when the snippet is triggered in a path like: '..../customers/service.ts' You will have this result:
class CustomersService {
}
export const customersService = new CustomersService();
The problem is that I have duplications of long hard to read regexes, and I would like to extract them to variables (or mirrors without tab stops).
I would even prefer having these variables in a "snippet-global location" so that I can use them in multiple snippets.
Is it possible to somehow reduce these duplications?
There are a couple of things you can do to simplify your snippet. There is no built-in way to save "variables" of pre-defined snippet parts.
Here though is a simplification of your code:
"Service": {
"prefix": "singletonByPath",
"body": [
// "class ${TM_DIRECTORY/.*[^\\w]([a-z])(\\w+)$/${1:/upcase}$2/g}${TM_FILENAME_BASE/([a-z])(\\w+)/${1:/upcase}$2/g} {",
"class ${1:${TM_DIRECTORY/.*[^\\w]([a-z])(\\w+)$/${1:/upcase}$2/g}}${2:${TM_FILENAME_BASE/([a-z])(\\w+)/${1:/upcase}$2/g}} {",
-- --
" $0",
"}",
"",
// "export const ${TM_DIRECTORY/.*[^\\w]([a-z])(\\w+)$/${1:/downcase}$2/g}${TM_FILENAME_BASE/([a-z])(\\w+)/${1:/upcase}$2/g} = new ${TM_DIRECTORY/.*[^\\w]([a-z])(\\w+)$/${1:/upcase}$2/g}${TM_FILENAME_BASE/([a-z])(\\w+)/${1:/upcase}$2/g}();",
"export const ${1/(\\w+)/${1:/downcase}/}$2 = new $1$2();",
""
],
"description": "Create an exported singleton instance and a class based on the filename and path"
}
Note the use of $1:${TM_DIRECTORY...} and likewise ${2:${TM_FILENAME_BASE...}
This effectively sets $1 to the result of the TM_DIRECTORY transform and $2 to the result of the TM_FILENAME_BASE transform and those "variables" can be used elsewhere in the snippet by just referring to $1 and $2.
Those "variables" can even be transformed themselves as in the ${1/(\\w+)/${1:/downcase}/} transform in the last line.
The last line of your snippet then becomes simply:
"export const ${1/(\\w+)/${1:/downcase}/}$2 = new $1$2();",
You will have to tab a couple of times because those "variables" are now tabstops, and the last transform won't be completed until you do tabstop past it, but that is a small price to pay for such a simplification.
There are other simplifications to your snippet that aren't "variable-related":
"body": [
"class ${1:${TM_DIRECTORY/.*[\\/\\\\](.*)/${1:/capitalize}/}}${2:${TM_FILENAME_BASE/(.*)/${1:/capitalize}/}} {",
" $0",
"}",
"",
"export const ${1/(\\w+)/${1:/downcase}/g}$2 = new $1$2();",
""
],
You can use the capitalize transform. Also note that this last body works for Windows and linux path separators.

What is the exception that should be thrown when user input is blank?

I've been searching for some time now, and I'm sure I've missed it, is there any documentation that states what should be thrown when a value is incorrect/blank?
For example, Python has ValueError and the documentation clearly states when to use it.
I have the following method:
proc getJobinfo {question} {
puts -nonewline "$question: "
flush stdout
gets stdin answer
set cleanedanswer [string trim [string totitle $answer]]
if {$cleanedanswer eq ""} {
# What error should be thrown?
}
return $cleanedanswer
}
I've searched throw, error, and catch, but couldn't find it.
Tcl doesn't have a pre-defined hierarchy of exceptions. The throw command takes 2 arguments: type is a list of words; and message is an error message for humans.
You could do something like
proc getJobinfo {question} {
...
if {$cleanedanswer eq ""} {
throw {Value Empty} "Please provide a suitable answer."
} elseif {[string length $cleanedanswer] < 5} {
throw {Value Invalid} "Your answer is too short."
} else ...
return $cleanedanswer
}
If you want to trap that error:
try {
set answer [getJobinfo "What is the answer to this question"]
} trap {Value *} msg {
puts "Value Error: $msg"
}
throw and try interact via the type words of the throw call. We throw "Value Empty" or "Value Invalid". In the trap, we match Value exactly, but we won't match * exactly. In hindsight the * should not be there.
The try manpage is not super clear at first read:
trap pattern variableList script
This clause matches if the evaluation of body resulted in an error and the prefix of the -errorcode from the interpreter's status dictionary is equal to the pattern. The number of prefix words taken from the -errorcode is equal to the list-length of pattern, and inter-word spaces are normalized in both the -errorcode and pattern before comparison.
pattern is not a pattern in the regexp or string match sense: it's a list of words that is matched one-by-one with the list of words thrown in the try body.
The try can be implemented with multiple traps to have cascading "catches":
try {
set answer [getJobinfo "What is the answer to this question"]
} trap {Value Empty} msg {
do something specific here
} trap {Value Invalid} msg {
do something specific here
} trap {Value} msg {
do something general for some other "throw {Value anything} msg"
} on error e {
this can be default catch-all for any other error
} finally {
any cleanup code goes here
}

deserialization issue with char '\'

Does json.net have an in built method that would escape special characters? My json strings I recv from vendors have \, double " .
If not what is the best way to escape the special charecters before invoking JsonConvert.DeserializeObject(myjsonString)?
My sample json string
{
"EmailAddresses": [
{
"EmailAddress": "N\A"
}
]
}
Pasting this in json lint results in
Parse error on line 4:
... "EmailAddress": "N\A",
-----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
VB.NET code
instanceofmytype = JsonConvert.DeserializeObject(Of myType)(myJsonString)
Exception: Newtonsoft.Json.JsonReaderException: Bad JSON escape sequence:
The JSON is not valid: a \ must be followed by one of the following: "\/bfnrtu. Since it's followed by A, Json.NET chokes (as it ought to). The source of your JSON should be fixed. If this is not an option, you can make a guess to fix it yourself, e.g.
myStr = Regex.Replace(myStr, "\\(?=[^""\\/bfnrtu])", "\\")
You shouldn't have to worry about it. JSON.NET handles a lot of nice things for you. It should just work.
Have you tried it?

Parsing JSON file using JSONKit

I am constructing a tuning fork app. The fork should allow up to 12 preset pitches.
Moreover, I wish to allow the user to choose a theme. Each theme will load a set of presets (not necessary to use all of them).
My configuration file would look something like this*:
theme: "A3"
comment: "An octave below concert pitch (ie A4 440Hz)"
presets: {
A3 220Hz=220.0
}
// http://en.wikipedia.org/wiki/Guitar_tuning
theme: "Guitar Standard Tuning"
comment:"EADGBE using 12-TET tuning"
presets: {
E2=82.41
A2=110.00
D3=146.83
G3=196.00
B3=246.94
E4=329.63
}
theme: "Bass Guitar Standard Tuning"
comment: "EADG using 12-TET tuning"
presets: {
E1=41.204
A2=55.000
D3=73.416
G3=97.999
}
...which need to be extracted into some structure like this:
#class Preset
{
NSString* label;
double freq;
}
#class Theme
{
NSString* label;
NSMutableArray* presets;
}
NSMutableArray* themes;
How do I write my file using JSON? ( I would like to create a minimum of typing on the part of the user -- how succinct can I get it? Could someone give me an example for the first theme? )
And how do I parse it into the structures using https://github.com/johnezang/JSONKit?
Here's a valid JSON example based on your thoughts:
[
{
"name": "Guitar Standard Tuning",
"comment": "EADGBE using 12-TET tuning",
"presets": {
"E2": "82.41",
"A2": "110.00",
"D3": "146.83",
"G3": "196.00",
"B3": "246.94",
"E4": "329.63"
}
},
{
"name": "Bass Guitar Standard Tuning",
"comment": "EADG using 12-TET tuning",
"presets": {
"E1": "41.204",
"A1": "55.000",
"D2": "73.416",
"G2": "97.999"
}
}
]
Read a file and parse using JSONKit:
NSData* jsonData = [NSData dataWithContentsOfFile: path];
JSONDecoder* decoder = [[JSONDecoder alloc]
initWithParseOptions:JKParseOptionNone];
NSArray* json = [decoder objectWithData:jsonData];
After that, you'll have to iterate over the json variable using a for loop.
Using the parser in your question and assuming you have Simeon's string in an NSString variable. Here's how to parse it:
#import "JSONKit.h"
id parsedJSON = [myJSONString objectFromJSONString];
That will give you a hierarchy of arrays and dictionaries that you can walk to get your Preset and Theme objects. In the above case, you would get an array with two dictionaries each with a name, comment and presets key. The first two will have NSString values and the third (presets) will have a dictionary as it's value with the note name as keys and the frequencies as values (as NSString objects).