code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def create_key(kwargs=None, call=None): if call != 'function': log.error( 'The create_key function must be called with -f or --function.' ) return False try: result = query( method='account', command='keys', args={'name': kwargs['name'], 'public_key': kwargs['public_key']}, http_method='post' ) except KeyError: log.info('`name` and `public_key` arguments must be specified') return False return result
module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false try_statement block expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end subscript identifier string string_start string_content string_end pair string string_start string_content string_end subscript identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement false return_statement identifier
Upload a public key
def _validate(self): if self._method not in _RANK_METHODS: raise UnknownRankMethod( method=self._method, choices=set(_RANK_METHODS), ) return super(Rank, self)._validate()
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier identifier block raise_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list identifier return_statement call attribute call identifier argument_list identifier identifier identifier argument_list
Verify that the stored rank method is valid.
def run(self): processes = [] progress_queue = ProgressQueue(Queue()) num_chunks = ParallelChunkProcessor.determine_num_chunks(self.config.upload_bytes_per_chunk, self.local_file.size) work_parcels = ParallelChunkProcessor.make_work_parcels(self.config.upload_workers, num_chunks) for (index, num_items) in work_parcels: processes.append(self.make_and_start_process(index, num_items, progress_queue)) wait_for_processes(processes, num_chunks, progress_queue, self.watcher, self.local_file)
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call identifier argument_list call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier for_statement tuple_pattern identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier identifier identifier attribute identifier identifier attribute identifier identifier
Sends contents of a local file to a remote data service.
def save(self, *args, **kwargs): auto_update = kwargs.get('auto_update', True) if auto_update: self.updated = now() if 'auto_update' in kwargs: kwargs.pop('auto_update') super(BaseDate, self).save(*args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end true if_statement identifier block expression_statement assignment attribute identifier identifier call identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier
automatically update updated date field
async def _send_sleep(self, request: Request, stack: Stack): duration = stack.get_layer(lyr.Sleep).duration await sleep(duration)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement await call identifier argument_list identifier
Sleep for the amount of time specified in the Sleep layer
def update(self): pixels = len(self.matrix) for x in range(self.width): for y in range(self.height): pixel = y * self.width * 3 + x * 3 if pixel < pixels: pygame.draw.circle(self.screen, (self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]), (x * self.dotsize + self.dotsize / 2, y * self.dotsize + self.dotsize / 2), self.dotsize / 2, 0)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier call identifier argument_list attribute identifier identifier block for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier binary_operator binary_operator binary_operator identifier attribute identifier identifier integer binary_operator identifier integer if_statement comparison_operator identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier tuple subscript attribute identifier identifier identifier subscript attribute identifier identifier binary_operator identifier integer subscript attribute identifier identifier binary_operator identifier integer tuple binary_operator binary_operator identifier attribute identifier identifier binary_operator attribute identifier identifier integer binary_operator binary_operator identifier attribute identifier identifier binary_operator attribute identifier identifier integer binary_operator attribute identifier identifier integer integer
Generate the output from the matrix.
def recreate(cls, *args, **kwargs): cls.check_arguments(kwargs) first_is_callable = True if any(args) and callable(args[0]) else False signature = cls.default_arguments() allowed_arguments = {k: v for k, v in kwargs.items() if k in signature} if (any(allowed_arguments) or any(args)) and not first_is_callable: if any(args) and not first_is_callable: return cls(args[0], **allowed_arguments) elif any(allowed_arguments): return cls(**allowed_arguments) return cls.instances[-1] if any(cls.instances) else cls()
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier conditional_expression true boolean_operator call identifier argument_list identifier call identifier argument_list subscript identifier integer false expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list if_clause comparison_operator identifier identifier if_statement boolean_operator parenthesized_expression boolean_operator call identifier argument_list identifier call identifier argument_list identifier not_operator identifier block if_statement boolean_operator call identifier argument_list identifier not_operator identifier block return_statement call identifier argument_list subscript identifier integer dictionary_splat identifier elif_clause call identifier argument_list identifier block return_statement call identifier argument_list dictionary_splat identifier return_statement conditional_expression subscript attribute identifier identifier unary_operator integer call identifier argument_list attribute identifier identifier call identifier argument_list
Recreate the class based in your args, multiple uses
def replaceData(self, offset: int, count: int, string: str) -> None: self._replace_data(offset, count, string)
module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block expression_statement call attribute identifier identifier argument_list identifier identifier identifier
Replace data from offset to count by string.
def interpret(self, msg): self.captions = msg.get('captions', '.') for item in msg['slides']: self.add(item)
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier
Create a slide show
def _append_message(self, text, char_format): self._cursor = self._text_edit.textCursor() operations = self._parser.parse_text(FormattedText(text, char_format)) for i, operation in enumerate(operations): try: func = getattr(self, '_%s' % operation.command) except AttributeError: print('command not implemented: %r - %r' % ( operation.command, operation.data)) else: try: func(operation.data) except Exception: _logger().exception('exception while running %r', operation) self._text_edit.repaint()
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end attribute identifier identifier except_clause identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier else_clause block try_statement block expression_statement call identifier argument_list attribute identifier identifier except_clause identifier block expression_statement call attribute call identifier argument_list identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list
Parses text and executes parsed operations.
def make_valid_string(self, string=''): if not self.is_valid_str(string): if string in self.val_map and not self.allow_dups: raise IndexError("Value {} has already been given to the sanitizer".format(string)) internal_name = super(_NameSanitizer, self).make_valid_string() self.val_map[string] = internal_name return internal_name else: if self.map_valid: self.val_map[string] = string return string
module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block if_statement not_operator call attribute identifier identifier argument_list identifier block if_statement boolean_operator comparison_operator identifier attribute identifier identifier not_operator attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier else_clause block if_statement attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement identifier
Inputting a value for the first time
def maybe_start_recording(tokens, index): if _is_begin_quoted_type(tokens[index].type): string_type = _get_string_type_from_token(tokens[index].type) return _MultilineStringRecorder(index, string_type) return None
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list attribute subscript identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute subscript identifier identifier identifier return_statement call identifier argument_list identifier identifier return_statement none
Return a new _MultilineStringRecorder when its time to record.
def display_warning(self, message, short_message, style=wx.OK | wx.ICON_WARNING): dlg = GMD.GenericMessageDialog(self.main_window, message, short_message, style) dlg.ShowModal() dlg.Destroy()
module function_definition identifier parameters identifier identifier identifier default_parameter identifier binary_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list
Displays a warning message
def expand_nested(self, cats): down = '│' right = '└──' def get_children(parent): return [e() for e in parent._entries.values() if e._container == 'catalog'] if len(cats) == 0: return cat = cats[0] old = list(self.options.items()) name = next(k for k, v in old if v == cat) index = next(i for i, (k, v) in enumerate(old) if v == cat) if right in name: prefix = f'{name.split(right)[0]}{down} {right}' else: prefix = right children = get_children(cat) for i, child in enumerate(children): old.insert(index+i+1, (f'{prefix} {child.name}', child)) self.widget.options = dict(old)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end function_definition identifier parameters identifier block return_statement list_comprehension call identifier argument_list for_in_clause identifier call attribute attribute identifier identifier identifier argument_list if_clause comparison_operator attribute identifier identifier string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block return_statement expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call identifier generator_expression identifier for_in_clause pattern_list identifier identifier identifier if_clause comparison_operator identifier identifier expression_statement assignment identifier call identifier generator_expression identifier for_in_clause pattern_list identifier tuple_pattern identifier identifier call identifier argument_list identifier if_clause comparison_operator identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier string string_start interpolation subscript call attribute identifier identifier argument_list identifier integer interpolation identifier string_content interpolation identifier string_end else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator identifier identifier integer tuple string string_start interpolation identifier string_content interpolation attribute identifier identifier string_end identifier expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list identifier
Populate widget with nested catalogs
def type_string(self): if self.is_tuple: subtypes = [item.type_string for item in self.children] return '{}({})'.format( '' if self.val_guaranteed else '*', ', '.join(subtypes)) elif self.is_list: return '{}[{}]'.format( '' if self.val_guaranteed else '*', self.children[0].type_string) else: return '{}{}'.format( '' if self.val_guaranteed else '*', self.type_.__name__)
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier return_statement call attribute string string_start string_content string_end identifier argument_list conditional_expression string string_start string_end attribute identifier identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier elif_clause attribute identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list conditional_expression string string_start string_end attribute identifier identifier string string_start string_content string_end attribute subscript attribute identifier identifier integer identifier else_clause block return_statement call attribute string string_start string_content string_end identifier argument_list conditional_expression string string_start string_end attribute identifier identifier string string_start string_content string_end attribute attribute identifier identifier identifier
Returns a string representing the type of the structure
def visit_continue(self, node, parent): return nodes.Continue( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list call identifier argument_list identifier string string_start string_content string_end none call identifier argument_list identifier string string_start string_content string_end none identifier
visit a Continue node by returning a fresh instance of it
def main(): startLogging(stdout) checker = InMemoryUsernamePasswordDatabaseDontUse() checker.addUser("testuser", "examplepass") realm = AdditionRealm() factory = CredAMPServerFactory(Portal(realm, [checker])) reactor.listenTCP(7805, factory) reactor.run()
module function_definition identifier parameters block expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier list identifier expression_statement call attribute identifier identifier argument_list integer identifier expression_statement call attribute identifier identifier argument_list
Start the AMP server and the reactor.
def process_column(self, idx, value): "Process a single column." if value is not None: value = str(value).decode(self.encoding) return value
module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list attribute identifier identifier return_statement identifier
Process a single column.
def find_unconstrained_reactions(model): lower_bound, upper_bound = helpers.find_bounds(model) return [rxn for rxn in model.reactions if rxn.lower_bound <= lower_bound and rxn.upper_bound >= upper_bound]
module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier return_statement list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause boolean_operator comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier
Return list of reactions that are not constrained at all.
def viewer_has_liked(self) -> Optional[bool]: if not self._context.is_logged_in: return None if 'likes' in self._node and 'viewer_has_liked' in self._node['likes']: return self._node['likes']['viewer_has_liked'] return self._field('viewer_has_liked')
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block if_statement not_operator attribute attribute identifier identifier identifier block return_statement none if_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier comparison_operator string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end block return_statement subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list string string_start string_content string_end
Whether the viewer has liked the post, or None if not logged in.
def count_generated_adv_examples(self): result = {} for v in itervalues(self.data): s_id = v['submission_id'] result[s_id] = result.get(s_id, 0) + len(v['images']) return result
module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier identifier binary_operator call attribute identifier identifier argument_list identifier integer call identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier
Returns total number of all generated adversarial examples.
def _check_pwm_list(pwm_list): for pwm in pwm_list: if not isinstance(pwm, PWM): raise TypeError("element {0} of pwm_list is not of type PWM".format(pwm)) return True
module function_definition identifier parameters identifier block for_statement identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement true
Check the input validity
def run(self, messages): statistics = {} statistics['time'] = str(datetime.now()) statistics['time-utc'] = str(datetime.utcnow()) statistics['unlock'] = self.args.unlock if self.args.question: statistics['question'] = [t.name for t in self.assignment.specified_tests] statistics['requested-questions'] = self.args.question if self.args.suite: statistics['requested-suite'] = self.args.suite if self.args.case: statistics['requested-case'] = self.args.case messages['analytics'] = statistics self.log_run(messages)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension attribute identifier identifier for_in_clause identifier attribute attribute identifier identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier if_statement attribute attribute identifier identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier
Returns some analytics about this autograder run.
def fetchUser(self, username, rawResults = False) : url = "%s/%s" % (self.URL, username) r = self.connection.session.get(url) if r.status_code == 200 : data = r.json() if rawResults : return data["result"] else : u = User(self, data) return u else : raise KeyError("Unable to get user: %s" % username)
module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block return_statement subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list identifier identifier return_statement identifier else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier
Returns a single user. if rawResults, the result will be a list of python dicts instead of User objects
def _objectify(items, container_name): objects = [] for item in items: if item.get("subdir", None) is not None: object_cls = PseudoFolder else: object_cls = StorageObject objects.append(object_cls(item, container_name)) return objects
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end none none block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier return_statement identifier
Splits a listing of objects into their appropriate wrapper classes.
def _init_composite_fields(self): self.composite_fields = copy.deepcopy(self.base_composite_fields) self.forms = OrderedDict() self.formsets = OrderedDict() for name, field in self.composite_fields.items(): self._init_composite_field(name, field)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier identifier
Setup the forms and formsets.
def map_all(self, prot_alignment, nucl_sequences): zipped = itertools.zip_longest(prot_alignment, nucl_sequences) for p, n in zipped: if p is None: raise ValueError("Exhausted protein sequences") elif n is None: raise ValueError("Exhausted nucleotide sequences") yield self.map_alignment(p, n)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier for_statement pattern_list identifier identifier identifier block if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end elif_clause comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement yield call attribute identifier identifier argument_list identifier identifier
Convert protein sequences to nucleotide alignment
def population_feature_values(pops, feature): pops_feature_values = [] for pop in pops: feature_values = [getattr(neu, 'get_' + feature)() for neu in pop.neurons] if any([isinstance(p, (list, np.ndarray)) for p in feature_values]): feature_values = list(chain(*feature_values)) pops_feature_values.append(feature_values) return pops_feature_values
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier list_comprehension call call identifier argument_list identifier binary_operator string string_start string_content string_end identifier argument_list for_in_clause identifier attribute identifier identifier if_statement call identifier argument_list list_comprehension call identifier argument_list identifier tuple identifier attribute identifier identifier for_in_clause identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list list_splat identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Extracts feature values per population
def build_catalog_info(self, catalog_info): cat = SourceFactory.build_catalog(**catalog_info) catalog_info['catalog'] = cat catalog_info['catalog_table'] = cat.table catalog_info['roi_model'] =\ SourceFactory.make_fermipy_roi_model_from_catalogs([cat]) catalog_info['srcmdl_name'] =\ self._name_factory.srcmdl_xml(sourcekey=catalog_info['catalog_name']) return CatalogInfo(**catalog_info)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end line_continuation call attribute identifier identifier argument_list list identifier expression_statement assignment subscript identifier string string_start string_content string_end line_continuation call attribute attribute identifier identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end return_statement call identifier argument_list dictionary_splat identifier
Build a CatalogInfo object
def read(src): 'Event generator from u2 stream.' parser, buff_agg = Parser(), '' while True: buff = parser.read(src) if not buff: break buff_agg += buff while True: buff_agg, ev = parser.process(buff_agg) if ev is None: break yield ev
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list string string_start string_end while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block break_statement expression_statement augmented_assignment identifier identifier while_statement true block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block break_statement expression_statement yield identifier
Event generator from u2 stream.
def use_loggly(self, enabled=True, loggly_token=None, loggly_tag=None, level=logging.WARNING, log_format=None, date_format=None): if enabled: if not self.__loggly_handler: assert loggly_token, 'Loggly token is missing!' if not loggly_tag: loggly_tag = self.name self.__loggly_handler = LogglyHandler(token=loggly_token, tag=loggly_tag) if not log_format: log_format = '{"name":"%(name)s","process":"%(process)d",' \ '"levelname":"%(levelname)s","time":"%(asctime)s",' \ '"filename":"%(filename)s","programname":"%(programname)s",' \ '"module":"%(module)s","funcName":"%(funcName)s",' \ '"lineno":"%(lineno)d","message":"%(message)s"}' formatter = logging.Formatter(fmt=log_format, datefmt=date_format) self.__loggly_handler.setFormatter(fmt=formatter) self.__loggly_handler.setLevel(level=level) self.add_handler(hdlr=self.__loggly_handler) elif self.__loggly_handler: self.remove_handler(hdlr=self.__loggly_handler) self.__loggly_handler = None
module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier none default_parameter identifier none default_parameter identifier attribute identifier identifier default_parameter identifier none default_parameter identifier none block if_statement identifier block if_statement not_operator attribute identifier identifier block assert_statement identifier string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier if_statement not_operator identifier block expression_statement assignment identifier concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier elif_clause attribute identifier identifier block expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier none
Enable handler for sending the record to Loggly service.
def _recursive_reindex_object_security(self, obj): if hasattr(aq_base(obj), "objectValues"): for obj in obj.objectValues(): self._recursive_reindex_object_security(obj) logger.debug("Reindexing object security for {}".format(repr(obj))) obj.reindexObjectSecurity()
module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list call identifier argument_list identifier string string_start string_content string_end block for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list
Reindex object security after user linking
def _complete_sig(self, symbol, attribute): fncall = self.context.el_name iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "executables") if iexec is None: iexec, execmod = self.context.parser.tree_find(fncall, self.context.module, "interfaces") if iexec is not None: if symbol == "": return iexec.parameters else: result = {} for ikey in iexec.parameters: if self._symbol_in(symbol, ikey): result[ikey] = iexec.parameters[ikey] return result else: return self._complete_word(symbol, attribute)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier attribute attribute identifier identifier identifier string string_start string_content string_end if_statement comparison_operator identifier none block if_statement comparison_operator identifier string string_start string_end block return_statement attribute identifier identifier else_clause block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier subscript attribute identifier identifier identifier return_statement identifier else_clause block return_statement call attribute identifier identifier argument_list identifier identifier
Suggests completion for calling a function or subroutine.
def run_netsh_command(netsh_args): devnull = open(os.devnull, 'w') command_raw = 'netsh interface ipv4 ' + netsh_args return int(subprocess.call(command_raw, stdout=devnull))
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end identifier return_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier
Execute a netsh command and return the output.
def _number_xpad(self): js_path = self._device_path.replace('-event', '') js_chardev = os.path.realpath(js_path) try: number_text = js_chardev.split('js')[1] except IndexError: return try: number = int(number_text) except ValueError: return self.__device_number = number
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier try_statement block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer except_clause identifier block return_statement try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block return_statement expression_statement assignment attribute identifier identifier identifier
Get the number of the joystick.
def delete_vlan_entry(self, vlan_id): with self.session.begin(subtransactions=True): try: self.session.query(ucsm_model.PortProfile).filter_by( vlan_id=vlan_id).delete() except orm.exc.NoResultFound: return
module function_definition identifier parameters identifier identifier block with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true block try_statement block expression_statement call attribute call attribute call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list except_clause attribute attribute identifier identifier identifier block return_statement
Deletes entry for a vlan_id if it exists.
def count(self, sqlTail = '') : "Compile filters and counts the number of results. You can use sqlTail to add things such as order by" sql, sqlValues = self.getSQLQuery(count = True) return int(self.con.execute('%s %s'% (sql, sqlTail), sqlValues).fetchone()[0])
module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block expression_statement string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier true return_statement call identifier argument_list subscript call attribute call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier identifier identifier argument_list integer
Compile filters and counts the number of results. You can use sqlTail to add things such as order by
def refresh(self): strawpoll_response = requests.get('{api_url}/{poll_id}'.format(api_url=api_url, poll_id=self.id)) raise_status(strawpoll_response) self.status_code = strawpoll_response.status_code self.response_json = strawpoll_response.json() self.id = self.response_json['id'] self.title = self.response_json['title'] self.options = self.response_json['options'] self.votes = self.response_json['votes'] self.captcha = self.response_json['captcha'] self.dupcheck = self.response_json['dupcheck'] self.url = 'https://www.strawpoll.me/{id}'.format(id=self.id) self.results_url = 'https://www.strawpoll.me/{id}/r'.format(id=self.id)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call identifier argument_list identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier
Refresh all class attributes.
def _get_bank_redis_key(bank): opts = _get_redis_keys_opts() return '{prefix}{separator}{bank}'.format( prefix=opts['bank_prefix'], separator=opts['separator'], bank=bank )
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list return_statement call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier identifier
Return the Redis key for the bank given the name.
def convert_result(converter): def decorate(fn): @inspection.wraps(fn) def new_fn(*args, **kwargs): return converter(fn(*args, **kwargs)) return new_fn return decorate
module function_definition identifier parameters identifier block function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier
Decorator that can convert the result of a function call.
def new_section(self, name, params=None): self.sections[name.lower()] = SectionTerm(None, name, term_args=params, doc=self) s = self.sections[name.lower()] if name.lower() in self.decl_sections: s.args = self.decl_sections[name.lower()]['args'] return s
module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment subscript attribute identifier identifier call attribute identifier identifier argument_list call identifier argument_list none identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier subscript attribute identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment attribute identifier identifier subscript subscript attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier
Return a new section
def _fill_buffer(self): if self._all_results_fetched: self._eof() raw_results = self.result_fetcher(page=self._page, per_page=self.per_page) entities = [] for raw in raw_results: entities.append(self.entity.deserialize(raw, bind_client=self.bind_client)) self._buffer = collections.deque(entities) self.log.debug("Requested page {0} (got: {1} items)".format(self._page, len(self._buffer))) if len(self._buffer) < self.per_page: self._all_results_fetched = True self._page += 1
module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement augmented_assignment attribute identifier identifier integer
Fills the internal size-50 buffer from Strava API.
def ingest(bundle, assets_version, show_progress): bundles_module.ingest( bundle, os.environ, pd.Timestamp.utcnow(), assets_version, show_progress, )
module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier identifier
Ingest the data for the given bundle.
def result_type(self): if not hasattr(self, '_result_type'): self._result_type = conf.lib.clang_getResultType(self.type) return self._result_type
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement attribute identifier identifier
Retrieve the Type of the result for this Cursor.
def ask_string(*question: Token, default: Optional[str] = None) -> Optional[str]: tokens = get_ask_tokens(question) if default: tokens.append("(%s)" % default) info(*tokens) answer = read_input() if not answer: return default return answer
module function_definition identifier parameters typed_parameter list_splat_pattern identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier none type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call identifier argument_list list_splat identifier expression_statement assignment identifier call identifier argument_list if_statement not_operator identifier block return_statement identifier return_statement identifier
Ask the user to enter a string.
def airspeed_voltage(VFR_HUD, ratio=None): import mavutil mav = mavutil.mavfile_global if ratio is None: ratio = 1.9936 if 'ARSPD_RATIO' in mav.params: used_ratio = mav.params['ARSPD_RATIO'] else: used_ratio = ratio if 'ARSPD_OFFSET' in mav.params: offset = mav.params['ARSPD_OFFSET'] else: return -1 airspeed_pressure = (pow(VFR_HUD.airspeed,2)) / used_ratio raw = airspeed_pressure + offset SCALING_OLD_CALIBRATION = 204.8 voltage = 5.0 * raw / 4096 return voltage
module function_definition identifier parameters identifier default_parameter identifier none block import_statement dotted_name identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier float if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end else_clause block expression_statement assignment identifier identifier if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end else_clause block return_statement unary_operator integer expression_statement assignment identifier binary_operator parenthesized_expression call identifier argument_list attribute identifier identifier integer identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier float expression_statement assignment identifier binary_operator binary_operator float identifier integer return_statement identifier
back-calculate the voltage the airspeed sensor must have seen
def delete_service_settings_on_service_delete(sender, instance, **kwargs): service = instance try: service_settings = service.settings except ServiceSettings.DoesNotExist: return if not service_settings.shared: service.settings.delete()
module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier identifier try_statement block expression_statement assignment identifier attribute identifier identifier except_clause attribute identifier identifier block return_statement if_statement not_operator attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list
Delete not shared service settings without services
async def jsk_in(self, ctx: commands.Context, channel: discord.TextChannel, *, command_string: str): alt_ctx = await copy_context_with(ctx, channel=channel, content=ctx.prefix + command_string) if alt_ctx.command is None: return await ctx.send(f'Command "{alt_ctx.invoked_with}" is not found') return await alt_ctx.command.invoke(alt_ctx)
module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier typed_parameter identifier type attribute identifier identifier keyword_separator typed_parameter identifier type identifier block expression_statement assignment identifier await call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier binary_operator attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier none block return_statement await call attribute identifier identifier argument_list string string_start string_content interpolation attribute identifier identifier string_content string_end return_statement await call attribute attribute identifier identifier identifier argument_list identifier
Run a command as if it were in a different channel.
def _get_bandfilenames(self): path = self.path for band in MODIS_BAND_NAMES: bnum = int(band) LOG.debug("Band = %s", str(band)) if self.platform_name == 'EOS-Terra': filename = os.path.join(path, "rsr.{0:d}.inb.final".format(bnum)) else: if bnum in [5, 6, 7] + range(20, 37): filename = os.path.join( path, "{0:>02d}.tv.1pct.det".format(bnum)) else: filename = os.path.join( path, "{0:>02d}.amb.1pct.det".format(bnum)) self.filenames[band] = filename
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier else_clause block if_statement comparison_operator identifier binary_operator list integer integer integer call identifier argument_list integer integer block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment subscript attribute identifier identifier identifier identifier
Get the MODIS rsr filenames
def _dispatch(self, operation, request, path_args): request_type = resolve_content_type(self.request_type_resolvers, request) request_type = self.remap_codecs.get(request_type, request_type) try: request.request_codec = self.registered_codecs[request_type] except KeyError: return HttpResponse.from_status(HTTPStatus.UNPROCESSABLE_ENTITY) response_type = resolve_content_type(self.response_type_resolvers, request) response_type = self.remap_codecs.get(response_type, response_type) try: request.response_codec = self.registered_codecs[response_type] except KeyError: return HttpResponse.from_status(HTTPStatus.NOT_ACCEPTABLE) if request.method not in operation.methods: return HttpResponse.from_status( HTTPStatus.METHOD_NOT_ALLOWED, {'Allow': ','.join(m.value for m in operation.methods)} ) resource, status, headers = self.dispatch_operation(operation, request, path_args) if isinstance(status, HTTPStatus): status = status.value if isinstance(resource, HttpResponse): return resource return create_response(request, resource, status, headers)
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier try_statement block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier identifier except_clause identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier try_statement block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier identifier except_clause identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier generator_expression attribute identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement call identifier argument_list identifier identifier block return_statement identifier return_statement call identifier argument_list identifier identifier identifier identifier
Wrapped dispatch method, prepare request and generate a HTTP Response.
def validate(self, node): assert isinstance(node, Node) if isinstance(node.operator, Logical): self.validate(node.left) self.validate(node.right) return assert isinstance(node.left, Name) assert isinstance(node.operator, Comparison) assert isinstance(node.right, (Const, List)) field = self.resolve_name(node.left) value = node.right.value if field is None: if value is not None: raise DjangoQLSchemaError( 'Related model %s can be compared to None only, but not to ' '%s' % (node.left.value, type(value).__name__) ) else: values = value if isinstance(node.right, List) else [value] for v in values: field.validate(v)
module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list identifier identifier if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement assert_statement call identifier argument_list attribute identifier identifier identifier assert_statement call identifier argument_list attribute identifier identifier identifier assert_statement call identifier argument_list attribute identifier identifier tuple identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier none block if_statement comparison_operator identifier none block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end tuple attribute attribute identifier identifier identifier attribute call identifier argument_list identifier identifier else_clause block expression_statement assignment identifier conditional_expression identifier call identifier argument_list attribute identifier identifier identifier list identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier
Validate DjangoQL AST tree vs. current schema
def _accumulate_remotes(synapse_parent_id, syn): remotes = {} s_base_folder = syn.get(synapse_parent_id) for (s_dirpath, s_dirpath_id), _, s_filenames in synapseutils.walk(syn, synapse_parent_id): remotes[s_dirpath] = s_dirpath_id if s_filenames: for s_filename, s_filename_id in s_filenames: remotes[os.path.join(s_dirpath, s_filename)] = s_filename_id return s_base_folder, remotes
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement pattern_list tuple_pattern identifier identifier identifier identifier call attribute identifier identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier identifier if_statement identifier block for_statement pattern_list identifier identifier identifier block expression_statement assignment subscript identifier call attribute attribute identifier identifier identifier argument_list identifier identifier identifier return_statement expression_list identifier identifier
Retrieve references to all remote directories and files.
def u_string_check(self, original, loc, tokens): return self.check_strict("Python-2-style unicode string", original, loc, tokens)
module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier identifier
Check for Python2-style unicode strings.
def words_from_archive(filename, include_dups=False, map_case=False): bz2 = os.path.join(PATH, BZ2) tar_path = '{}/{}'.format('words', filename) with closing(tarfile.open(bz2, 'r:bz2')) as t: with closing(t.extractfile(tar_path)) as f: words = re.findall(RE, f.read().decode(encoding='utf-8')) if include_dups: return words elif map_case: return {w.lower():w for w in words} else: return set(words)
module function_definition identifier parameters identifier default_parameter identifier false default_parameter identifier false block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list string string_start string_content string_end identifier with_statement with_clause with_item as_pattern call identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list call attribute identifier identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier string string_start string_content string_end if_statement identifier block return_statement identifier elif_clause identifier block return_statement dictionary_comprehension pair call attribute identifier identifier argument_list identifier for_in_clause identifier identifier else_clause block return_statement call identifier argument_list identifier
extract words from a text file in the archive
def _prepare_resources(self, variables, overrides=None): if overrides is None: overrides = {} res_map = {} own_map = {} for decl in self.resources.values(): resource = overrides.get(decl.name) if resource is None: args = _complete_parameters(decl.args, variables) resource = decl.type(args) own_map[decl.name] = resource if decl.autocreate: resource.open() res_map[decl.name] = resource return res_map, own_map
module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment subscript identifier attribute identifier identifier identifier return_statement expression_list identifier identifier
Create and optionally open all shared resources.
def getRandomPairwiseAlignment(): i, j, k, l = _getRandomSegment() m, n, o, p = _getRandomSegment() score = random.choice(xrange(-1000, 1000)) return PairwiseAlignment(i, j, k, l, m, n, o, p, score, getRandomOperationList(abs(k - j), abs(o - n)))
module function_definition identifier parameters block expression_statement assignment pattern_list identifier identifier identifier identifier call identifier argument_list expression_statement assignment pattern_list identifier identifier identifier identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list unary_operator integer integer return_statement call identifier argument_list identifier identifier identifier identifier identifier identifier identifier identifier identifier call identifier argument_list call identifier argument_list binary_operator identifier identifier call identifier argument_list binary_operator identifier identifier
Gets a random pairwiseAlignment.
def cancel(self): target_url = self._client.get_url('PUBLISH', 'DELETE', 'single', {'id': self.id}) r = self._client.request('DELETE', target_url) logger.info("cancel(): %s", r.status_code)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier
Cancel a pending publish task
async def _run_socket(self): try: while True: message = await ZMQUtils.recv(self._socket) msg_class = message.__msgtype__ if msg_class in self._handlers_registered: self._loop.create_task(self._handlers_registered[msg_class](message)) elif msg_class in self._transactions: _1, get_key, coroutine_recv, _2, responsible = self._msgs_registered[msg_class] key = get_key(message) if key in self._transactions[msg_class]: for args, kwargs in self._transactions[msg_class][key]: self._loop.create_task(coroutine_recv(message, *args, **kwargs)) for key2 in responsible: del self._transactions[key2][key] else: raise Exception("Received message %s for an unknown transaction %s", msg_class, key) else: raise Exception("Received unknown message %s", msg_class) except asyncio.CancelledError: return except KeyboardInterrupt: return
module function_definition identifier parameters identifier block try_statement block while_statement true block expression_statement assignment identifier await call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call subscript attribute identifier identifier identifier argument_list identifier elif_clause comparison_operator identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier subscript attribute identifier identifier identifier block for_statement pattern_list identifier identifier subscript subscript attribute identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier list_splat identifier dictionary_splat identifier for_statement identifier identifier block delete_statement subscript subscript attribute identifier identifier identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end identifier except_clause attribute identifier identifier block return_statement except_clause identifier block return_statement
Task that runs this client.
def publish_properties(self): publish = self.publish publish(b"$homie", b"3.0.1") publish(b"$name", self.settings.DEVICE_NAME) publish(b"$state", b"init") publish(b"$fw/name", b"Microhomie") publish(b"$fw/version", __version__) publish(b"$implementation", bytes(sys.platform, "utf-8")) publish(b"$localip", utils.get_local_ip()) publish(b"$mac", utils.get_local_mac()) publish(b"$stats", b"interval,uptime,freeheap") publish(b"$stats/interval", self.stats_interval) publish(b"$nodes", b",".join(self.node_ids)) for node in self.nodes: try: for propertie in node.get_properties(): if propertie: publish(*propertie) except NotImplementedError: raise except Exception as error: self.node_error(node, error)
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list string string_start string_content string_end call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifier block try_statement block for_statement identifier call attribute identifier identifier argument_list block if_statement identifier block expression_statement call identifier argument_list list_splat identifier except_clause identifier block raise_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier
publish device and node properties
def profile(script, argv, profiler_factory, pickle_protocol, dump_filename, mono): filename, code, globals_ = script sys.argv[:] = [filename] + list(argv) __profile__(filename, code, globals_, profiler_factory, pickle_protocol=pickle_protocol, dump_filename=dump_filename, mono=mono)
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment subscript attribute identifier identifier slice binary_operator list identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Profile a Python script.
def _open_browser(self, single_doc_html): url = os.path.join('file://', DOC_PATH, 'build', 'html', single_doc_html) webbrowser.open(url, new=2)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier integer
Open a browser tab showing single
def _get_ssl_sock(self): assert self.scheme == u"https", self raw_connection = self.url_connection.raw._connection if raw_connection.sock is None: raw_connection.connect() return raw_connection.sock
module function_definition identifier parameters identifier block assert_statement comparison_operator attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list return_statement attribute identifier identifier
Get raw SSL socket.
def extras_msg(extras): if len(extras) == 1: verb = "was" else: verb = "were" return ", ".join(repr(extra) for extra in extras), verb
module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end return_statement expression_list call attribute string string_start string_content string_end identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier identifier
Create an error message for extra items or properties.
def pypy_json_encode(value, pretty=False): global _dealing_with_problem if pretty: return pretty_json(value) try: _buffer = UnicodeBuilder(2048) _value2json(value, _buffer) output = _buffer.build() return output except Exception as e: from mo_logs import Log if _dealing_with_problem: Log.error("Serialization of JSON problems", e) else: Log.warning("Serialization of JSON problems", e) _dealing_with_problem = True try: return pretty_json(value) except Exception as f: Log.error("problem serializing object", f) finally: _dealing_with_problem = False
module function_definition identifier parameters identifier default_parameter identifier false block global_statement identifier if_statement identifier block return_statement call identifier argument_list identifier try_statement block expression_statement assignment identifier call identifier argument_list integer expression_statement call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block import_from_statement dotted_name identifier dotted_name identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier true try_statement block return_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier finally_clause block expression_statement assignment identifier false
pypy DOES NOT OPTIMIZE GENERATOR CODE WELL
def plot(self, minx=-1.5, maxx=1.2, miny=-0.2, maxy=2, **kwargs): import matplotlib.pyplot as pp grid_width = max(maxx-minx, maxy-miny) / 200.0 ax = kwargs.pop('ax', None) xx, yy = np.mgrid[minx:maxx:grid_width, miny:maxy:grid_width] V = self.potential(xx, yy) if ax is None: ax = pp ax.contourf(xx, yy, V.clip(max=200), 40, **kwargs)
module function_definition identifier parameters identifier default_parameter identifier unary_operator float default_parameter identifier float default_parameter identifier unary_operator float default_parameter identifier integer dictionary_splat_pattern identifier block import_statement aliased_import dotted_name identifier identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list binary_operator identifier identifier binary_operator identifier identifier float expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment pattern_list identifier identifier subscript attribute identifier identifier slice identifier identifier identifier slice identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier integer integer dictionary_splat identifier
Helper function to plot the Muller potential
def context_factory(apply_globally=False, api=None): def decorator(context_factory_): if apply_globally: hug.defaults.context_factory = context_factory_ else: apply_to_api = hug.API(api) if api else hug.api.from_object(context_factory_) apply_to_api.context_factory = context_factory_ return context_factory_ return decorator
module function_definition identifier parameters default_parameter identifier false default_parameter identifier none block function_definition identifier parameters identifier block if_statement identifier block expression_statement assignment attribute attribute identifier identifier identifier identifier else_clause block expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier return_statement identifier
A decorator that registers a single hug context factory
def startLoop(self, useDriverLoop): if useDriverLoop: self._driver.startLoop() else: self._iterator = self._driver.iterate()
module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list
Called by the engine to start an event loop.
def focus_first_reply(self): mid = self.get_selected_mid() newpos = self._tree.first_child_position(mid) if newpos is not None: newpos = self._sanitize_position((newpos,)) self.body.set_focus(newpos)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
move focus to first reply to currently focussed message
def extension_by_source(source, mime_type): "Return the file extension used by this plugin" extension = source.plugin_name if extension: return extension if mime_type: return mime_type.split("/")[-1]
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier if_statement identifier block return_statement identifier if_statement identifier block return_statement subscript call attribute identifier identifier argument_list string string_start string_content string_end unary_operator integer
Return the file extension used by this plugin
def dag(self) -> Tuple[Dict, Dict]: from pipelines import dags operations = self.operations.all().prefetch_related('downstream_operations') def get_downstream(op): return op.downstream_operations.values_list('id', flat=True) return dags.get_dag(operations, get_downstream)
module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier type identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end function_definition identifier parameters identifier block return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true return_statement call attribute identifier identifier argument_list identifier identifier
Construct the DAG of this pipeline based on the its operations and their downstream.
def error_handler(f): @wraps(f) def decorated(*args, **kwargs): try: return f(*args, **kwargs) except OAuth2Error as e: if hasattr(e, 'redirect_uri'): return redirect(e.in_uri(e.redirect_uri)) else: return redirect(e.in_uri(oauth2.error_uri)) return decorated
module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier else_clause block return_statement call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier
Handle uncaught OAuth errors.
def new_parallel(self, function, *params): if self.ppool is None: if core_type == 'thread': from multiprocessing.pool import ThreadPool self.ppool = ThreadPool(500) else: from gevent.pool import Pool self.ppool = Pool(500) self.ppool.apply_async(function, *params)
module function_definition identifier parameters identifier identifier list_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block if_statement comparison_operator identifier string string_start string_content string_end block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment attribute identifier identifier call identifier argument_list integer else_clause block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment attribute identifier identifier call identifier argument_list integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier list_splat identifier
Register a new thread executing a parallel method.
def unset(self, section, option): with self._lock: if not self._config.has_section(section): return if self._config.has_option(section, option): self._config.remove_option(section, option) self._dirty = True if not self._config.options(section): self._config.remove_section(section) self._dirty = True
module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item attribute identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block return_statement if_statement call attribute attribute identifier identifier identifier argument_list identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement assignment attribute identifier identifier true if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier true
Remove option from section.
def act(self): g = get_root(self).globals fname = filedialog.askopenfilename( defaultextension='.json', filetypes=[('json files', '.json'), ('fits files', '.fits')], initialdir=g.cpars['app_directory']) if not fname: g.clog.warn('Aborted load from disk') return False if fname.endswith('.json'): with open(fname) as ifname: json_string = ifname.read() else: json_string = jsonFromFits(fname) g.ipars.loadJSON(json_string) g.rpars.loadJSON(json_string) return True
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier list tuple string string_start string_content string_end string string_start string_content string_end tuple string string_start string_content string_end string string_start string_content string_end keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end if_statement not_operator identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement false if_statement call attribute identifier identifier argument_list string string_start string_content string_end block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement true
Carries out the action associated with the Load button
def add_summaries(self, step, *tags_and_values): values = [] to_print = [] for tag, value in tags_and_values: values.append(tf.Summary.Value(tag=tag, simple_value=float(value))) to_print.append('%s=%g' % (tag, value)) if self._summary_writer: summary = tf.Summary(value=values) event = tf.Event(wall_time=time.time(), summary=summary, step=int(step)) self._summary_writer.add_event(event) print('[%d] %s' % (step, ', '.join(to_print)))
module function_definition identifier parameters identifier identifier list_splat_pattern identifier block expression_statement assignment identifier list expression_statement assignment identifier list for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list identifier
Adds summaries to the writer and prints a log statement.
def update_main_table(self): data = (json.dumps(self.settings),) self.cursor.execute( ) self.cursor.execute('SELECT * FROM main') if self.cursor.fetchall() == []: self.cursor.execute('INSERT INTO main (settings) VALUES (?)', data) else: self.cursor.execute('UPDATE main SET settings=?', data)
module function_definition identifier parameters identifier block expression_statement assignment identifier tuple call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list list block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier
Write generator settings to database.
def fulltext_add(self, index, docs): xml = Document() root = xml.createElement('add') for doc in docs: doc_element = xml.createElement('doc') for key in doc: value = doc[key] field = xml.createElement('field') field.setAttribute("name", key) text = xml.createTextNode(value) field.appendChild(text) doc_element.appendChild(field) root.appendChild(doc_element) xml.appendChild(root) self._request('POST', self.solr_update_path(index), {'Content-Type': 'text/xml'}, xml.toxml().encode('utf-8'))
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end string string_start string_content string_end call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end
Adds documents to the search index.
def cds(self): ces = self.coding_exons if len(ces) < 1: return ces ces[0] = (self.cdsStart, ces[0][1]) ces[-1] = (ces[-1][0], self.cdsEnd) assert all((s < e for s, e in ces)) return ces
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement identifier expression_statement assignment subscript identifier integer tuple attribute identifier identifier subscript subscript identifier integer integer expression_statement assignment subscript identifier unary_operator integer tuple subscript subscript identifier unary_operator integer integer attribute identifier identifier assert_statement call identifier argument_list generator_expression comparison_operator identifier identifier for_in_clause pattern_list identifier identifier identifier return_statement identifier
just the parts of the exons that are translated
def find_bled112_devices(cls): found_devs = [] ports = serial.tools.list_ports.comports() for port in ports: if not hasattr(port, 'pid') or not hasattr(port, 'vid'): continue if port.pid == 1 and port.vid == 9304: found_devs.append(port.device) return found_devs
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list for_statement identifier identifier block if_statement boolean_operator not_operator call identifier argument_list identifier string string_start string_content string_end not_operator call identifier argument_list identifier string string_start string_content string_end block continue_statement if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier
Look for BLED112 dongles on this computer and start an instance on each one
def s3(self, url, account_acessor=None, access=None, secret=None): from ambry.util.ambrys3 import AmbryS3FS from ambry.util import parse_url_to_dict import ssl pd = parse_url_to_dict(url) if account_acessor: account = account_acessor(pd['hostname']) assert account['account_id'] == pd['hostname'] aws_access_key = account['access_key'], aws_secret_key = account['secret'] else: aws_access_key = access aws_secret_key = secret assert access, url assert secret, url s3 = AmbryS3FS( bucket=pd['netloc'], prefix=pd['path'].strip('/')+'/', aws_access_key=aws_access_key, aws_secret_key=aws_secret_key, ) return s3
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block import_from_statement dotted_name identifier identifier identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier import_statement dotted_name identifier expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end assert_statement comparison_operator subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier expression_list subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier identifier expression_statement assignment identifier identifier assert_statement identifier identifier assert_statement identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier binary_operator call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier return_statement identifier
Setup an S3 pyfs, with account credentials, fixing an ssl matching problem
def shell(command, *args): if args: command = command.format(*args) print LOCALE['shell'].format(command) try: return subprocess.check_output(command, shell=True) except subprocess.CalledProcessError, ex: return ex
module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_splat identifier print_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier try_statement block return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true except_clause attribute identifier identifier identifier block return_statement identifier
Pass a command into the shell.
def get(name, import_str=False): value = None default_value = getattr(default_settings, name) try: value = getattr(settings, name) except AttributeError: if name in default_settings.required_attrs: raise Exception('You must set ' + name + ' in your settings.') if isinstance(default_value, dict) and value: default_value.update(value) value = default_value else: if value is None: value = default_value value = import_from_str(value) if import_str else value return value
module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier none expression_statement assignment identifier call identifier argument_list identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier except_clause identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end if_statement boolean_operator call identifier argument_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier else_clause block if_statement comparison_operator identifier none block expression_statement assignment identifier identifier expression_statement assignment identifier conditional_expression call identifier argument_list identifier identifier identifier return_statement identifier
Helper function to use inside the package.
def _get_window_list(self): window_list = Quartz.CGWindowListCopyWindowInfo(Quartz.kCGWindowListExcludeDesktopElements, Quartz.kCGNullWindowID) return window_list
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier return_statement identifier
Returns a dictionary of details about open windows
def cases(self): import nitrate if self._cases is None: log.info(u"Searching for cases created by {0}".format(self.user)) self._cases = [ case for case in nitrate.TestCase.search( author__email=self.user.email, create_date__gt=str(self.options.since), create_date__lt=str(self.options.until)) if case.status != nitrate.CaseStatus("DISABLED")] return self._cases
module function_definition identifier parameters identifier block import_statement dotted_name identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier list_comprehension identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier call identifier argument_list attribute attribute identifier identifier identifier if_clause comparison_operator attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement attribute identifier identifier
All test cases created by the user
def load(self, filething): fileobj = filething.fileobj self.metadata_blocks = [] self.tags = None self.cuesheet = None self.seektable = None fileobj = StrictFileObject(fileobj) self.__check_header(fileobj, filething.name) while self.__read_metadata_block(fileobj): pass try: self.metadata_blocks[0].length except (AttributeError, IndexError): raise FLACNoHeaderError("Stream info block not found") if self.info.length: start = fileobj.tell() fileobj.seek(0, 2) self.info.bitrate = int( float(fileobj.tell() - start) * 8 / self.info.length) else: self.info.bitrate = 0
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment attribute identifier identifier none expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier while_statement call attribute identifier identifier argument_list identifier block pass_statement try_statement block expression_statement attribute subscript attribute identifier identifier integer identifier except_clause tuple identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement attribute attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer integer expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list binary_operator binary_operator call identifier argument_list binary_operator call attribute identifier identifier argument_list identifier integer attribute attribute identifier identifier identifier else_clause block expression_statement assignment attribute attribute identifier identifier identifier integer
Load file information from a filename.
def registerAPI(self, name, handler, container = None, discoverinfo = None, criteria = None): self.handler.registerHandler(*self._createHandler(name, handler, container, criteria)) if discoverinfo is None: self.discoverinfo[name] = {'description': cleandoc(handler.__doc__)} else: self.discoverinfo[name] = discoverinfo
module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list list_splat call attribute identifier identifier argument_list identifier identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment subscript attribute identifier identifier identifier dictionary pair string string_start string_content string_end call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment subscript attribute identifier identifier identifier identifier
Append new API to this handler
def start(self): msg = '' if not self.running(): if self._port == 0: self._port = _port_not_in_use() self._process = start_server_background(self._port) else: msg = 'Server already started\n' msg += 'Server running at {}'.format(self.url()) print(msg)
module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end if_statement not_operator call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier
Start server if not previously started.
def transformer_tall_pretrain_lm_tpu(): hparams = transformer_tall_pretrain_lm_tpu_adafactor() hparams.learning_rate_constant = 2e-4 hparams.learning_rate_schedule = ("linear_warmup * constant * cosdecay") hparams.optimizer = "adam_w" return hparams
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier float expression_statement assignment attribute identifier identifier parenthesized_expression string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end return_statement identifier
Hparams for transformer on LM pretraining on TPU with AdamW.
def server_by_name(self, name): return self.server_show_libcloud( self.server_list().get(name, {}).get('id', '') )
module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier dictionary identifier argument_list string string_start string_content string_end string string_start string_end
Find a server by its name
def Parse(self, stat, unused_knowledge_base): value = stat.registry_data.GetValue() if not str(value).isdigit() or int(value) > 999 or int(value) < 0: raise parser.ParseError( "Invalid value for CurrentControlSet key %s" % value) yield rdfvalue.RDFString( "HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet%03d" % int(value))
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement boolean_operator boolean_operator not_operator call attribute call identifier argument_list identifier identifier argument_list comparison_operator call identifier argument_list identifier integer comparison_operator call identifier argument_list identifier integer block raise_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement yield call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence escape_sequence string_end call identifier argument_list identifier
Parse the key currentcontrolset output.
def _set_or_check_remote_id(self, remote_id): if not self.remote_id: assert self.closed_state == self.ClosedState.PENDING, 'Bad ClosedState!' self.remote_id = remote_id self.closed_state = self.ClosedState.OPEN elif self.remote_id != remote_id: raise usb_exceptions.AdbProtocolError( '%s remote-id change to %s', self, remote_id)
module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block assert_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier elif_clause comparison_operator attribute identifier identifier identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier
Set or check the remote id.
def google_get_token(self, config, prefix): params = { 'code': self.request_args_get( 'code', default=''), 'client_id': self.google_api_client_id, 'client_secret': self.google_api_client_secret, 'redirect_uri': self.scheme_host_port_prefix( 'http', config.host, config.port, prefix) + '/home', 'grant_type': 'authorization_code', } payload = urlencode(params).encode('utf-8') url = self.google_oauth2_url + 'token' req = Request(url, payload) json_str = urlopen(req).read() return json.loads(json_str.decode('utf-8'))
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end binary_operator call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier identifier string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end
Make request to Google API to get token.
def create_event(self, timestamp, event_type, hostname, fields, tags=None): event_payload = fields._asdict() msg_text = { 'event_type': event_payload.pop('event_type', None), 'event_soft_hard': event_payload.pop('event_soft_hard', None), 'check_name': event_payload.pop('check_name', None), 'event_state': event_payload.pop('event_state', None), 'payload': event_payload.pop('payload', None), 'ack_author': event_payload.pop('ack_author', None), } msg_text = json.dumps(msg_text) self.log.info("Nagios Event pack: {}".format(msg_text)) event_payload.update( { 'timestamp': timestamp, 'event_type': event_type, 'msg_text': msg_text, 'source_type_name': SOURCE_TYPE_NAME, 'tags': tags, } ) host = event_payload.get('host', None) if host == "localhost": event_payload["host"] = hostname return event_payload
module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end none pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end none pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end none pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end none pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end none pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end none if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier
Factory method called by the parsers
def parse_cl_args(arg_vector): parser = argparse.ArgumentParser(description='Compiles markdown files into html files for remark.js') parser.add_argument('source', metavar='source', help='the source to compile. If a directory is provided, all markdown files in that directory are compiled. Output is saved in the current working directory under a md2remark_build subdirectory.') return parser.parse_args(arg_vector)
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier
Parses the command line arguments
def _create_index(self): if not self.index_exists: index_settings = {} headers = {'Content-Type': 'application/json', 'DB-Method': 'POST'} url = '/v2/exchange/db/{}/{}'.format(self.domain, self.data_type) r = self.tcex.session.post(url, json=index_settings, headers=headers) if not r.ok: error = r.text or r.reason self.tcex.handle_error(800, [r.status_code, error]) self.tcex.log.debug( 'creating index. status_code: {}, response: "{}".'.format(r.status_code, r.text) )
module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement not_operator attribute identifier identifier block expression_statement assignment identifier boolean_operator attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list integer list attribute identifier identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier
Create index if it doesn't exist.
def _handle_tag_defineshape(self): obj = _make_object("DefineShape") obj.ShapeId = unpack_ui16(self._src) obj.ShapeBounds = self._get_struct_rect() obj.Shapes = self._get_struct_shapewithstyle(1) return obj
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer return_statement identifier
Handle the DefineShape tag.
def _initialize_tables(self): self.table_struct, self.idnt_struct_size = self._create_struct_table() self.table_values, self.idnt_values_size = self._create_values_table()
module function_definition identifier parameters identifier block expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list
Create tables for structure and values, word->vocabulary
def __get_idxs(self, words): if self.bow: return list(itertools.chain.from_iterable( [self.positions[z] for z in words])) else: return self.positions[words]
module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list list_comprehension subscript attribute identifier identifier identifier for_in_clause identifier identifier else_clause block return_statement subscript attribute identifier identifier identifier
Returns indexes to appropriate words.
def pssm_array2pwm_array(arr, background_probs=DEFAULT_BASE_BACKGROUND): b = background_probs2array(background_probs) b = b.reshape([1, 4, 1]) return (np.exp(arr) * b).astype(arr.dtype)
module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list list integer integer integer return_statement call attribute parenthesized_expression binary_operator call attribute identifier identifier argument_list identifier identifier identifier argument_list attribute identifier identifier
Convert pssm array to pwm array
def isasteroid(self): if self.asteroid is not None: return self.asteroid elif self.comet is not None: return not self.comet else: return any(self.parse_asteroid()) is not None
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement attribute identifier identifier elif_clause comparison_operator attribute identifier identifier none block return_statement not_operator attribute identifier identifier else_clause block return_statement comparison_operator call identifier argument_list call attribute identifier identifier argument_list none
`True` if `targetname` appears to be an asteroid.