Customizing the Cloze Card Type - Having two cards in a card type - anki

I am having two cards in my card type, which I created based on the cloze deletion type, by copying it.
If the position of my card is 1, than as described in the documentation, {{cloze:MyDataField}} works, as I like. But if the position of the card is two, the cloze deletion extension seems to be disabled.
On my card on position two I only need to display the sentence, without the {{c1::word1}}, ...., {{cN::wordN}} tags but with the words, wrapped by those.
Is there maybe a way to create two cards using a close type in my card type's template? Or is there maybe a way to get the plain text of my fields so that I can parse it with JavaScript? Or can I maybe somehow just display the content of the field, ignoring {{c1 expressions, but displaying the content?

It is possible to write an Anki add-on to do this, if you are familiar with Python 2. Cards compiled with a Desktop Anki with this add-on installed will work on AnkiWeb without displaying gibberish. Here is an (untested!) add-on that should register a special fmod that allows you to write {{uncloze:fieldname}} to get the plain text sans {{cn:: and }} marks.
import re
from anki.hooks import addHook
from anki.template.template import Template
"""Adds support for the unclose Moustache tag.
Blame wizzwizz4 if this does / doesn't work.
Modified to work for <anki_version> by <your_name>."""
open_cloze_regex = re.compile(r"{{c\d+::")
def fmod_uncloze(txt, extra, context, tag, tag_name):
field_name = tag_name[8:] # Strip off "uncloze:"
field_content = Template("{{" + field_name + "}}", context).render()
return open_cloze_regex.sub("", field_content).replace("}}", "")
addHook("fmod_uncloze", fmod_uncloze)
Put this in a file in the Anki add-ons directory then restart Anki to install it.
Much of this code is from this answer.

Related

configure sort order in sublimetext3

I know how to sort lines in Sublime (ctrl+p "sort"). The problem is it doesn't sort some characters as I want, namely åäö.
Is there some way to change how sublime orders the text? Perhaps by a specific locale? It would also be interesting to be able to sort V and W as being equal.
Example: I want the following words to be sorted in this order:
bår
bär
bör
but Sublime sorts it like this:
bär
bår
bör
There has been a similar request logged on ST's issue tracker: https://github.com/SublimeTextIssues/Core/issues/1324
One of the ST developers replied:
Sorting in Python 3 uses Unicode code points as the basis for sorting. Sublime Text doesn't know what language your encoding represents, so it doesn't use locale-based sorting rules.
This seems like it is probably best solved by a package dedicated to providing locale-based collation rules.
Using https://packagecontrol.io/packages/PackageResourceViewer, we can see that the case_sensitive_sort method in Packages/Default/sort.py uses Python's built in list.sort method. Typing the following into ST's Python console (View menu -> Show Console), we get the same result as you have shown:
>>> a = ['bår', 'bär', 'bör']
>>> a.sort()
>>> a
['bär', 'bår', 'bör']
So the answer is that there is no setting to configure the sorting behavior, and nor is there likely to be in future. However, according to https://docs.python.org/3/howto/sorting.html#odd-and-ends, it is possible to use a locale-aware sort using locale.strxfrm as a key function.
Let's try. On Windows, I had to use
>>> import locale
>>> locale.setlocale(locale.LC_COLLATE, 'sve')
'Swedish_Sweden.1252'
to get Python to use a Swedish locale - as per https://stackoverflow.com/a/956084/4473405
>>> a.sort(key=locale.strxfrm)
>>> a
['bår', 'bär', 'bör']
Using this knowledge, you might choose to change the case_sensitive_sort method, so that ST's built in sort functionality (Edit menu -> Sort Lines (Case Sensitive)) will use the locale aware sort key. Note that saving the sort.py file opened from PackageResourceViewer will create an override, so that if future builds of ST include changes to sort.py, you won't see them until you delete the override (which you can do by finding the file using the Preferences menu -> Browse Packages -> Default. You can reapply your changes afterwards, if appropriate, using the exact same steps.)
You can also change the case_insensitive_sort method from
txt.sort(key=lambda x: x.lower())
to
txt.sort(key=lambda x: locale.strxfrm(x.lower()))
Note that, if your correct locale isn't picked up automatically (it probably defaults to C), then setting the locale in this (case_sensitive_sort) method isn't recommended, even if, immediately afterwards, you restore it back to what it was beforehand - so use at your own risk.
It is generally a bad idea to call setlocale() in some library routine, since as a side effect it affects the entire program. Saving and restoring it is almost as bad: it is expensive and affects other threads that happen to run before the settings have been restored.
You could instead add the following to the end of the sort.py file:
def plugin_loaded():
import locale
locale.setlocale(locale.LC_COLLATE, '')
which will, when the plugin is loaded, allow Python to infer the locale from your LANG env var, as per https://docs.python.org/3/library/locale.html#locale.setlocale. The advantage being you only set it once, and hopefully won't introduce any problems with other plugin code executing at the same time.
Happy sorting!

