rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self.assertAlmostEquals(sms_peak.amplitude, simpl_peak.amplitude, places=self.FLOAT_PRECISION) self.assertAlmostEquals(sms_peak.frequency, simpl_peak.frequency, places=self.FLOAT_PRECISION) self.assertAlmostEquals(sms_peak.phase, simpl_peak.phase, places=self.FLOAT_PRECISION) | assert_almost_equals(sms_peak.amplitude, simpl_peak.amplitude, self.FLOAT_PRECISION) assert_almost_equals(sms_peak.frequency, simpl_peak.frequency, self.FLOAT_PRECISION) assert_almost_equals(sms_peak.phase, simpl_peak.phase, self.FLOAT_PRECISION) | def test_peak_detection(self): """test_peak_detection Compare simplsms Peaks with SMS peaks. Exact peak information cannot be retrieved using libsms. Basic peak detection is performed by sms_detectPeaks, but this is called multiple times with different frame sizes by sms_analyze. This peak data cannot be returned from ... |
self.assertEquals(len(sms_partials), len(partials)) | assert len(sms_partials) == len(partials) | def test_partial_tracking(self): """test_partial_tracking Compare pysms Partials with SMS partials.""" audio, sampling_rate = self.get_audio() pysms.sms_init() snd_header = pysms.SMS_SndHeader() # Try to open the input file to fill snd_header if(pysms.sms_openSF(self.input_file, snd_header)): raise NameError("error ope... |
self.assertEquals(sms_partials[i].get_length(), partials[i].get_length()) | assert sms_partials[i].get_length() == partials[i].get_length() | def test_partial_tracking(self): """test_partial_tracking Compare pysms Partials with SMS partials.""" audio, sampling_rate = self.get_audio() pysms.sms_init() snd_header = pysms.SMS_SndHeader() # Try to open the input file to fill snd_header if(pysms.sms_openSF(self.input_file, snd_header)): raise NameError("error ope... |
self.assertAlmostEquals(sms_partials[i].peaks[peak_number].amplitude, partials[i].peaks[peak_number].amplitude, places = self.FLOAT_PRECISION) self.assertAlmostEquals(sms_partials[i].peaks[peak_number].frequency, partials[i].peaks[peak_number].frequency, places = self.FLOAT_PRECISION) self.assertAlmostEquals(sms_partia... | assert_almost_equals(sms_partials[i].peaks[peak_number].amplitude, partials[i].peaks[peak_number].amplitude, self.FLOAT_PRECISION) assert_almost_equals(sms_partials[i].peaks[peak_number].frequency, partials[i].peaks[peak_number].frequency, self.FLOAT_PRECISION) assert_almost_equals(sms_partials[i].peaks[peak_number].ph... | def test_partial_tracking(self): """test_partial_tracking Compare pysms Partials with SMS partials.""" audio, sampling_rate = self.get_audio() pysms.sms_init() snd_header = pysms.SMS_SndHeader() # Try to open the input file to fill snd_header if(pysms.sms_openSF(self.input_file, snd_header)): raise NameError("error ope... |
__file__ + ":TestSimplSMS.test_partial_tracking"] | __file__ + ":TestSimplSMS.test_simplsms_interpolate_frames"] | #def test_residual_synthesis(self): |
p.amplitude = 10**(simplsms_amps[i]/20.0) | p.amplitude = simplsms_amps[i] | def test_peak_detection(self): """test_peak_detection Compare simplsms Peaks with SMS peaks. Exact peak information cannot be retrieved using libsms. Basic peak detection is performed by sms_detectPeaks, but this is called multiple times with different frame sizes by sms_analyze. This peak data cannot be returned from ... |
simpl_residual = res.find_residual(simpl_harmonic, audio[0:simpl_harmonic.size]) | simpl_residual = res.synth(simpl_harmonic, audio[0:simpl_harmonic.size]) | def test_residual_synthesis(self): """test_residual_synthesis Compare pysms residual signal with SMS residual""" audio, sampling_rate = self.get_audio() pysms.sms_init() snd_header = pysms.SMS_SndHeader() # Try to open the input file to fill snd_header if(pysms.sms_openSF(self.input_file, snd_header)): raise NameError(... |
ienv_stats['CACHE_BYTES_INUSE'] = Stat( ['perm'], 'bytes currently allocated in the cache') ienv_stats['CACHE_BYTES_MAX'] = Stat( ['perm'], 'maximum bytes configured for the cache') ienv_stats['CACHE_ALLOC'] = Stat( [], 'pages allocated in the cache') ienv_stats['CACHE_EVICT'] = Stat( [], 'clean pages evicted from the ... | ienv_stats['CACHE_ALLOC'] = Stat([], 'pages allocated in the cache') ienv_stats['CACHE_BYTES_INUSE'] = Stat(['perm'], 'bytes currently allocated in the cache') ienv_stats['CACHE_BYTES_MAX'] = Stat(['perm'], 'maximum bytes configured for the cache') ienv_stats['CACHE_EVICT'] = Stat([], 'clean pages evicted from the cach... | def __init__(self, config, str): self.config = config self.str = str |
idb_dstats['BASE_RECNO'] = Stat( [], 'base record number') idb_dstats['PAGE_COL_INTERNAL'] = Stat( [], 'column-store internal pages') idb_dstats['PAGE_COL_FIXED'] = Stat( [], 'column-store fixed-size leaf pages') idb_dstats['PAGE_COL_VARIABLE'] = Stat( [], 'column-store variable-size leaf pages') idb_dstats['EXTSIZE'] ... | idb_dstats['BASE_RECNO'] = Stat([], 'base record number') idb_dstats['EXTSIZE'] = Stat([], 'database extent size') idb_dstats['FIXED_LEN'] = Stat([], 'database fixed-record size') idb_dstats['FRAGSIZE'] = Stat([], 'database fragment size') idb_dstats['INTLSIZE'] = Stat([], 'internal page size') idb_dstats['ITEM_DATA_OV... | def __init__(self, config, str): self.config = config self.str = str |
ienv_stats['HASH_BUCKETS'] = Stat([], 'hash buckets') | def __init__(self, config, str): self.config = config self.str = str | |
cache_stats['CACHE_EVICT'] = Stat([], 'clean pages evicted from the cache') | cache_stats['CACHE_EVICT'] = Stat([], 'unmodified pages evicted from the cache') cache_stats['CACHE_EVICT_HAZARD'] = Stat([], 'pages not evicted because of a hazard reference') cache_stats['CACHE_EVICT_MODIFIED'] = Stat([], 'modified pages evicted from the cache') | def __init__(self, config, str): self.config = config self.str = str |
cache_stats['CACHE_HAZARD_EVICT'] = Stat([], 'pages not evicted because of a hazard reference') | def __init__(self, config, str): self.config = config self.str = str | |
cache_stats['CACHE_WRITE'] = Stat([], 'pages written from the cache') cache_stats['CACHE_WRITE_EVICT'] = Stat([], 'dirty pages evicted from the cache') | def __init__(self, config, str): self.config = config self.str = str | |
f.write('\t__wt_unlock(ienv->mtx);\n') | f.write('\t__wt_unlock(env, ienv->mtx);\n') | def func_method_getset(a, f): func_method_decl(a, f) handle = a.handle method = a.method config = a.config args = a.args extfunc = config.count('extfunc') # Declarations: # If we don't have an environment handle, acquire one. # If we are hand-coding the routine, we'll need a place to save the # return value. if hand... |
f.write('\t__wt_unlock(ienv->mtx);\n') | f.write('\t__wt_unlock(env, ienv->mtx);\n') | def func_method(a, f): # Write the declaration for this function. func_method_decl(a, f) handle = a.handle method = a.method config = a.config args = a.args colonly = config.count('colonly') # Check row-only databases locking = config.count('ienvlock') # Lock rdonly = config.count('rdonly') # Check read-only databas... |
serial['bt_del'] = Serial( | serial['bt_delete'] = Serial( | def __init__(self, key, op, args): self.key = key self.op = op self.args = args |
['WT_PAGE */page', 'WT_REPL */new']) | ['WT_PAGE */page']) | def __init__(self, key, op, args): self.key = key self.op = op self.args = args |
serial['bt_repl'] = Serial( | serial['bt_replace'] = Serial( | def __init__(self, key, op, args): self.key = key self.op = op self.args = args |
'WT_REPL */repl', | def __init__(self, key, op, args): self.key = key self.op = op self.args = args | |
idb_dstats['PAGE_COL_FIXED'] = Stat([], 'column-store fixed-size leaf pages') | idb_dstats['PAGE_COL_FIX'] = Stat([], 'column-store fixed-size leaf pages') | def __init__(self, config, str): self.config = config self.str = str |
idb_stats['BULK_DUP_DATA_READ'] = Stat([], 'bulk duplicate data pairs read') idb_stats['BULK_HUFFMAN_DATA'] = Stat([], 'bulk insert huffman data compression') idb_stats['BULK_HUFFMAN_KEY'] = Stat([], 'bulk insert huffman key compression') idb_stats['BULK_OVERFLOW_DATA'] = Stat([], 'bulk overflow data items read') idb_s... | idb_stats['DB_CACHE_ALLOC'] = Stat([], 'cache: pages allocated in the cache') | def __init__(self, config, str): self.config = config self.str = str |
'method, setter', | 'method, setter, verify', | def __init__(self, key, config, args, f, on, off): self.key = key self.handle = key.split('.')[0] self.method = key.split('.')[1] self.config = config self.args = args if f: flags[key] = f self.on = on self.off = off |
print >>sys.stderr, '%r' % ((score, display),) | def GetRowScoreAndDisplayValue(self, results): """Get the overall score for this row of results data. | |
score = ua_results.get(test.key).get('score') | test_result = ua_results.get(test.key) score = test_result.get('score') display = test_result.get('display') if params['is_user_test']: display = custom_filters.group_thousands(display) | def FormatStatsDataAsGviz(params, tqx): """Takes the output of GetStats and returns a GViz appropriate response. This makes use of the Python GViz API on Google Code. Copied roughly from: http://code.google.com/p/google-visualization-python/source/browse/trunk/examples/dynamic_example.py Args: params: The dict output f... |
display = ua_results.get(test.key).get('display') if params['is_user_test']: display = custom_filters.group_thousands(display) | def FormatStatsDataAsGviz(params, tqx): """Takes the output of GetStats and returns a GViz appropriate response. This makes use of the Python GViz API on Google Code. Copied roughly from: http://code.google.com/p/google-visualization-python/source/browse/trunk/examples/dynamic_example.py Args: params: The dict output f... | |
score = str(ua_results.get(test_key).get('score')) test_scores.append([test_key, score]) logging.info('TEST_SCORES: %s' % test_scores) | display = str(ua_results.get(test_key).get('display')) test_scores.append([test_key, display]) | def UpdateDatastore(request): """Generic datastore munging routine.""" # query = db.Query(models.user_agent.UserAgent) # query.filter('family =', 'IE') # query.filter('v1 =', '9') # key = request.GET.get('key') # if key: # query.filter('__key__ >', db.Key(key)) # query.order('__key__') # user_agent = query.get() # i... |
output = request.REQUEST.get('o', 'js') if output == 'js': | output = request.REQUEST.get('o', 'html') if output == 'html': ua_parsed = None ua_string = request.GET.get('ua_string', '') if ua_string: ua_parsed = models.user_agent.UserAgent.factory(ua_string) params = { 'ua_string': ua_string, 'ua_parsed': ua_parsed, } return Render(request, 'user_agent.html', params) elif ou... | def UaParser(request): output = request.REQUEST.get('o', 'js') if output == 'js': params = {'mimetype': 'text/javascript'} return Render(request, 'user_agent_js.tpl', params) else: raise NotImplementedError |
current_scores[category] = dict( | current_scores = dict( | def GetStats(request, test_set, output='html', opt_tests=None, use_memcache=True): """Returns the stats table. Args: request: a request object. test_set: a TestSet instance. output: Output type html or pickle or else you get a dict of params. opt_tests: list of tests. use_memcache: Use memcache or not. """ category = ... |
name = 'category-update-%s' % result_parent_key.replace('_', '-') | name = 'category-update-%s' % str(result_parent_key).replace('_', '-') | def ScheduleCategoryUpdate(result_parent_key): """Add a task to update a category's statistics. The task is handled by base.admin.UpdateCategory which then calls UpdateCategory below. """ # Give the task a name to ensure only one task for each ResultParent. name = 'category-update-%s' % result_parent_key.replace('_', ... |
js_document_mode = request.REQUEST.get('doc_mode') | js_document_mode = request.REQUEST.get('js_doc_mode') | def Render(request, template, params={}, category=None): """Wrapper function to render templates with global and category vars.""" params['app_title'] = settings.APP_TITLE params['version_id'] = os.environ['CURRENT_VERSION_ID'] params['build'] = settings.BUILD params['resource_version'] = custom_filters.get_resource_ve... |
ua_parsed = None ua_string = request.GET.get('ua_string', '') if ua_string: ua_parsed = models.user_agent.UserAgent.factory(ua_string) params = { 'ua_string': ua_string, 'ua_parsed': ua_parsed, } | def UaParser(request): output = request.REQUEST.get('o', 'html') # HTML form if output == 'html': ua_parsed = None ua_string = request.GET.get('ua_string', '') if ua_string: ua_parsed = models.user_agent.UserAgent.factory(ua_string) params = { 'ua_string': ua_string, 'ua_parsed': ua_parsed, } return Render(request, 'u... | |
headers = task['headers'] | content_type = dict(task['headers'])['Content-Type'] | def _Dynamic_Add(self, request, response): # TODO(slamm): Handle task errors taskqueue_stub.TaskQueueServiceStub._Dynamic_Add(self, request, response) for queue in self.GetQueues(): queue_name = queue['name'] for task in self.GetTasks(queue_name): headers = task['headers'] c = client.Client() if task['method'] == 'GET'... |
c.get(url, query_data, content_type=headers['Content-Type']) | c.get(url, query_data, content_type=content_type) | def _Dynamic_Add(self, request, response): # TODO(slamm): Handle task errors taskqueue_stub.TaskQueueServiceStub._Dynamic_Add(self, request, response) for queue in self.GetQueues(): queue_name = queue['name'] for task in self.GetTasks(queue_name): headers = task['headers'] c = client.Client() if task['method'] == 'GET'... |
c.post(task['url'], data=body, content_type=task['headers']['Content-Type']) | c.post(task['url'], data=body, content_type=content_type) | def _Dynamic_Add(self, request, response): # TODO(slamm): Handle task errors taskqueue_stub.TaskQueueServiceStub._Dynamic_Add(self, request, response) for queue in self.GetQueues(): queue_name = queue['name'] for task in self.GetTasks(queue_name): headers = task['headers'] c = client.Client() if task['method'] == 'GET'... |
key_prefix = os.path.commonprefix(next_keys) prefix_len = len(key_prefix) params = { 'model': model, 'key_prefix': key_prefix, 'keys': ','.join([key[prefix_len:] for key in next_keys]), } | if len(next_keys) == 1: params = { 'model': model, 'keys': next_keys[0], } else: key_prefix = os.path.commonprefix(next_keys) prefix_len = len(key_prefix) params = { 'model': model, 'key_prefix': key_prefix, 'keys': ','.join([key[prefix_len:] for key in next_keys]), } | def DumpEntities(self, db, model, keys): logging.info('DumpEntities: model=%s, num_entities=%s', model, len(keys)) cursor = db.cursor() index = 0 needed_keys = set(keys) while needed_keys: logging.info('DumpEntities: model=%s, num_needed=%s', model, len(needed_keys)) next_keys = [] for i, key in enumerate(sorted(needed... |
response.write('<html>LOADED <script>top.x_content_type_options_test_fail=true;</script></html>') | def XContentTypeOptionsTest(request): response = HttpResponse() response.write('<html>LOADED <script>top.x_content_type_options_test_fail=true;</script></html>') if 'nosniff' in request.GET: response['X-Content-Type-Options'] = 'nosniff' response['Content-Type'] = 'text/plain' return response | |
return score, 'yo' | return score, score | def GetRowScoreAndDisplayValue(self, results): """Get the overall score for this row of results data. Args: results: A dictionary that looks like: { 'testkey1': {'score': 1-10, 'median': median, 'display': 'celltext'}, 'testkey2': {'score': 1-10, 'median': median, 'display': 'celltext'}, etc... } |
row_data.append(user_agent.lower(), user_agent) | row_data.append((user_agent.lower(), user_agent)) | def FormatStatsDataAsGviz(params, tqx): """Takes the output of GetStats and returns a GViz appropriate response. This makes use of the Python GViz API on Google Code. Copied roughly from: http://code.google.com/p/google-visualization-python/source/browse/trunk/examples/dynamic_example.py Args: params: The dict output f... |
'iCab|NetNewsWire|Iron|Space Bison|Stainless|Orca') | 'iCab|NetNewsWire|Iron|Space Bison|Stainless|Orca|Dolfin') | def Parse(self, user_agent_string): family, v1, v2, v3 = None, None, None, None match = self.user_agent_re.search(user_agent_string) if match: if self.family_replacement: if re.search(r'\$1', self.family_replacement): family = re.sub(r'\$1', match.group(1), self.family_replacement) else: family = self.family_replacemen... |
logging.info('UpdateStatsCache: category=%s, browsers=%s', category, browsers_str) | compressed_browsers_str = request.REQUEST.get('zbrowsers') | def UpdateStatsCache(request): """Load rankers into memcache.""" category = request.REQUEST.get('category') browsers_str = request.REQUEST.get('browsers') logging.info('UpdateStatsCache: category=%s, browsers=%s', category, browsers_str) if not category: logging.info('UpdateStatsCache: Must set category') return http.H... |
logging.info('UpdateStatsCache: Must set browsers.') return http.HttpResponseServerError('Must set "browsers" ' '(comma-separated list).') | logging.info('UpdateStatsCache: Must set "browsers" (or "zbrowsers").') return http.HttpResponseServerError('Must set "browsers" (or "zbrowsers").') | def UpdateStatsCache(request): """Load rankers into memcache.""" category = request.REQUEST.get('category') browsers_str = request.REQUEST.get('browsers') logging.info('UpdateStatsCache: category=%s, browsers=%s', category, browsers_str) if not category: logging.info('UpdateStatsCache: Must set category') return http.H... |
(category, results_str)) | (category, results_str[0:100])) | def Beacon(request, category_id=None): """Records result times in the datastore. This is the handler for after a test is done. ex: /beacon?category=reflow&csrf_token=number&results=tes1=150,test2=300 """ ip = request.META.get('REMOTE_ADDR') ip_hash = hashlib.md5(ip).hexdigest() category = request.REQUEST.get('category'... |
elif output in ['csv', 'gviz', 'json', 'jsonp']: | elif output in ['csv', 'gviz_table', 'json', 'jsonp']: | def GetStats(request, test_set, output='html', opt_tests=None, use_memcache=True): """Returns the stats table. Args: request: a request object. test_set: a TestSet instance. output: Output type html or pickle or else you get a dict of params. opt_tests: list of tests. use_memcache: Use memcache or not. """ category = ... |
def help_page(msg, stats_data): | def help_page(msg): | def help_page(msg, stats_data): return ( '<title>%(msg)s</title>' '<h1>%(msg)s</h1>' '<p><code>%(stats_data)s</code></p>' 'Serve JSON mapping code snippets to results.\n' '<p>The JSON is the intersection of the (key, value) pairs accross all' ' user agents requested, so if Firefox 3 was requested then only' ' key/value... |
'<p><code>%(stats_data)s</code></p>' | def help_page(msg, stats_data): return ( '<title>%(msg)s</title>' '<h1>%(msg)s</h1>' '<p><code>%(stats_data)s</code></p>' 'Serve JSON mapping code snippets to results.\n' '<p>The JSON is the intersection of the (key, value) pairs accross all' ' user agents requested, so if Firefox 3 was requested then only' ' key/value... | |
) % { 'msg': html(msg), 'stats_data': html('%s' % stats_data) } | ) % { 'msg': html(msg) } | def help_page(msg, stats_data): return ( '<title>%(msg)s</title>' '<h1>%(msg)s</h1>' '<p><code>%(stats_data)s</code></p>' 'Serve JSON mapping code snippets to results.\n' '<p>The JSON is the intersection of the (key, value) pairs accross all' ' user agents requested, so if Firefox 3 was requested then only' ' key/value... |
test_set, user_agent_strings, test_keys) | test_set=test_set, browsers=user_agent_strings, test_keys=test_keys) | def help_page(msg, stats_data): return ( '<title>%(msg)s</title>' '<h1>%(msg)s</h1>' '<p><code>%(stats_data)s</code></p>' 'Serve JSON mapping code snippets to results.\n' '<p>The JSON is the intersection of the (key, value) pairs accross all' ' user agents requested, so if Firefox 3 was requested then only' ' key/value... |
def html(text): return re.sub('<', '<', re.sub('>', '>', re.sub('&', '&', text))) | def html(text): return cgi.escape(text, quote='"') | def html(text): return re.sub('<', '<', re.sub('>', '>', re.sub('&', '&', text))) |
if (not results.has_key('passed') or results['passed']['median'] or results['failed']['median'] is None): score = 0 display = '' else: score = str(int(100.0 * results['passed']['median'] / (results['passed']['median'] + results['failed']['median']))) num = round(100.0 * results['passed']['median'] / (results['passed']... | total_score = 0 n_results = 0 display = '' for _, v in results.iteritems(): total_score += float(v['score']) n_results += 1 if not n_results: return 0, '' score = total_score / n_results if score > 75: display = 'Good' elif score > 50: display = 'OK' else: display = 'Meh' print >>sys.stderr, '%r' % ((score, display),) | def GetRowScoreAndDisplayValue(self, results): """Get the overall score for this row of results data. |
return http.HttpResponse(BAD_BEACON_MSG + 'ResultParent') | msg = BAD_BEACON_MSG + 'ResultParent' logging.info(msg) return http.HttpResponse(msg) | def Beacon(request, category_id=None): """Records result times in the datastore. This is the handler for after a test is done. ex: /beacon?category=reflow&csrf_token=number&results=tes1=150,test2=300 """ ip = request.META.get('REMOTE_ADDR') ip_hash = hashlib.md5(ip).hexdigest() category = request.REQUEST.get('category'... |
def XContentTypeOptionsTest(request): response = HttpResponse() response.write('<html>LOADED <script>top.xcontenttype_options_test_fail=true;</script></html>') response['X-CONTENT-TYPE-OPTIONS'] = 'nosniff' response['Content-type'] = 'text' return response | def XContentTypeOptionsTest(request): response = HttpResponse() response.write('<html>LOADED <script>top.xcontenttype_options_test_fail=true;</script></html>') response['X-CONTENT-TYPE-OPTIONS'] = 'nosniff' response['Content-type'] = 'text' return response | |
display_score = 0 for category_test in category_tests: raw_score = raw_scores[category_test.key] if raw_score is None: num_tests -= 1 else: display_score += raw_score | if sorted(raw_scores.keys()) == CATEGORIES: display_score = int(raw_scores[test_key]) else: display_score = 0 for category_test in category_tests: raw_score = raw_scores.get(category_test.key) if raw_score is None: num_tests -= 1 else: display_score += raw_score | def GetTestScoreAndDisplayValue(self, test_key, raw_scores): """Get a normalized score (0 to 100) and a value to output to the display. |
name = 'category-update-%s' % result_parent_key | name = 'category-update-%s' % result_parent_key.replace('_', '-') | def ScheduleCategoryUpdate(result_parent_key): """Add a task to update a category's statistics. The task is handled by base.admin.UpdateCategory which then calls UpdateCategory below. """ name = 'category-update-%s' % result_parent_key # run only once per parent result_parent = ResultParent.get(result_parent_key) tas... |
registry.CommaSeparatedListOfStrings(['newBug', 'newAttach', 'Flag', 'Attachment Flag', 'Resolution', 'Product', 'Component'], | registry.CommaSeparatedListOfStrings(['newBug', 'newAttach', 'Flags', 'Attachment Flags', 'Resolution', 'Product', 'Component'], | def registerBugzilla(name, url=''): if (not re.match('\w+$', name)): s = utils.str.normalizeWhitespace(BugzillaName.__doc__) raise registry.InvalidRegistryValue("%s (%s)" % (s, name)) install = conf.registerGroup(conf.supybot.plugins.Bugzilla.bugzillas, name.lower()) conf.registerGlobalValue(install, 'url', registry.S... |
self.pprint(sorted(item.items())) | self.pprint(undict(item)) | def __iter__(self): for item in self.previous: self.pprint(sorted(item.items())) yield item |
if value in BEAD_LABELS: self.spr.set_label(BEAD_LABELS[value]) else: self.spr.set_label(value) | self.spr.set_label(dec2frac(value)) | def update_label(self): """ Label active beads """ value = self.get_value() if self.state == 1 and value < 10000 and value > 0.05: value = self.get_value() if value in BEAD_LABELS: self.spr.set_label(BEAD_LABELS[value]) else: self.spr.set_label(value) else: self.spr.set_label("") |
if x in BEAD_LABELS: rod_value = BEAD_LABELS[x] else: rod_value = str(x) | rod_value = dec2frac(x) | def _button_release_cb(self, win, event): """ Callback to handle the button releases """ if self.press == None: return True self.press = None # The complexity below is to make the label as simple as possible sum = "" for x in self.mode.get_rod_values(): if x > 0: if x in BEAD_LABELS: rod_value = BEAD_LABELS[x] else: ro... |
self.mode.label(" + ".join([str(x) for x in self.mode.rod_values()])+\ " = "+self.mode.value()) | sum = "" for x in self.mode.get_rod_values(): if x > 0: if x in BEAD_LABELS: rod_value = BEAD_LABELS[x] else: rod_value = str(x) if sum == "": sum = rod_value else: sum += " + %s" % (rod_value) if sum == "": self.mode.label("") else: self.mode.label(sum + " = " + self.mode.value()) | def _button_release_cb(self, win, event): """ Callback to handle the button releases """ if self.press == None: return True self.press = None # might be worth removing 0s and converting decimals to mixed fractions self.mode.label(" + ".join([str(x) for x in self.mode.rod_values()])+\ " = "+self.mode.value()) return Tru... |
def rod_values(self): | def get_rod_values(self): | def rod_values(self): """ Return the sum of the values per rod as an array """ v = [0] * (self.num_rods + 1) |
def rod_values(self): | def value(self, count_beads=False): """ Return a string representing the value of each rod. """ string = '' v = [] for r in range(self.num_rods+1): v.append(0) for i, bead in enumerate(self.beads): count = 0 for r in range(len(self.bead_count)): count += self.bead_count[r] if i < count: break if bead.get_state() == 1... | def rod_values(self): """ Return the sum of the values per rod as an array """ v = [0] * (self.num_rods + 1) |
elif self.metadata['abacus'] == 'hex': | elif self.metadata['abacus'] == 'hexadecimal': | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
def _button_factory(icon_name, tooltip, callback, toolbar): | def _button_factory(icon_name, tooltip, callback, toolbar, accelerator=None): | def _button_factory(icon_name, tooltip, callback, toolbar): """Factory for making toolbar buttons""" my_button = ToolButton( icon_name ) my_button.set_tooltip(tooltip) my_button.props.sensitive = True my_button.connect('clicked', callback) if hasattr(toolbar, 'insert'): # the main toolbar toolbar.insert(my_button, -1) ... |
_abacus_toolbar = gtk.Toolbar() _custom_toolbar = gtk.Toolbar() | abacus_toolbar = gtk.Toolbar() custom_toolbar = gtk.Toolbar() edit_toolbar = gtk.Toolbar() | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_abacus_toolbar_button = ToolbarButton( page=_abacus_toolbar, | abacus_toolbar_button = ToolbarButton( page=abacus_toolbar, | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_abacus_toolbar.show() toolbox.toolbar.insert(_abacus_toolbar_button, -1) _abacus_toolbar_button.show() _custom_toolbar_button = ToolbarButton( page=_custom_toolbar, | abacus_toolbar.show() toolbox.toolbar.insert(abacus_toolbar_button, -1) abacus_toolbar_button.show() custom_toolbar_button = ToolbarButton( page=custom_toolbar, | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_custom_toolbar.show() toolbox.toolbar.insert(_custom_toolbar_button, -1) _custom_toolbar_button.show() | custom_toolbar.show() toolbox.toolbar.insert(custom_toolbar_button, -1) custom_toolbar_button.show() edit_toolbar_button = ToolbarButton(label=_('Edit'), page=edit_toolbar, icon_name='toolbar-edit') edit_toolbar_button.show() toolbox.toolbar.insert(edit_toolbar_button, -1) edit_toolbar_button.show() | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_abacus_toolbar_button.set_expanded(True) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) | |
toolbox.add_toolbar( _('Project'), _abacus_toolbar ) toolbox.add_toolbar( _('Custom'), _custom_toolbar ) self._basic_abacus(_abacus_toolbar) | toolbox.add_toolbar( _('Project'), abacus_toolbar ) toolbox.add_toolbar( _('Custom'), custom_toolbar ) toolbox.add_toolbar(_('Edit'), edit_toolbar) self._basic_abacus(abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._japanese_cb, _abacus_toolbar) | self._japanese_cb, abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._mayan_cb, _abacus_toolbar) | self._mayan_cb, abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._hex_cb, _abacus_toolbar) | self._hex_cb, abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._binary_cb, _abacus_toolbar) | self._binary_cb, abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._russian_cb, _abacus_toolbar) | self._russian_cb, abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._fraction_cb, _abacus_toolbar) | self._fraction_cb, abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._caacupe_cb, _abacus_toolbar) | self._caacupe_cb, abacus_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._cuisenaire_cb, _abacus_toolbar) self._rods_label = _label_factory(_("Rods:")+" ", _custom_toolbar) | self._cuisenaire_cb, abacus_toolbar) self._rods_label = _label_factory(_("Rods:")+" ", custom_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_custom_toolbar) self._top_label = _label_factory(_("Top:")+" ", _custom_toolbar) | custom_toolbar) self._top_label = _label_factory(_("Top:")+" ", custom_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_custom_toolbar) | custom_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_custom_toolbar) self._value_label = _label_factory(_("Factor:")+" ", _custom_toolbar) | custom_toolbar) self._value_label = _label_factory(_("Factor:")+" ", custom_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
_custom_toolbar) self._base_label = _label_factory(_("Base:")+" ", _custom_toolbar) | custom_toolbar) self._base_label = _label_factory(_("Base:")+" ", custom_toolbar) | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
self._custom_cb, _custom_toolbar) | self._custom_cb, custom_toolbar) copy = _button_factory('edit-copy', _('Copy'), self._copy_cb, edit_toolbar_button, accelerator='<Ctrl>c') paste = _button_factory('edit-paste', _('Paste'), self._paste_cb, edit_toolbar_button, accelerator='<Ctrl>v') | def __init__(self, handle): """ Initiate activity. """ super(AbacusActivity,self).__init__(handle) |
v[r+1] += 5 | v[r+1] += 5*pow(2,self.num_rods-r-1) | def value(self): """ Return a string representing the value of each rod. """ string = '' v = [] for r in range(self.num_rods+1): # +1 for overflow v.append(0) |
v[r+1] += 1 | v[r+1] += 1*pow(2,self.num_rods-r-1) | def value(self): """ Return a string representing the value of each rod. """ string = '' v = [] for r in range(self.num_rods+1): # +1 for overflow v.append(0) |
v[len(v)-j-1] -= 10 v[len(v)-j-2] += 1 | units = v[len(v)-j-1]%10 tens = v[len(v)-j-1]-units v[len(v)-j-1] = units v[len(v)-j-2] += tens/10 | def value(self): """ Return a string representing the value of each rod. """ string = '' v = [] for r in range(self.num_rods+1): # +1 for overflow v.append(0) |
string += str(j) | string += str(int(j)) | def value(self): """ Return a string representing the value of each rod. """ string = '' v = [] for r in range(self.num_rods+1): # +1 for overflow v.append(0) |
_logger.debug("restoring %s: %s" % (self.name, string)) | _logger.debug("restoring %s: [%s]" % (self.name, string)) | def set_value(self, string): """ Set abacus to value in string """ _logger.debug("restoring %s: %s" % (self.name, string)) # String has two bytes per column. v = [] for r in range(self.num_rods): v.append(0) |
string[2*self.num_rods-i*2-1:2*self.num_rods-i*2]) | string[2*self.num_rods-i*2-2:2*self.num_rods-i*2]) | def set_value(self, string): """ Set abacus to value in string """ _logger.debug("restoring %s: %s" % (self.name, string)) # String has two bytes per column. v = [] for r in range(self.num_rods): v.append(0) |
self.name = "fraction" | self.name = "caacupe" | def set_parameters(self): """ Create an abacus with fractions: 15 by 10 (with 1/2, 1/3. 1/4, 1/5, 1/6, 1/8, 1/9, 1/10, 1/12). """ self.bead_count = (10, 10, 10, 10, 10, 10, 2, 3, 4, 5, 6, 8, 9, 10, 12) self.bead_offset = (2, 2, 2, 2, 2, 2, 6, 5.5, 5, 4.5, 4, 3, 2.5, 2, 1) self.name = "fraction" # "caacupe" self.num_rod... |
print "move up: %d %d" % (dy, bead.state) | def move_bead(self, sprite, dy): """ Move a bead (or beads) up or down a rod from the middle. """ | |
print "move down: %d %d" % (dy, bead.state) | def move_bead(self, sprite, dy): """ Move a bead (or beads) up or down a rod from the middle. """ | |
else: print "no move: %d %d" % (dy, bead.state) return | return def set_rod_value(self, rod, value): """ Move beads on rod r to represent value v (v can go negative)""" bead_index = 0 for r in range(rod): bead_index += self.bead_count[r] for i in range(self.bead_count[rod]): if self.beads[bead_index+i].get_state() == 1: self.beads[bead_index+i].move_down() if self.beads[b... | def move_bead(self, sprite, dy): """ Move a bead (or beads) up or down a rod from the middle. """ |
frame = _svg_header(self.frame_width, self.frame_height, self.abacus.scale) +\ _svg_rect(self.frame_width, self.frame_height, FSTROKE/2, FSTROKE/2, 0, 0, " _svg_rect(self.frame_width-(FSTROKE*2), self.frame_height-(FSTROKE*2), 0, 0, FSTROKE, FSTROKE, " _svg_footer() | _frame = _svg_header(self.frame_width, self.frame_height, self.abacus.scale) +\ _svg_rect(self.frame_width, self.frame_height, FSTROKE/2, FSTROKE/2, 0, 0, " _svg_rect(self.frame_width-(FSTROKE*2), self.frame_height-(FSTROKE*2), 0, 0, FSTROKE, FSTROKE, " _svg_footer() | def create(self): """ Create and position the sprites that compose the abacus """ |
_svg_str_to_pixbuf(frame)) | _svg_str_to_pixbuf(_frame)) | def create(self): """ Create and position the sprites that compose the abacus """ |
bar = _svg_header(self.frame_width-(FSTROKE*2), BHEIGHT, self.abacus.scale) +\ _svg_rect(self.frame_width-(FSTROKE*2), BHEIGHT, 0, 0, 0, 0, " _svg_footer() | _bar = _svg_header(self.frame_width-(FSTROKE*2), BHEIGHT, self.abacus.scale) +\ _svg_rect(self.frame_width-(FSTROKE*2), BHEIGHT, 0, 0, 0, 0, " _svg_footer() | def create(self): """ Create and position the sprites that compose the abacus """ |
_svg_str_to_pixbuf(bar)) | _svg_str_to_pixbuf(_bar)) | def create(self): """ Create and position the sprites that compose the abacus """ |
mark = _svg_header(20, 15, self.abacus.scale) +\ _svg_indicator() +\ _svg_footer() | _mark = _svg_header(20, 15, self.abacus.scale) +\ _svg_indicator() +\ _svg_footer() | def create(self): """ Create and position the sprites that compose the abacus """ |
_svg_str_to_pixbuf(mark)) | _svg_str_to_pixbuf(_mark)) | def create(self): """ Create and position the sprites that compose the abacus """ |
rod_colors = [" " " white = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\ _svg_bead(" _svg_footer() yellow1 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\ _svg_bead(" _svg_footer() yellow2 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\ _svg_bead(" _svg_footer() yellow3 = _svg_header(BWIDTH, BHEIGHT, s... | _white = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\ _svg_bead(" _svg_footer() _yellow1 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\ _svg_bead(" _svg_footer() _yellow2 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale) +\ _svg_bead(" _svg_footer() _yellow3 = _svg_header(BWIDTH, BHEIGHT, self.abacus.scale)... | def draw_rods_and_beads(self, x, y): """ Draw the rods and beads """ rod_colors = ["#006ffe", "#007ee7", "#0082c4", "#0089ab", "#008c8b", "#008e68", "#008e4c", "#008900", "#5e7700", "#787000", "#876a00", "#986200", "#ab5600", "#d60000", "#e30038"] |
rod = _svg_header(10, self.frame_height-(FSTROKE*2), self.abacus.scale) +\ _svg_rect(10, self.frame_height-(FSTROKE*2), 0, 0, 0, 0, rod_colors[i%len(rod_colors)], " _svg_footer() self.rods.append(Sprite(self.abacus.sprites, x+i*dx+ro, y, _svg_str_to_pixbuf(rod))) | _rod = _svg_header(10, self.frame_height-(FSTROKE*2), self.abacus.scale) +\ _svg_rect(10, self.frame_height-(FSTROKE*2), 0, 0, 0, 0, ROD_COLORS[i%len(ROD_COLORS)], " _svg_footer() self.rods.append(Sprite(self.abacus.sprites, x+i*dx+ro, y, _svg_str_to_pixbuf(_rod))) | def draw_rods_and_beads(self, x, y): """ Draw the rods and beads """ rod_colors = ["#006ffe", "#007ee7", "#0082c4", "#0089ab", "#008c8b", "#008e68", "#008e4c", "#008900", "#5e7700", "#787000", "#876a00", "#986200", "#ab5600", "#d60000", "#e30038"] |
self.beads[top_bead_index+i].move((0, | self.beads[top_bead_index+i].move_relative((0, | def set_rod_value(self, r, v): """ Move beads on rod r to represent value v """ bot = v % 5 top = (v-bot)/5 top_bead_index = r*(self.top_beads+self.bot_beads) bot_bead_index = r*(self.top_beads+self.bot_beads)+self.top_beads |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.