function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def _check_main_disease(self, cr, uid, ids, context=None): ''' verify there's only one main disease ''' for r in self.browse(cr, uid, ids, context=context): diseases_ids = self.search(cr,uid,[('attentiont_id','=',r.attentiont_id.id),('diseases_type','=','main')]) if len(diseases_ids) > 1: return False return True
hivam/l10n_co_doctor
[ 2, 3, 2, 3, 1403128853 ]
def do_create(self, cr, uid, ids, context=None): holiday_obj = self.pool.get("official.holiday") template_obj = self.pool.get("official.holiday.template") user_obj = self.pool.get("res.users") template_ids = template_obj.search(cr,uid,[("id","in",util.active_ids(context))]) company_id = user_obj.browse(cr, uid, uid, context).company_id.id official_holiday_ids = [] for template_id in template_ids: template = template_obj.browse(cr, uid, template_id) for holiday in template.official_holiday_ids: official_holiday_ids.append(holiday.id) for wizard in self.browse(cr, uid, ids, context=context): if wizard.calendar_ids: for calendar in wizard.calendar_ids: holiday_obj.create_calendar_entries(cr, uid, official_holiday_ids, fiscalyear_id=wizard.fiscalyear_id.id, company_id=company_id, calendar_id=calendar.id,context=context) else: holiday_obj.create_calendar_entries(cr, uid, official_holiday_ids, fiscalyear_id=wizard.fiscalyear_id.id, company_id=company_id, context=context) return { "type" : "ir.actions.act_window_close" }
funkring/fdoo
[ 1, 5, 1, 8, 1400249085 ]
def print_wrapped(text): paras = text.split("\n") for i in paras: print(*cjkwrap.wrap(i), sep="\n")
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def __init__(self, profile): self.profile = profile self.yaml = YAML() self.config = None self.modules: Dict[str, Module] = {}
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def default_config(): # TRANSLATORS: This part of text must be formatted in a monospaced font, and all lines must not exceed the width of a 70-cell-wide terminal. config = _( "# ===================================\n" "# EH Forwarder Bot Configuration File\n" "# ===================================\n" "# \n" "# This file determines what modules, including master channel, slave channels,\n" "# and middlewares, are enabled in this profile.\n" "# \n" "# \n" "# Master Channel\n" "# --------------\n" "# Exactly one instance of a master channel is required for a profile.\n" "# Fill in the module ID and instance ID (if needed) below.\n" ) config += "\nmaster_channel:\n\n" # TRANSLATORS: This part of text must be formatted in a monospaced font, and all lines must not exceed the width of a 70-cell-wide terminal. config += _( "# Slave Channels\n" "# --------------\n" "# \n" "# At least one slave channel is required for a profile.\n" "# Fill in the module ID and instance ID (if needed) of each slave channel\n" "# to be enabled below.\n" ) config += "\nslave_channels: []\n\n" # TRANSLATORS: This part of text must be formatted in a monospaced font, and all lines must not exceed the width of a 70-cell-wide terminal. config += _( "# Middlewares\n" "# -----------\n" "# Middlewares are not required to run an EFB profile. If you are not\n" "# going to use any middleware in this profile, you can safely remove\n" "# this section. Otherwise, please list down the module ID and instance\n" "# ID of each middleware to be enabled below.\n" ) config += "middlewares: []\n" str_io = StringIO(config) str_io.seek(0) return str_io
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def save_config(self): coordinator.profile = self.profile conf_path = utils.get_config_path() if not conf_path.exists(): conf_path.parent.mkdir(parents=True, exist_ok=True) with open(conf_path, 'w') as f: self.yaml.dump(self.config, f)
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def get_master_lists(self): names = [] ids = [] for i in self.modules.values(): if i.type == "master": names.append(i.name) ids.append(i.id) return names, ids
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def split_cid(cid): if "#" in cid: mid, iid = cid.split("#") else: mid = cid iid = None return mid, iid
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def has_wizard(self, cid): mid, _ = self.split_cid(cid) if mid not in self.modules: return False return callable(self.modules[mid].wizard)
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def get_middleware_lists(self): names = [] ids = [] for i in self.modules.values(): if i.type == "middleware": names.append(i.name) ids.append(i.id) return names, ids
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def __init__(self, prompt: str = "", choices: list = [], choices_id: list = [], bullet: str = "●", bullet_color: str = colors.foreground["default"], word_color: str = colors.foreground["default"], word_on_switch: str = colors.REVERSE, background_color: str = colors.background["default"], background_on_switch: str = colors.REVERSE, pad_right=0, indent: int = 0, align=0, margin: int = 0, shift: int = 0): super().__init__(prompt, choices, bullet, bullet_color, word_color, word_on_switch, background_color, background_on_switch, pad_right, indent, align, margin, shift) self.choices_id = choices_id self._key_handler: Dict[int, Callable] = self._key_handler.copy() self._key_handler[NEWLINE_KEY] = self.__class__.accept
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def accept(self, *args): pos = self.pos bullet.utils.moveCursorDown(len(self.choices) - pos) self.pos = 0 return self.choices[pos], self.choices_id[pos]
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def __init__(self, prompt: str = "", choices: list = None, choices_id: list = None, bullet: str = "●", bullet_color: str = colors.foreground["default"], word_color: str = colors.foreground["default"], word_on_switch: str = colors.REVERSE, background_color: str = colors.background["default"], background_on_switch: str = colors.REVERSE, pad_right=0, indent: int = 0, align=0, margin: int = 0, shift: int = 0, required: bool = False): if choices is None: choices = [] if choices_id is None: choices_id = [] prompt += "\n" + _( "[ =: Shift up; -: Shift down; Backspace: Remove ]" ) choices.extend(( _("+ Add"), _("✓ Submit") )) super().__init__(prompt, choices, bullet, bullet_color, word_color, word_on_switch, background_color, background_on_switch, pad_right, indent, align, margin, shift) self.choices_id = choices_id self.choices_id.extend(( "add", "submit" )) self._key_handler: Dict[int, Callable] = self._key_handler.copy() self._key_handler[NEWLINE_KEY] = self.__class__.accept_fork self.required = required
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def shift_up(self): choices = len(self.choices) if self.pos - 1 < 0 or self.pos >= choices - 2: return else: self.choices[self.pos - 1], self.choices[self.pos] = self.choices[self.pos], self.choices[self.pos - 1] bullet.utils.clearLine() old_pos = self.pos self.pos -= 1 self.printBullet(old_pos) bullet.utils.moveCursorUp(1) bullet.utils.clearLine() self.printBullet(self.pos)
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def shift_down(self): choices = len(self.choices) if self.pos >= choices - 3: return else: self.choices[self.pos + 1], self.choices[self.pos] = self.choices[self.pos], self.choices[self.pos + 1] bullet.utils.clearLine() old_pos = self.pos self.pos += 1 self.printBullet(old_pos) bullet.utils.moveCursorDown(1) bullet.utils.clearLine() self.printBullet(self.pos)
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def delete_item(self): choices = len(self.choices) if self.pos >= choices - 2: return self.choices.pop(self.pos) self.choices_id.pop(self.pos) bullet.utils.moveCursorUp(self.pos - 1) bullet.utils.clearConsoleDown(choices) bullet.utils.moveCursorUp(1) for i in range(len(self.choices)): bullet.utils.moveCursorDown(1) self.printBullet(i) bullet.utils.moveCursorUp(1)
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def accept_fork(self): choices = len(self.choices) if self.required and self.pos == choices - 1 and choices <= 2: # Reject empty list return None if self.pos >= choices - 2: # Add / Submit pos = self.pos bullet.utils.moveCursorDown(len(self.choices) - pos) self.pos = 0 return self.choices[:-2], self.choices_id[:-2], self.choices_id[pos] return None
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def build_search_query(query): return "https://google.com/search?q=" + quote(query)
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def choose_master_channel(data: DataModel): channel_names, channel_ids = data.get_master_lists() list_widget = KeyValueBullet(prompt=_("1. Choose master channel"), choices=channel_names, choices_id=channel_ids) default_idx = None default_instance = '' if "master_channel" in data.config and data.config['master_channel']: default_config = data.config['master_channel'].split("#") default_id = default_config[0] if len(default_config) > 1: default_instance = default_config[1] with suppress(ValueError): default_idx = channel_ids.index(default_id) chosen_channel_name, chosen_channel_id = list_widget.launch(default=default_idx) chosen_instance = input(_("Instance name to use with {channel_name}: [{default_instance}]") .format(channel_name=chosen_channel_name, default_instance=default_instance or _("default instance")) + " ").strip() if chosen_instance: chosen_channel_id += "#" + chosen_instance data.config['master_channel'] = chosen_channel_id
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def choose_middlewares(data: DataModel): chosen_middlewares_names, chosen_middlewares_ids = data.get_selected_middleware_lists() widget = ReorderBullet(_("3. Choose middlewares (optional)."), choices=chosen_middlewares_names, choices_id=chosen_middlewares_ids) middlewares_names, middlewares_ids = data.get_middleware_lists() list_widget: Optional[KeyValueBullet] if middlewares_ids: list_widget = KeyValueBullet(prompt=_("Choose a middleware to add."), choices=middlewares_names, choices_id=middlewares_ids) else: list_widget = None while True: print() chosen_middlewares_names, chosen_middlewares_ids, action = widget.launch() if action == 'add': print() if not list_widget: print_wrapped(_("No installed middleware is detected, press ENTER to go back.")) input() else: add_middleware_name, add_middleware_id = list_widget.launch() add_middleware_instance = input(_("Instance name to use with {middleware_name}: [{default_instance}]") .format(middleware_name=add_middleware_name, default_instance=_("default instance")) + " ").strip() if add_middleware_instance: add_middleware_id += "#" + add_middleware_instance display_name = data.get_instance_display_name(add_middleware_id) if add_middleware_id in widget.choices_id: print_wrapped(_("{instance_name} ({instance_id}) is already enabled. " "Please try another one.") .format(instance_name=display_name, instance_id=add_middleware_id)) else: widget.choices.insert(-2, display_name) widget.choices_id.insert(-2, add_middleware_id) else: # action == 'submit' break data.config['middlewares'] = chosen_middlewares_ids
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def main(): parser = argparse.ArgumentParser() parser.add_argument("-p", "--profile", help=_("Choose a profile to start with."), default="default") parser.add_argument("-m", "--module", help=_("Start the wizard of a module manually, skipping " "the framework wizard.")) args = parser.parse_args() data = DataModel(args.profile) data.load_config() if args.module: mid, iid = data.split_cid(args.module) if callable(data.modules[mid].wizard): data.modules[mid].wizard(data.profile, iid) return else: print(_("{module_id} did not register any wizard " "program to start with.").format(module_id=args.module)) exit(1) prerequisite_check() print_wrapped(_("Welcome to EH Forwarder Bot Setup Wizard. This program " "will guide you to finish up the last few steps to " "get EFB ready to use.\n" "\n" "To use this wizard in another supported language, " "please change your system language or modify the " "language environment variable and restart the wizard.")) print() data.profile = input(_("Profile") + f": [{data.profile}] ") or data.profile print() choose_master_channel(data) choose_slave_channels(data) choose_middlewares(data) confirmation(data) print_wrapped(_("Some more advanced settings, such as granulated log control, " "are not included in this wizard. For further details, you may want to " "refer to the documentation.\n\n" "https://ehforwarderbot.readthedocs.io/en/latest/config.html")) print() modules_count = 1 missing_wizards = [] if not data.has_wizard(data.config['master_channel']): missing_wizards.append(data.config['master_channel']) for i in data.config['slave_channels']: modules_count += 1 if not data.has_wizard(i): missing_wizards.append(i) for i in data.config['middlewares']: modules_count += 1 if not data.has_wizard(i): missing_wizards.append(i) if missing_wizards: prompt = ngettext("Note:\n" "The following module does not have a setup wizard. It is probably because " "that it does not need to be set up, or it requires you to set up manually.\n" "Please consult its documentation for further details.\n", "Note:\n" "The following modules do not have a setup wizard. It is probably because " "that they do not need to be set up, or they require you to set up manually.\n" "Please consult their documentations respectively for further details.\n", len(missing_wizards)) print_wrapped(prompt) print() for i in missing_wizards: print_wrapped("- " + data.get_instance_display_name(i) + " (" + i + ")") print() if len(missing_wizards) == modules_count: print_wrapped(_("Congratulations! You have finished setting up EFB " "framework for the chosen profile. " "You may now continue to configure modules you have " "enabled manually, if necessary.")) exit(0) else: print_wrapped(_("We will now guide you to set up some modules you " "have enabled. " "But you may still need to configure other modules " "manually if necessary.")) else: print_wrapped("We will now guide you to set up modules you have enabled, " "each at a time.") modules = [data.config['master_channel']] modules.extend(data.config['slave_channels']) if 'middlewares' in data.config: modules.extend(data.config['middlewares']) for i in modules: mid, iid = data.split_cid(i) if mid in data.modules and callable(data.modules[mid].wizard): print(_("Press ENTER/RETURN to start setting up {0}.").format(i)) input() data.modules[mid].wizard(data.profile, iid) print() print_wrapped(_("Congratulations! You have now finished all wizard-enabled " "modules. If you did not configure some modules enabled, " "you might need to configure them manually."))
blueset/ehForwarderBot
[ 2891, 274, 2891, 9, 1464585956 ]
def __str__(self): """ Return a string that can be used as a command line argument to nose. """ return "%s:%s.%s" % (inspect.getfile(self.__class__), self.__class__.__name__, self._testMethodName)
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def _enter_atomics(cls): # Prevent rollbacks. pass
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def _rollback_atomics(cls, atomics): # Prevent rollbacks. pass
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def setUpClass(self): super().setUpClass() self.runner = django.test.runner.DiscoverRunner(interactive=False) django.test.utils.setup_test_environment() self.old_config = self.runner.setup_databases() self.db = Db()
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def tearDownClass(self): if 'KEEP_DATA' in os.environ: print("\nkeeping test database: %r." % self.db.db_name, file=sys.stderr) else: self.db.delete_all() self.runner.teardown_databases(self.old_config) django.test.utils.teardown_test_environment() super().tearDownClass()
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def load(self): self.cpp = sc2.RankingData(self.db.db_name, Enums.INFO) self.cpp.load(self.db.ranking.id)
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def save_to_ranking(self): self.cpp.save_data(self.db.ranking.id, self.db.ranking.season_id, to_unix(utcnow()))
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def date(self, **kwargs): return self.today + timedelta(**kwargs)
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def datetime(self, **kwargs): return self.now + timedelta(**kwargs)
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def unix_time(self, **kwargs): return to_unix(self.now + timedelta(**kwargs))
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def setUp(self): super().setUp() self.bnet = BnetClient()
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def mock_current_season(self, status=200, season_id=None, start_time=None, fetch_time=None): self.bnet.fetch_current_season = \ Mock(return_value=SeasonResponse(status, ApiSeason({'seasonId': season_id or self.db.season.id, 'startDate': to_unix(start_time or utcnow())}, 'http://fake-url'), fetch_time or utcnow(), 0))
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def mock_fetch_ladder(self, status=200, fetch_time=None, members=None, **kwargs): self.bnet.fetch_ladder = \ Mock(return_value=LadderResponse(status, gen_api_ladder(members, **kwargs), fetch_time or utcnow(), 0))
andersroos/rankedftw
[ 61, 6, 61, 14, 1480368416 ]
def basename(value): return os.path.basename(value)
troeger/opensubmit
[ 30, 18, 30, 45, 1411388038 ]
def replace_macros(value, user_dict): return value.replace("#FIRSTNAME#", user_dict['first_name'].strip()) \ .replace("#LASTNAME#", user_dict['last_name'].strip())
troeger/opensubmit
[ 30, 18, 30, 45, 1411388038 ]
def state_label_css(subm): green_label = "badge label label-success" red_label = "badge label label-important" grey_label = "badge label label-info" # We expect a submission as input if subm.is_closed() and subm.grading: if subm.grading.means_passed: return green_label else: return red_label if subm.state in [subm.SUBMITTED_TESTED, subm.SUBMITTED, subm.TEST_FULL_PENDING, subm.GRADED, subm.TEST_FULL_FAILED]: return green_label if subm.state == subm.TEST_VALIDITY_FAILED: return red_label return grey_label
troeger/opensubmit
[ 30, 18, 30, 45, 1411388038 ]
def setting(name): return getattr(settings, name, "")
troeger/opensubmit
[ 30, 18, 30, 45, 1411388038 ]
def details_table(submission): return {'submission': submission}
troeger/opensubmit
[ 30, 18, 30, 45, 1411388038 ]
def deadline_timeout(assignment): return {'assignment': assignment, 'show_timeout': True}
troeger/opensubmit
[ 30, 18, 30, 45, 1411388038 ]
def deadline(assignment): return {'assignment': assignment, 'show_timeout': False}
troeger/opensubmit
[ 30, 18, 30, 45, 1411388038 ]
def get_main_user(): """Return the only user remaining in the DB""" return User.objects.first()
lutris/website
[ 107, 124, 107, 33, 1385593889 ]
def delete_tokens(): """Remove all auth tokens (OpenID, DRF, ...)""" res = UserOpenID.objects.all().delete() print("Deleted %s openids" % res[0]) res = Token.objects.all().delete() print("Deleted %s tokens" % res[0]) res = LogEntry.objects.all().delete() print("Deleted %s log entries" % res[0])
lutris/website
[ 107, 124, 107, 33, 1385593889 ]
def main(argv): parser = _stbt.core.argparser() parser.prog = 'stbt run' parser.description = 'Run an stb-tester test script' parser.add_argument( '--cache', default=imgproc_cache.default_filename, help="Path for image-processing cache (default: %(default)s") parser.add_argument( '--save-screenshot', default='on-failure', choices=['always', 'on-failure', 'never'], help="Save a screenshot at the end of the test to screenshot.png") parser.add_argument( '--save-thumbnail', default='never', choices=['always', 'on-failure', 'never'], help="Save a thumbnail at the end of the test to thumbnail.jpg") parser.add_argument( 'script', metavar='FILE[::TESTCASE]', help=( "The python test script to run. Optionally specify a python " "function name to run that function; otherwise only the script's " "top-level will be executed.")) parser.add_argument( 'args', nargs=argparse.REMAINDER, metavar='ARG', help='Additional arguments passed on to the test script (in sys.argv)') args = parser.parse_args(argv[1:]) debug("Arguments:\n" + "\n".join([ "%s: %s" % (k, v) for k, v in args.__dict__.items()])) dut = _stbt.core.new_device_under_test_from_config(args) with sane_unicode_and_exception_handling(args.script), \ video(args, dut), \ imgproc_cache.setup_cache(filename=args.cache): test_function = load_test_function(args.script, args.args) test_function.call()
stb-tester/stb-tester
[ 171, 100, 171, 34, 1340284288 ]
def get_submit_string(self,time_limit,duration): """ Функция генерирует строку для submit задачи в очередь slurm """ s=list() s.append("sbatch") # # Uncomment for debug slurm # #s.append("-vv") s.append("--account=%s" % self.task_class) s.append("--comment=\"Pseudo cluster emulating task\"") s.append("--job-name=\"pseudo_cluster|%s|%s\"" % (self.job_id, self.job_name)) try: limit=self.other["memory_limit"] except KeyError: limit="0" if int(limit) > 0: s.append("--mem=%d" % int(limit)) s.append("--ntasks=%d" % self.required_cpus) s.append("--partition=%s" % self.partition) if self.priority !=0: s.append("--priority=%d" % self.priority)
pseudo-cluster/pseudo-cluster
[ 1, 2, 1, 2, 1414075320 ]
def get_cancel_string(self): return [ "scancel" , str(self.actual_task_id) ]
pseudo-cluster/pseudo-cluster
[ 1, 2, 1, 2, 1414075320 ]
def main(argv=None): """ То, с чего начинается программа """ if argv == None: argv=sys.argv gettext.install('pseudo-cluster')
pseudo-cluster/pseudo-cluster
[ 1, 2, 1, 2, 1414075320 ]
def __init__(self, config, logger, readq): super(MapReduce, self).__init__(config, logger, readq) self.port = self.get_config('port', 8080) self.host = self.get_config('host', "localhost") self.http_prefix = 'http://%s:%s' % (self.host, self.port)
wangy1931/tcollector
[ 1, 2, 1, 3, 1439667326 ]
def _get_running_app_ids(self): try: running_apps = {} metrics_json = self.request("/%s?%s" % (REST_API['YARN_APPS_PATH'], "states=RUNNING&applicationTypes=MAPREDUCE")) if metrics_json.get('apps'): if metrics_json['apps'].get('app') is not None: for app_json in metrics_json['apps']['app']: app_id = app_json.get('id') tracking_url = app_json.get('trackingUrl') app_name = app_json.get('name') if app_id and tracking_url and app_name: running_apps[app_id] = (app_name, tracking_url) except Exception as e: self._readq.nput("mapreduce.state %s %s" % (int(time.time()), '1')) self.log_exception('exception collecting yarn apps metric for mapreduce \n %s',e) return running_apps
wangy1931/tcollector
[ 1, 2, 1, 3, 1439667326 ]
def _mapreduce_job_counters_metrics(self, running_jobs): ''' Get custom metrics specified for each counter ''' try: for job_id, job_metrics in running_jobs.iteritems(): ts = time.time() job_name = job_metrics['job_name'] if job_name: metrics_json = self.request_url("%s%s" % (job_metrics['tracking_url'],'/counters')) if metrics_json.get('jobCounters'): if metrics_json['jobCounters'].get('counterGroup'): for counter_group in metrics_json['jobCounters']['counterGroup']: group_name = counter_group.get('counterGroupName') if group_name: if counter_group.get('counter'): for counter in counter_group['counter']: counter_name = counter.get('name') for metric in JOB_COUNTER: self._readq.nput('mapreduce.job.counter.%s %d %d app_name=%s user_name=%s job_name=%s counter_name=%s' % (metric, ts, counter[metric], utils.remove_invalid_characters(job_metrics.get('app_name')), utils.remove_invalid_characters(job_metrics.get('user_name')), utils.remove_invalid_characters(job_name), utils.remove_invalid_characters(str(counter_name).lower()))) except Exception as e: self._readq.nput("mapreduce.state %s %s" % (int(time.time()), '1')) self.log_exception('exception collecting mapreduce jobs counter metric \n %s',e)
wangy1931/tcollector
[ 1, 2, 1, 3, 1439667326 ]
def request(self,uri): resp = requests.get('%s%s' % (self.http_prefix, uri)) if resp.status_code != 200: raise HTTPError('%s%s' % (self.http_prefix, uri)) return resp.json()
wangy1931/tcollector
[ 1, 2, 1, 3, 1439667326 ]
def execute(code): ctx = zmq.Context.instance() ctx.setsockopt(zmq.LINGER, 50) repl_in = ctx.socket(zmq.PUSH) repl_in.connect('tcp://127.0.0.1:2000') repl_out = ctx.socket(zmq.PULL) repl_out.connect('tcp://127.0.0.1:2001') with repl_in, repl_out: msg = (b'xcode1', code.encode('utf8')) repl_in.send_multipart(msg) while True: data = repl_out.recv_multipart() msg_type = data[0].decode('ascii') msg_data = data[1].decode('utf8') if msg_type == 'finished': print('--- finished ---') break elif msg_type == 'stdout': print(msg_data, end='') sys.stdout.flush() elif msg_type == 'stderr': print(Fore.RED + msg_data + Fore.RESET, end='', file=sys.stderr) sys.stderr.flush() elif msg_type == 'waiting-input': opts = json.loads(msg_data) if opts['is_password']: t = getpass(prompt='') else: t = input() repl_in.send_multipart([b'input', t.encode('utf8')]) else: print('--- other msg ---') print(msg_type) print(msg_data)
lablup/sorna-repl
[ 26, 13, 26, 92, 1445502133 ]
def x(): raise RuntimeError('asdf')
lablup/sorna-repl
[ 26, 13, 26, 92, 1445502133 ]
def main(): parser = argparse.ArgumentParser() parser.add_argument('program_name') args =parser.parse_args() src = sources[args.program_name] print('Test code:') print(textwrap.indent(src, ' ')) print() print('Execution log:') execute(src)
lablup/sorna-repl
[ 26, 13, 26, 92, 1445502133 ]
def __init__(self, gpio, spi, dc_pin="P9_15", reset_pin="P9_13", buffer_rows=64, buffer_cols=128, rows=32, cols=128): self.gpio = gpio self.spi = spi self.cols = cols self.rows = rows self.buffer_rows = buffer_rows self.mem_bytes = self.buffer_rows * self.cols >> 3 # total bytes in SSD1306 display ram self.dc_pin = dc_pin self.reset_pin = reset_pin self.gpio.setup(self.reset_pin, self.gpio.OUT) self.gpio.output(self.reset_pin, self.gpio.HIGH) self.gpio.setup(self.dc_pin, self.gpio.OUT) self.gpio.output(self.dc_pin, self.gpio.LOW) self.font = gaugette.font5x8.Font5x8 self.col_offset = 0 self.bitmap = self.Bitmap(buffer_cols, buffer_rows) self.flipped = False
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def command(self, *bytes): # already low # self.gpio.output(self.dc_pin, self.gpio.LOW) self.spi.writebytes(list(bytes))
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def begin(self, vcc_state=SWITCH_CAP_VCC): time.sleep(0.001) # 1ms self.reset() self.command(self.DISPLAY_OFF) self.command(self.SET_DISPLAY_CLOCK_DIV, 0x80) # support for 128x32 and 128x64 line models if self.rows == 64: self.command(self.SET_MULTIPLEX, 0x3F) self.command(self.SET_COM_PINS, 0x12) else: self.command(self.SET_MULTIPLEX, 0x1F) self.command(self.SET_COM_PINS, 0x02) self.command(self.SET_DISPLAY_OFFSET, 0x00) self.command(self.SET_START_LINE | 0x00) if vcc_state == self.EXTERNAL_VCC: self.command(self.CHARGE_PUMP, 0x10) else: self.command(self.CHARGE_PUMP, 0x14) self.command(self.SET_MEMORY_MODE, 0x00) self.command(self.SEG_REMAP | 0x01) self.command(self.COM_SCAN_DEC) self.command(self.SET_CONTRAST, 0x8f) if vcc_state == self.EXTERNAL_VCC: self.command(self.SET_PRECHARGE, 0x22) else: self.command(self.SET_PRECHARGE, 0xF1) self.command(self.SET_VCOM_DETECT, 0x40) self.command(self.DISPLAY_ALL_ON_RESUME) self.command(self.NORMAL_DISPLAY) self.command(self.DISPLAY_ON)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def invert_display(self): self.command(self.INVERT_DISPLAY)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def normal_display(self): self.command(self.NORMAL_DISPLAY)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def display(self): self.display_block(self.bitmap, 0, 0, self.cols, self.col_offset)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def display_block(self, bitmap, row, col, col_count, col_offset=0): page_count = bitmap.rows >> 3 page_start = row >> 3 page_end = page_start + page_count - 1 col_start = col col_end = col + col_count - 1 self.command(self.SET_MEMORY_MODE, self.MEMORY_MODE_VERT) self.command(self.SET_PAGE_ADDRESS, page_start, page_end) self.command(self.SET_COL_ADDRESS, col_start, col_end) start = col_offset * page_count length = col_count * page_count self.data(bitmap.data[start:start+length])
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def dump_buffer(self): self.bitmap.dump()
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def draw_text(self, x, y, string): font_bytes = self.font.bytes font_rows = self.font.rows font_cols = self.font.cols for c in string: p = ord(c) * font_cols for col in range(0, font_cols): mask = font_bytes[p] p += 1 for row in range(0, 8): self.draw_pixel(x, y + row, mask & 0x1) mask >>= 1 x += 1
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def clear_block(self, x0, y0, dx, dy): self.bitmap.clear_block(x0, y0, dx, dy)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def text_width(self, string, font): return self.bitmap.text_width(string, font)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def __init__(self, cols, rows): self.rows = rows self.cols = cols self.bytes_per_col = rows >> 3 self.data = [0] * (self.cols * self.bytes_per_col)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def dump(self): for y in range(0, self.rows): mem_row = y >> 3 bit_mask = 1 << (y % 8) line = "" for x in range(0, self.cols): mem_col = x offset = mem_row + (self.rows >> 3) * mem_col if self.data[offset] & bit_mask: line += '*' else: line += ' ' print('|'+line+'|')
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def clear_block(self, x0, y0, dx, dy): for x in range(x0, x0 + dx): for y in range(y0, y0 + dy): self.draw_pixel(x, y, 0)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def text_width(self, string, font): x = 0 prev_char = None for c in string: if c < font.start_char or c > font.end_char: if prev_char != None: x += font.space_width + prev_width + font.gap_width prev_char = None else: pos = ord(c) - ord(font.start_char) (width, offset) = font.descriptors[pos] if prev_char != None: x += font.kerning[prev_char][pos] + font.gap_width prev_char = pos prev_width = width if prev_char != None: x += prev_width return x
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def __init__(self, ssd1306, list, font): self.ssd1306 = ssd1306 self.list = list self.font = font self.position = 0 # row index into list, 0 to len(list) * self.rows - 1 self.offset = 0 # led hardware scroll offset self.pan_row = -1 self.pan_offset = 0 self.pan_direction = 1 self.bitmaps = [] self.rows = ssd1306.rows self.cols = ssd1306.cols self.bufrows = self.rows * 2 downset = (self.rows - font.char_height) >> 1 for text in list: width = ssd1306.cols text_bitmap = ssd1306.Bitmap(width, self.rows) width = text_bitmap.draw_text(0, downset, text, font) if width > 128: text_bitmap = ssd1306.Bitmap(width + 15, self.rows) text_bitmap.draw_text(0, downset, text, font) self.bitmaps.append(text_bitmap) # display the first word in the first position self.ssd1306.display_block(self.bitmaps[0], 0, 0, self.cols)
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def align_offset(self): pos = self.position % self.rows midway = self.rows >> 1 delta = (pos + midway) % self.rows - midway return -delta
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def scroll(self, delta): if delta == 0: return count = len(self.list) step = (delta > 0) - (delta < 0) # step = 1 or -1 for i in range(0, delta, step): if (self.position % self.rows) == 0: n = self.position // self.rows # at even boundary, need to update hidden row m = (n + step + count) % count row = (self.offset + self.rows) % self.bufrows self.ssd1306.display_block(self.bitmaps[m], row, 0, self.cols) if m == self.pan_row: self.pan_offset = 0 self.offset = (self.offset + self.bufrows + step) % self.bufrows self.ssd1306.command(self.ssd1306.SET_START_LINE | self.offset) max_position = count * self.rows self.position = (self.position + max_position + step) % max_position
guyc/py-gaugette
[ 120, 43, 120, 9, 1352169832 ]
def __init__(self, name, experiment, description=''): super(Counters, self).__init__(name, experiment, description) # start with a blank list of counters self.counters = ListProp('counters', experiment, listElementType=Counter, listElementName='counter') self.properties += ['version', 'counters']
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def __init__(self, name, experiment, description=''): super(Counter, self).__init__(name, experiment, description) self.properties += ['counter_source', 'clock_source', 'clock_rate']
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def __init__(self, name, experiment, description=''): super(CounterAnalysis, self).__init__(name, experiment, description) self.meas_analysis_path = 'analysis/counter_data' self.meas_data_path = 'data/counter/data' self.iter_analysis_path = 'shotData' self.properties += ['enable', 'drops', 'bins', 'shots', 'graph_roi','draw_fig','iterationonly']
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def preIteration(self, iterationResults, experimentResults): self.counter_array = [] self.binned_array = None
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def format_data(self, array): """Formats raw 2D counter data into the required 4D format.
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def analyzeMeasurement(self, measurementResults, iterationResults, experimentResults): if self.enable:
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def analyzeIteration(self, iterationResults, experimentResults): if self.enable: # recalculate binned_array to get rid of cut data # iterationResults[self.iter_analysis_path] = self.binned_array meas = map(int, iterationResults['measurements'].keys()) meas.sort() path = 'measurements/{}/' + self.meas_analysis_path try: res = np.array([iterationResults[path.format(m)] for m in meas]) except KeyError: # I was having problem with the file maybe not being ready logger.warning("Issue reading hdf5 file. Waiting then repeating.") time.sleep(0.1) # try again in a little res = [] for m in meas: try: res.append(iterationResults[path.format(m)]) except KeyError: msg = ( "Reading from hdf5 file during measurement `{}`" " failed." ).format(m) logger.exception(msg) res = np.array(res) total_meas = len(self.binned_array) # drop superfluous ROI_columns dimension self.binned_array = res.reshape(res.shape[:4]) logger.info('cut data: {}'.format(total_meas - len(self.binned_array))) iterationResults[self.iter_analysis_path] = self.binned_array if self.iterationonly: self.updateFigure() return
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def updateFigure(self): if self.draw_fig: if self.enable: if not self.update_lock: try: self.update_lock = True
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def intersection(self, A0,A1,m0,m1,s0,s1): return (m1*s0**2-m0*s1**2-np.sqrt(s0**2*s1**2*(m0**2-2*m0*m1+m1**2+2*np.log(A0/A1)*(s1**2-s0**2))))/(s0**2-s1**2)
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def area(self,A0,A1,m0,m1,s0,s1): return np.sqrt(np.pi/2)*(A0*s0+A0*s0*erf(m0/np.sqrt(2)/s0)+A1*s1+A1*s1*erf(m1/np.sqrt(2)/s1))
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def overlap(self,xc,A0,A1,m0,m1,s0,s1): err0=A0*np.sqrt(np.pi/2)*s0*(1-erf((xc-m0)/np.sqrt(2)/s0)) err1=A1*np.sqrt(np.pi/2)*s1*(erf((xc-m1)/np.sqrt(2)/s1)+erf(m1/np.sqrt(2)/s1)) return (err0+err1)/self.area(A0,A1,m0,m1,s0,s1)
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def frac(self, A0,A1,m0,m1,s0,s1): return 1/(1+A0*s0*(1+erf(m0/np.sqrt(2)/s0))/A1/s1/(1+erf(m1/np.sqrt(2)/s1)))
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def dblgauss(self, x,A0,A1,m0,m1,s0,s1): return A0*np.exp(-(x-m0)**2 / (2*s0**2)) + A1*np.exp(-(x-m1)**2 / (2*s1**2))
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def __init__(self, name, experiment, description=''): super(CounterHistogramAnalysis, self).__init__(name, experiment, description) self.properties += ['enable']
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def preExperiment(self, experimentResults): # self.hist_rec = np.recarray(1,) return
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def analyzeMeasurement(self, measurementResults, iterationResults, experimentResults): return
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def analyzeIteration(self, iterationResults, experimentResults): if self.enable: histout = [] # amplitudes, edges # Overlap, fraction, cutoff fitout = np.recarray(2, [('overlap', float), ('fraction', float), ('cutoff', float)]) optout = np.recarray(2, [('A0', float), ('A1', float), ('m0', float), ('m1', float), ('s0', float), ('s1', float)]) shots = iterationResults['shotData'][()] # make shot number the primary axis shots = shots.reshape(-1, *shots.shape[2:]).swapaxes(0, 1) shots = shots[:, :, 0] # pick out first roi only hbins = self.hbins if self.hbins < 0: hbins = np.arange(np.max(shots)+1) for i in range(shots.shape[0]): gmix.fit(np.array([shots[i]]).transpose()) h = np.histogram(shots[i], bins=hbins, normed=True) histout.append((h[1][:-1], h[0])) est = [ gmix.weights_.max()/10, gmix.weights_.min()/10, gmix.means_.min(), gmix.means_.max(), np.sqrt(gmix.means_.min()), np.sqrt(gmix.means_.max()) ] try: popt, pcov = curve_fit(self.dblgauss, h[1][1:], h[0], est) # popt=[A0,A1,m0,m1,s0,s1] : Absolute value popt = np.abs(popt) xc = self.intersection(*popt) if np.isnan(xc): logger.warning('Bad Cut on Shot: {}'.format(i)) fitout[i] = np.nan, np.nan, np.nan optout[i] = popt*np.nan else: fitout[i] = self.overlap(xc, *popt), self.frac(*popt), xc optout[i] = popt except (RuntimeError, RuntimeWarning, TypeError): logger.exception('Bad fit on Shot: {} '.format(i)) fitout[i] = np.nan, np.nan, np.nan optout[i] = np.ones(6)*np.nan iterationResults['analysis/dblGaussPopt'] = optout iterationResults['analysis/dblGaussFit'] = fitout logger.info("histout: {}".format(histout)) iterationResults['analysis/histogram'] = np.array(histout, dtype='uint32') self.updateFigure(iterationResults) return
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def updateFigure(self, iterationResults): if self.draw_fig: if self.enable: if not self.update_lock: try: self.update_lock = True
QuantumQuadrate/CsPyController
[ 3, 2, 3, 24, 1492572590 ]
def importpyqt(): ''' Try to import pyqt, either PyQt4 or PyQt5, but allow it to fail ''' try: from PyQt4 import QtGui as pyqt except: try: from PyQt5 import QtWidgets as pyqt except: pyqt = Exception('QtGui could not be imported') return pyqt
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def plotresults(results, toplot=None, fig=None, figargs=None, **kwargs): ''' Does the hard work for updateplots() for pygui() Keyword arguments if supplied are passed on to figure().
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def pygui(tmpresults, toplot=None, advanced=False, verbose=2, figargs=None, **kwargs): ''' PYGUI
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def manualfit(project=None, parsubset=None, name=-1, ind=0, maxrows=25, verbose=2, advanced=False, figargs=None, **kwargs): ''' Create a GUI for doing manual fitting via the backend. Opens up three windows: results, results selection, and edit boxes.
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def closewindows(): ''' Close all three open windows ''' closegui() panel.close()
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def manualupdate(): ''' Update GUI with new results ''' global results, tmppars, fullkeylist, fullsubkeylist, fulltypelist, fullvallist
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def keeppars(): ''' Little function to reset origpars and update the project ''' global origpars, tmppars, parset origpars = dcp(tmppars) parset.pars = tmppars project.parsets[name].pars = tmppars print('Parameters kept') return None
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def resetpars(): ''' Reset the parameters to the last saved version -- WARNING, doesn't work ''' global origpars, tmppars, parset tmppars = dcp(origpars) parset.pars = tmppars for i in range(nfull): boxes[i].setText(sigfig(fullvallist[i], sigfigs=nsigfigs)) simparslist = parset.interp(start=project.settings.start, end=project.settings.end, dt=project.settings.dt) results = project.runsim(simpars=simparslist) updateplots(tmpresults=results) return None
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def plotpeople(project=None, people=None, tvec=None, ind=None, simind=None, start=2, end=None, pops=None, animate=False, skipempty=True, verbose=2, toplot=None, **kwargs): ''' A function to plot all people as a stacked plot
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]
def plotpars(parslist=None, start=None, end=None, verbose=2, rows=6, cols=5, figsize=(16,12), fontsize=8, die=True, **kwargs): ''' A function to plot all parameters. 'pars' can be an odict or a list of pars odicts.
optimamodel/Optima
[ 7, 1, 7, 8, 1406655820 ]