Recent Entries 10
- principle minor 112d agoVS 2015 std::char_traits<char16_t> operationsAt my workplace, we changed string type (which holds internationalized characters) for from `std::wstring` to `std::u16string` after VS 2015(Update 3) compiler upgrade. Due to this, we are seeing loads of performance regressions such as this. The profiler analysis reveals that `std::u16string`'s `std::char_traits` operations such as `copy`, `compare`, `find` and `assign` are the most hit and are taking longer than `std::wstring`'s `std::char_traits` counterparts. These `std::char_traits` operations are written in terms of `std::wmem*` and `std::char_traits` operations are written in terms of `for loops`. If we change these traits operations for `char16_t` type (or `std::u16string`) to use our own customized traits, we are seeing performance improvements with performance comparable to `std::wstring`. We are planning to write our own custom traits (until MS fixes it for next version of VS) as follows ``` struct string_custom_traits : public std::char_traits { static const char16_t * copy(char16_t* dest, const char16_t* src, size_t count) { return (count == 0 ? src : (char16_t*)std::memcpy(dest, src, count * sizeof(char16_t))); } }; ``` Would that be OK? Are there any problems with this approach ?
- snippet minor 112d agoPHP function to convert a Portuguese word from plural to singularI know, this sounds really difficult, but it is really easy. I needed to convert a single Portuguese word in the plural into singular. I know there's a right name for that, but it is escaping me. The rules are simple, and will compile them from http://www.easyportuguese.com/portuguese-lessons/plural/ (but applying in reverse): - If the word ends in a vowel, remove the `s` at the end - Words ending in `ões`, `ães` and `ãos` should end with `ão` - Words ending in `is`, remove the `is` and add `l` to the end Special case: accents should be removed, if needed. The only cases I saw were `anéis` and `pastéis`, which have to be `anel` and `papel`. - Words ending in `ns` get it replaced with `m` - Words ending with `[rsz]es` should lose the `es` Special case: words ending in `eses` need the first `e` replaced with `ê`, like in `meses => mês` - Some words are always used in the plural, like `óculos`, `parabéns` and `férias`. Below, here's the code: ``` function plural_to_singular($string) { if(preg_match('/^(?:[oó]culos|parab[eé]ns|f[eé]rias)$/iu', $string)) { return $string; } $regexes = array( '[õã]es' => 'ão', '[áó].*eis' => 'el', '[eé]is' => 'el', '([^eé])is' => '$1l', 'ns' => 'm', 'eses' => 'ês', '([rzs])es' => '$1', 's' => '' ); foreach($regexes as $fragment => $replace) { $regex = '/' . $fragment . '$/ui'; if(preg_match($regex, $string)) { return preg_replace($regex, $replace, $string); } } return $string; } ``` You can try it on http://sandbox.onlinephpfunctions.com/code/7947a0efd16f361e89491e4a64f71b578d2278df with some testcases In your opinion, what can I improve? Is there any obvious butchering or performance killer?
- snippet minor 112d agoConvert an amount to Indian NotationI need to convert an amount to an Indian currency format: ``` import decimal def currencyInIndiaFormat(n): d = decimal.Decimal(str(n)) if d.as_tuple().exponent =0: if flag==0: res = res + s[i] if s[i]=='.': flag = 1 elif flag==1: k = k + 1 res = res + s[i] if k==3 and i-1>=0: res = res + ',' flag = 2 k = 0 else: k = k + 1 res = res + s[i] if k==2 and i-1>=0: res = res + ',' flag = 2 k = 0 i = i - 1 return res[::-1] def main(): n = 100.52 print "INR " + currencyInIndiaFormat(n) # INR 100.52 n = 1000.108 print "INR " + currencyInIndiaFormat(n) # INR 1,000.108 n = 1200000 print "INR " + currencyInIndiaFormat(n) # INR 12,00,000.00 main() ``` Is there a way to make my `currencyInIndiaFormat` function shorter, more concise and clean? Is there a better way to write my `currencyInIndiaFormat` function? Indian Currency Format: For example, numbers here are represented as: ``` 1 10 100 1,000 10,000 1,00,000 10,00,000 1,00,00,000 10,00,00,000 ``` Refer: Indian Numbering System
- debug minor 112d agoDual-language beginner math solver program in C++I've written a program that solves questions of: - Addition - Finding the hypotenuse of a triangle - Checking if the triangle has a right-angle or not I've also written it to be viewed in English or French. There's a few errors regarding `int` and `while` but it still works all the same. In case of any exception, I just terminate the program altogether. Please give your opinions and some advice. ``` #include #include #include #include using namespace std; int language; void output(string en, string fr) { if (language == 1) cout > a; intcheck(a); output("Enter the second number: ", "\nEntrez le second nombre : "); cin >> b; intcheck(b); cout > a; intcheck(a); output("Enter the second length: ", "Entrez la seconde longueur : "); cin >> b; intcheck(b); cout > a; intcheck(a); output("Enter the second length : ", "Entrez la deuxieme longueur : "); cin >> b; intcheck(b); output("Enter the third length : ", "Entrez la troisieme longueur : "); cin >> c; intcheck(c); if (a b && a > c) { // a is the largest side lrgst = a; l1 = b; l2 = c; } else if (b > a && b > c) { // b is the largest side lrgst = b; l1 = a; l2 = c; } else if (c > a && c > b) { // c is the largest side lrgst = c; l1 = a; l2 = b; } else { // a = b = c output("It's an equilateral triangle.\n", "\nC'est un triangle equilateral.\n"); return; } } else { output("\nIt's not a triangle!", "\nCe n'est pas un triangle !\n"); return; } cout > language; intcheck(language); if (language == 1 || 2) { cout > input; if (input == "1") { addition(); } else if (input == "2") { hypotenuse(); }
- pattern minor 112d agoDescribing a date interval as text``` public String getDatePeriodtext(boolean userCanJoinAndLeave, Date startDate, Date endDate) { String text; if (!userCanJoinAndLeave) { text = getText(getLocale(), "no"); } else if (startDate == null && endDate == null) { text = getText(getLocale(), "continuous"); } else if (startDate == null && endDate != null) { text = getText(getLocale(), "to") + " " + formatDate(endDate); } else if (endDate == null) { text = getText(getLocale(), "from") + " " + formatDate(startDate); } else { text = formatDate(startDate) + " " + getText(getLocale(), "to") + " " + formatDate(endDate); } return text; } ``` Some scenarios: - `userCanJoinAndLeave = false` ==> No - `startDate = null` and `endDate` = null ==> Continuous - `startDate = 2016-10-31` and `endDate = null` ==> from 2016-10-31 - `startDate = null` and `endDate = 2016-11-01` ==> to 2016-11-01 - `startDate = 2016-10-31` and `endDate = 2016-11-01` ==> 2016-10-31 to 2016-11-01
- pattern minor 112d agoUsing a MutationObserver to reformat numbers in the user's localeI mostly just want to make sure I've understood the specs correctly with this code, but here goes: ``` var nums = document.getElementsByTagName('x-number'); var observer = new MutationObserver(replaceNumerics); var config = { childList: true, subtree: true }; observer.observe(document.body, config); replaceNumerics(); // initial load function replaceNumerics() { var l = nums.length, i, span; for( i=l-1; i>=0; i--) { // node list is live so iterate backwards span = document.createElement('span'); span.classList.add("x-number"); span.textContent = parseFloat(nums[i].textContent).toLocaleString(); nums[i].parentNode.replaceChild(span,nums[i]); } } ``` The idea is to have a custom `` tag that contains... a number, obviously. JavaScript will detect these tags, parse out the number, then render it according to the user's locale. I'm planning to do a similar thing for dates, which will be especially useful since `` already uses the user's locale. My biggest concern is I think this will result in an infinite loop, as the `replaceChild` call will fire the `MutationObserver` again... but if I understand the spec correctly, this second firing will only happen if and when all `` elements have been replaced (as opposed to the earlier `DOMSubtreeModified` event which would fire immediately), at which point there would be no more `` elements to replace and the loop would end. Honestly this is all very unfamiliar territory to me, but I believe this should work fine... But I figured I'd subject it to public opinion before going any further with it.
- pattern minor 112d agoFighting f̶i̶r̶e̶ regex with f̶i̶r̶e̶ regexSo someone requested a Regex Builder / Assistant for Rubberduck and since my CS class had been covering the topic only recently I was thinking to myself: "This sounds interesting, you should do this". Long story short, a day of designing and a weekend of implementation (and some more polishing) as well as a few reviews later Rubberduck has a fully working Regex Assistant (which even supports i18n). It can be given a VBA Regular Expression pattern and tells you what it does in a manner similar to other well-known assistants (regex101, expresso, ...) This means it can parse a given syntactically correct Regex and recognize the separate Atoms and Quantifiers. It analyzes said Atoms and builds a structure that allows displaying useful information about the pattern. This is accomplished by parsing the expression into a Tree-Structure. Any Regular Expression is built by either the smallest possible unit you have (an Atom) or other regular expressions. This definition allows us to "abuse" the syntax into building our Design. We basically need to handle two (well three) things to represent any arbitrary Regular Expression. - Atoms - Regular Expressions - Quantifiers to be fully correct, Quantifiers actually belong in cahoots with Atoms, but they're.. different, so we'll treat them differently. This sets the stage for our "data holders": Atom.cs ``` using Rubberduck.RegexAssistant.i18n; using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Rubberduck.RegexAssistant { public interface IAtom : IDescribable { string Specifier { get; } } internal class CharacterClass : IAtom { public static readonly string Pattern = @"(?.*?)(? _characterSpecifiers; public IList CharacterSpecifiers { get { return _characterSpecifiers; } } private readonly string _specifier; public CharacterClass(string specifier) { Match m = Matcher.Match(specifier);
- snippet minor 112d agoConvert accented character to user nameI am using the below function for converting the accented character to a standard ASCII user name. ``` function transliterateString($txt) { $transliterationTable = array('á' => 'a', 'Á' => 'A', 'à' => 'a', 'À' => 'A', 'ă' => 'a', 'Ă' => 'A', 'â' => 'a', 'Â' => 'A', 'å' => 'a', 'Å' => 'A', 'ã' => 'a', 'Ã' => 'A', 'ą' => 'a', 'Ą' => 'A', 'ā' => 'a', 'Ā' => 'A', 'ä' => 'ae', 'Ä' => 'AE', 'æ' => 'ae', 'Æ' => 'AE', 'ḃ' => 'b', 'Ḃ' => 'B', 'ć' => 'c', 'Ć' => 'C', 'ĉ' => 'c', 'Ĉ' => 'C', 'č' => 'c', 'Č' => 'C', 'ċ' => 'c', 'Ċ' => 'C', 'ç' => 'c', 'Ç' => 'C', 'ď' => 'd', 'Ď' => 'D', 'ḋ' => 'd', 'Ḋ' => 'D', 'đ' => 'd', 'Đ' => 'D', 'ð' => 'dh', 'Ð' => 'Dh', 'é' => 'e', 'É' => 'E', 'è' => 'e', 'È' => 'E', 'ĕ' => 'e', 'Ĕ' => 'E', 'ê' => 'e', 'Ê' => 'E', 'ě' => 'e', 'Ě' => 'E', 'ë' => 'e', 'Ë' => 'E', 'ė' => 'e', 'Ė' => 'E', 'ę' => 'e', 'Ę' => 'E', 'ē' => 'e', 'Ē' => 'E', 'ḟ' => 'f', 'Ḟ' => 'F', 'ƒ' => 'f', 'Ƒ' => 'F', 'ğ' => 'g', 'Ğ' => 'G', 'ĝ' => 'g', 'Ĝ' => 'G', 'ġ' => 'g', 'Ġ' => 'G', 'ģ' => 'g', 'Ģ' => 'G', 'ĥ' => 'h', 'Ĥ' => 'H', 'ħ' => 'h', 'Ħ' => 'H', 'í' => 'i', 'Í' => 'I', 'ì' => 'i', 'Ì' => 'I', 'î' => 'i', 'Î' => 'I', 'ï' => 'i', 'Ï' => 'I', 'ĩ' => 'i', 'Ĩ' => 'I', 'į' => 'i', 'Į' => 'I', 'ī' => 'i', 'Ī' => 'I', 'ĵ' => 'j', 'Ĵ' => 'J', 'ķ' => 'k', 'Ķ' => 'K', 'ĺ' => 'l', 'Ĺ' => 'L', 'ľ' => 'l', 'Ľ' => 'L', 'ļ' => 'l', 'Ļ' => 'L', 'ł' => 'l', 'Ł' => 'L', 'ṁ' => 'm', 'Ṁ' => 'M', 'ń' => 'n', 'Ń' => 'N', 'ň' => 'n', 'Ň' => 'N', 'ñ' => 'n', 'Ñ' => 'N', 'ņ' => 'n', 'Ņ' => 'N', 'ó' => 'o', 'Ó' => 'O', 'ò' => 'o', 'Ò' => 'O', 'ô' => 'o', 'Ô' => 'O', 'ő' => 'o', 'Ő' => 'O', 'õ' => 'o', 'Õ' => 'O', 'ø' => 'oe', 'Ø' => 'OE', 'ō' => 'o', 'Ō' => 'O', 'ơ' => 'o', 'Ơ' => 'O', 'ö' => 'oe', 'Ö' => 'OE', 'ṗ' => 'p', 'Ṗ' => 'P', 'ŕ' => 'r', 'Ŕ' => 'R', 'ř' => 'r', 'Ř' => 'R', 'ŗ' => 'r', 'Ŗ' => 'R', 'ś' => 's', 'Ś' => 'S', 'ŝ' => 's', 'Ŝ' => 'S', 'š' => 's', 'Š' => 'S', 'ṡ' => 's', 'Ṡ' => 'S', 'ş' => 's', 'Ş' => 'S', 'ș' => 's', 'Ș' => 'S', 'ß' => 'SS', 'ť' => 't', 'Ť' => 'T', 'ṫ' =>
- pattern minor 112d agoInteger to roman number converterThis is (yet another) integer to Roman numeral converter. To give it a slightly interesting twist, I've implemented this as a `num_put` facet of a C++ locale, so by creating the right locale, and imbuing a stream to use that locale, all the numbers written to that stream will be written out in Roman numerals (yeah, I know that's probably rarely useful or desirable, but it seemed like an interesting thing to do at the time). Here's the header: ``` #ifndef ROMAN_H_INC_ #define ROMAN_H_INC_ #include #include #include #include template > class roman : public std::num_put { public: typedef charT char_type; typedef OutputIterator iter_type; protected: virtual iter_type do_put(iter_type out, std::ios_base &, char_type, long v) const { return fmt(v, out); } virtual iter_type do_put(iter_type out, std::ios_base &, char_type, long long v) const { return fmt(v, out); } virtual iter_type do_put(iter_type out, std::ios_base &, char_type, unsigned long v) const { return fmt(v, out); } virtual iter_type do_put(iter_type out, std::ios_base &, char_type, unsigned long long v) const { return fmt(v, out); } std::string fmt_internal(unsigned long long value) const { struct conv { int val; std::string rep; }; static const conv table[] = { { 1000, "M" }, { 900, "CM" }, { 500, "D" }, { 400, "CD" }, { 100, "C" }, { 90, "XC" }, { 50, "L" }, { 40, "XL" }, { 10, "X" }, { 9, "IX" }, { 5, "V" }, { 4, "IV" }, { 1, "I" } }; std::string roman; for (auto const &c : table) { while (value >= c.val) { roman += c.rep; value -= c.val; } } return roman; } template Iter fmt(T t, Iter i) const {
- pattern minor 112d agoMultilanguage class that detects and sets languageI have been learning object oriented programming for quite a while. I understand many concepts about it but I quickly realized that I made a big mistake just reading theory and not doing any actual coding . There was no practise at all and when I started to write some code, I felt it was harder to think and come up with great ideas of what exactly my code should do before I blindly go to write some code. I'm trying to improve my multilanguage class and this is how it works: - It first checks if a language from the `lang=` GET parameter is set and if that value exists in possible languages array. I then set that language to the `currentLang` property and cookie to remember that language for a longer time. If I'm getting a language from `$_GET`, then I assume that the user manually switched to another language. - Almost the same check is made in the second `if` statement, but this time checking if `COOKIE['lang']` is set. This condition is needed to check if the language was set previously. - If $_GET['lang'] or $_COOKIE['lang'] is not set then I assume that no language was chosen manually nor last time user visited page, inside that condition I check if current browser language value can be found in possible languages array if so then I set current language from browser language string. If language from browser `HTTP_ACCEPT_LANGUAGE` can't be found then I set current language to 'English' as a default option. ``` class Langs { // for detecting current language public $currentLang = ''; // all possible languages private $allLangs = ['lt', 'en']; public function __construct() { // get first two letters from string $browserLang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); // if language in url is set and if that language value exists in possible languages array and if language file exists if(isset($_GET['lang']) && in_array($_GET['lang'], $this->allLangs) && $this->_langFileExist($_GET['lang'])) {