Animated icon in email subject

I know about Data URIs in which base64 encoded data can be used inline such as images. Today I received an email actually an spam one in which there was an animated (gif) icon in its subject:
Here is the icon alone:
So the only thing did cross my mind was all about Data URIs and if Gmail allows some sort of emoticons to be inserted in subject. I saw the full detailed version of email and pointed to subject line at the below picture:
So GIF comes from =?UTF-8?B?876Urg==?= encoded string which is similar to Data URI scheme however I couldn't get the icon out of it. Here is element HTML source:
Long story short, there are lots of emoticons from https://mail.google.com/mail/e/XXX where XXX are hexadecimal numbers. They are documented nowhere or I couldn't find it. If that's about Data URI, so how is it possible to include them in Gmail's email subject? (I forwarded that email to a yahoo email account, seeing [?] instead of icon) and if it's not, then how that encoded string is parsed?
#Short description:
They are referred to internally as goomoji, and they appear to be a non-standard UTF-8 extension. When Gmail encounters one of these characters, it is replaced by the corresponding icon. I wasn't able to find any documentation on them, but I was able to reverse engineer the format.
#What are these icons?
Those icons are actually the icons that appear under the "Insert emoticons" panel.
While I don't see the 52E icon in the list, there are several others that follow the same convention.
B0C
4F4
Note that there are also some icons whose names are prefixed, such as gtalk.03C . I was not able to determine if or how these icons can be used in this manner.
#What is this Data URI thing?
It's not actually a Data URI, though it does share some similarities. It's actually a special syntax for encoding non-ASCII characters in email subjects, defined in RFC 2047. Basically, it works like this.
=?charset?encoding?data?=
So, in our example string, we have the following data.
=?UTF-8?B?876Urg==?=
charset = UTF-8
encoding = B (means base64)
data = 876Urg==
#So, how does it work?
We know that somehow, 876Urg== means the icon 52E, but how?
If we base64 decode 876Urg==, we get 0xf3be94ae. This looks like the following in binary:
11110011 10111110 10010100 10101110
These bits are consistent with a 4-byte UTF-8 encoded character.
11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
So the relevant bits are the following.:
011 111110 010100 101110
Or when aligned:
00001111 11100101 00101110
In hexadecimal, these bytes are the following:
FE52E
As you can see, except for the FE prefix which is presumably to distinguished the goomoji icons from other UTF-8 characters, it matches the 52E in the icon URL. Some testing proves that this holds true for other icons.
#Sounds like a lot of work, is there a converter?:
This can of course be scripted. I created the following Python code for my testing. These functions can convert the base64 encoded string to and from the short hex string found in the URL. Note, this code is written for Python 3, and is not Python 2 compatible.
###Conversion functions:
import base64
def goomoji_decode(code):
#Base64 decode.
binary = base64.b64decode(code)
#UTF-8 decode.
decoded = binary.decode('utf8')
#Get the UTF-8 value.
value = ord(decoded)
#Hex encode, trim the 'FE' prefix, and uppercase.
return format(value, 'x')[2:].upper()
def goomoji_encode(code):
#Add the 'FE' prefix and decode.
value = int('FE' + code, 16)
#Convert to UTF-8 character.
encoded = chr(value)
#Encode UTF-8 to binary.
binary = bytearray(encoded, 'utf8')
#Base64 encode return end return a UTF-8 string.
return base64.b64encode(binary).decode('utf-8')
###Examples:
print(goomoji_decode('876Urg=='))
print(goomoji_encode('52E'))
###Output:
52E
876Urg==
And, of course, finding an icon's URL simply requires creating a new draft in Gmail, inserting the icon you want, and using your browser's DOM inspector.
If you use the correct hex code point (e.g. fe4f4 for 'pile of poo') and If it is correctly encoded within the subject line header, let it be base64 (see #AlexanderOMara) or quoted-printable (=?utf-8?Q?=F3=BE=93=B4?=), then Gmail will automatically parse and replace it with the corresponding emoji.
Here's a Gmail emoji list for copying and pasting into subject lines - or email bodies. Animated emojis, which will grab even more attention in the inbox, are placed on a yellow background:
Many thanks to Alexander O'Mara for such a well-researched answer about the goomoji-tagged HTML images!
I just wanted to add three things:
There are still many many emoji (and other Unicode sequences generating pictures) that spammers and other erstwhile marketers are starting to use in email subject lines and that gmail does not convert to HTML images. In some browsers these show up bold and colored, which is almost as bad as animation. Browsers could also choose to animate these, but I don't know if any do. These Unicode sequences get displayed by the browser as Unicode text, so the exact appearance (color or not, animated or not, ...) depends on what text rendering system the browser is using. The appearance of a given Unicode emoji also depends on any Unicode variation selectors and emoji modifiers that appear near it in the Unicode code point sequence. Unlike the image-based emoji spam, these sequences can be copied-and-pasted out of the browser and into other apps as Unicode text.
I hope the many marketers reading this StackOverflow question will just say no. It is a horrible idea to include these sequences in your email subject lines and it will immediately tarnish you and your brand as lowlife spammers. It is not worth the "attention" your email will get.
Of course the first question coming to everyone's mind is: "how do I get rid of these things?" Fortunately there is this open-source Greasemonkey/Tampermonkey/Violentmonkey userscript:
Gmail Subject Line Emoji Roach Motel
This userscript eliminates both HTML-image (thanks to awesome work of Alexander O'Mara) and pure-Unicode types.
For the latter type, the userscript includes a regular expression designed to capture the Unicode sequences likely to be abused by marketers. The regex looks like this in ES6 Javascript (the userscript translates this to widely-supported pre-ES6 regex using the amazing ES6 Regex Transpiler):
var re = /(\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F|[\u{2100}-\u{2BFF}\u{E000}-\u{F8FF}\u{1D000}-\u{1F5FF}\u{1F650}-\u{1FA6F}\u{F0000}-\u{FFFFF}\u{100000}-\u{10FFFF}])\s*/gu
// which includes the Unicode Emoji pattern from
// https://github.com/tc39/proposal-regexp-unicode-property-escapes
// plus also these blocks frequently used for spammy emojis
// (see https://en.wikipedia.org/wiki/Unicode_block ):
// U+2100..U+2BFF Arrows, Dingbats, Box Drawing, ...
// U+E000..U+F8FF Private Use Area (gmail generates them for some emoji)
// U+1D000..U+1F5FF Musical Symbols, Playing Cards (sigh), Pictographs, ...
// U+1F650..U+1FA6F Ornamental Dingbats, Transport and Map symbols, ...
// U+F0000..U+FFFFF Supplementary Private Use Area-A
// U+100000..U+10FFFF Supplementary Private Use Area-B
// plus any space AFTER the discovered emoji spam

ABAP startRFC.exe UTF-8 diacritics text transfer

I have a function module (FM) in SAP and I call it externally using startRFC. The only output of FM is one internal table. This table has only 1 column of type char(100) and I need to get it to text file. StartRFC works well, but if there is diacritics (for example Czech language: ěščřžýáíé) instead of these characters only hashes # appear.
Have someone ever solved similar issue?
If I call the same algorithm manually and write strings on screen in SAP, everything is ok. But startRFC somehow destroys it. The problem may be in the data transfer between SAP and startRFC. But I don't know how this transfer works.
I found a solution but it is terribly slow. It converts string to hexadecimal string using "gcl_conv_to_x->write" and "gcl_conv_to_x->get_buffer" than calls "SCMS_XSTRING_TO_BINARY" and you need a binary table. But it takes 5minutes to do all this stuff. Without this conversion my algorithm takes 15 seconds.
So finally a solution...
You need to create XSTRING variable and fill it with your text. To convert STRING to XSTRING use FM: SCMS_STRING_TO_XSTRING.
Then you will need an internal table with row type BAPICONTEN. It already contains component (column) of type SDOK_SDATX (RAW 1022).
And you just append a new line to this table like this:
data: my_table_row LIKE LINE OF my_table.
my_table_row-line = my_xstring.
APPEND my_table_row INTO my_table.
This table (my_table) can be returned via RFC and will contain Cyrillic, German characters etc..
I am just a beginner, so do not ask me how to create the table, please :)

How can I find an <acronym> tag with watir-webdriver without taking a huge performance hit?

I am using watir-webdriver (0.5.3) in a Cucumber (1.1.9) test. I am attempting to verify the text value of an <acronym> tag. The code is legacy, and there are plans to change it to a <div> or <span> tag, but in the mean time I have to deal with it. I first attempted:
#browser.acronym(:id => /expense_code(.*)/).text
I received the following error:
NoMethodError: undefined method `acronym' for #<Watir::Browser:0x33e9940>
I poked around in the Watir code to see how tag objects were being created, and found that they seem to be dynamically created based on the HTML5 spec, but then I also found a comment in element.rb stating that they are no longer being created from the spec. At any rate, I couldn't see an easy way to inherit a <span> object and call it an <acronym> object. So, I looked into alternatives, and found the element object.
#browser.element(:id => /expense_code(.*)/).text
This code works, but it takes about a minute to traverse my page. I'm stuck with the regex for now, as the tag id is actually dynamically generated and I don't currently have a way to figure out those values. This is what the tag actually looks like:
<acronym class="editable select fillwith:exp_codes default:E100"
title="Expense Code: Expenses" id="expense_code114_582_10777">
E100 </acronym>
I would appreciate any thoughts on how I can improve the performance of my test.
Is that class name predictable? could you construct that from a set part plus the text you are about to validate (it's the same in your example above) and go that way?
acronym = 'E100'
browser.element(:class, 'editable select fillwith:exp_codes default:#{acronym}'.text.should == acronym
Does using XPath to limit the elements to just acronym tags help performance?
#browser.element(:xpath, "//acronym[contains(#id, 'expense_code')]")
UPDATE: As Chuck mentioned, CSS-Selector is also an option:
#browser.element(:css => "acronym[id^=expense_code]")
I was recently stealing logic from Watir 1.6.5 to make custom locators/collections for my page objects and I noticed in the Watir::TaggedElementLocator, it kind of supports any method that the element supports. Noticing in Watir-Webdriver that elements have a tag_name() method, I thought I would try the same and it looks like it works.
So you can use tag_name as a locator by doing:
#browser.element(:tag_name => 'acronym', :id => /expense_code(.*)/).text
I'm not sure what order the locators get run in, so since the regex is expensive, it might be faster to get all the acronym elements and then find the one with the right ID:
#browser.elements(:tag_name, 'acronym').find{ |acronym|
acronym.id =~ /expense_code(.*)/
}.text
While I think it makes the code look better, unfortunately I'm not sure if its any faster. I am guessing the performance of each will depend on the specific page layout being tested.
I'm not sure what the proper etiquette is here, but this is the answer I came up with using Chuck's reply and feedback from jarib in the #watir IRC chat. With all my examples, expense_code = 'E100'.
#browser.element(:tag_name => "acronym",
:class => "default:#{expense_code}").text
The above code works at a very reasonable speed and doesn't require an xpath. It is a shortening of the following code:
#browser.element(:tag_name => "acronym",
:class => "editable select fillwith:exp_codes default:#{expense_code}").text
I learned that I didn't need to pass the whole string. Anything in a class delimited by a space is dealt with gracefully by watir. I adapted that code from this xpath:
#browser.element(:xpath => "//acronym[contains(#class,
\'editable select fillwith:exp_codes default:#{expense_code}\')]").text
The gotcha in that code above was needing to escape out the ' around the class values so that it would evaluate correctly.
Just searching for the class (code below) did not work. I have no idea why. I did notice that it pounded the database with requests. Whatever it was doing, the page didn't like it. Though the reason it was trying multiple times is I slipped a wait_until_present in there.
#browser.element(:class, "editable select fillwith:exp_codes
default:#{expense_code}").text
Thanks for the help. :)

How can I find all R packages that include graphics functions?

I always have difficulty in finding all available alternative ways to produce a specific graph, either one that I have already decided to use (looking for different variations) or one that I have not yet thought of.
The R Graphical Manual site provides a complete list of samples of R's graphics functions, however it's easier for me to search providing a package name (how else -for example- can I get a resultset including superbarplot function, when I want to look for barplots?. Let alone that the superbarplot graph does not appear in the results even if I try searching for it's package: UsingR)
The R-SAS-SPSS Add-on Module Comparison - and especially on topic Graphics, Static in the table provided - gave me the idea that it would be nice to have a place where all relevant packages are listed by topic.
Do you have any idea about something like that?
If you're interested in learning about all the possible graphics you can make, you should learn about the grammar of graphics, and (my) implementation of it in R: ggplot2.
Your question, or the general pattern anyway, was clearly a primary use case for the design of the sos package.
sos actually goes one step further that your question requires by identifying particular functions with packages; in addition, it ranks the results by relevance (by default, you can change the default behavior via the "sortby" parameter, e.g., sortby="Date")
Here's how it works:
most of this package's functionality is exposed via the "findFn" command
for instance, if you want a list of all functions and the parent package related to scatter plots:
findFn("scatter plot", maxPages=2, sortby="TotalScore")
This returns a dataframe formatted as HTML table and delivered in your default browser (if you don't want it to pop-up immediately, then just bind the function call to a variable and then call the variable when you're ready)
The right-most column of the dataframe/HTML page is "Description and Link". Clicking an entry in that column opens another tab in your browser (according to the user-set preferences set in your browser) with the complete R help page for that function.
The results from the function call above show, for instance, that the functions for plotting data in a 'scatter plot' format are found in the following packages:
ade4 (function: scatter)
IDPmisc (functions: ipairs, iplots)
GGally (function: ggally_points)
PerformanceAnalytics (function:
chart.Scatter)
mclust (function: clPairs)
Another example:
findFn("boxplot", maxPages=2, sortby="TotalScore")
identifies these (among others) packages/functions for plotting boxplots:
sfsmisc (function: boxplot.matrix)
aplpack (function: boxplot2D)
NADA (function: boxplot-methods)
StatDA (function: rg.boxplot)
plotrix (function: gap.boxplot)
gplots (function: boxplot.n)
multcompView (function:
multcompBoxplot)
oligo (function: boxplot)
Have you seen the R Graph Gallery ?
Other than that, you may have to index all the source code of CRAN packages to search efficiently...
these are good memory-joggers. I second the ggplot2 recommend, also recommend looking thru CRAN views:
http://cran.r-project.org/web/views/
http://cran.fhcrc.org/web/views/Graphics.html
(this mirror seems faster in west coast US)
http://dataspora.com/archive/2009/seminar/Survey_of_R_Graphics_by_Driscoll_Dataspora_Jun2009.pdf
http://zoonek2.free.fr/UNIX/48_R/04.html
(possibly world's longest webpage)
http://www.stat.auckland.ac.nz/~ihaka/120/lectures.html
Ihaka's lectures notes

Resources