code
stringlengths
51
2.34k
sequence
stringlengths
186
3.94k
docstring
stringlengths
11
171
def create(gitpath, cache=None): if gitpath.startswith(config.LIBRARY_PREFIX): path = gitpath[len(config.LIBRARY_PREFIX):] return Library(*path.split('/'), cache=cache)
module function_definition identifier parameters identifier default_parameter identifier none block if_statement call attribute identifier identifier argument_list attribute identifier identifier block expression_statement assignment identifier subscript identifier slice call identifier argument_list attribute identifier identifier return_statement call identifier argument_list list_splat call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier
Create a Library from a git path.
def publishing_prepare_published_copy(self, draft_obj): mysuper = super(PublishingModel, self) if hasattr(mysuper, 'publishing_prepare_published_copy'): mysuper.publishing_prepare_published_copy(draft_obj)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier
Prepare published copy of draft prior to saving it
def _init_client(): if client is not None: return global _mysql_kwargs, _table_name _mysql_kwargs = { 'host': __opts__.get('mysql.host', '127.0.0.1'), 'user': __opts__.get('mysql.user', None), 'passwd': __opts__.get('mysql.password', None), 'db': __opts__.get('mysql.database', _DEFAULT_DATABASE_NAME), 'port': __opts__.get('mysql.port', 3306), 'unix_socket': __opts__.get('mysql.unix_socket', None), 'connect_timeout': __opts__.get('mysql.connect_timeout', None), 'autocommit': True, } _table_name = __opts__.get('mysql.table_name', _table_name) for k, v in _mysql_kwargs.items(): if v is None: _mysql_kwargs.pop(k) kwargs_copy = _mysql_kwargs.copy() kwargs_copy['passwd'] = "<hidden>" log.info("mysql_cache: Setting up client with params: %r", kwargs_copy) _create_table()
module function_definition identifier parameters block if_statement comparison_operator identifier none block return_statement global_statement identifier identifier 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 string string_start string_content string_end 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 identifier pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end integer 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 true expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end 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 call identifier argument_list
Initialize connection and create table if needed
def success(self, request, message, extra_tags='', fail_silently=False): add(self.target_name, request, constants.SUCCESS, message, extra_tags=extra_tags, fail_silently=fail_silently)
module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_end default_parameter identifier false block expression_statement call identifier argument_list attribute identifier identifier identifier attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Add a message with the ``SUCCESS`` level.
def asrgb(self, *args, **kwargs): if self._keyframe is None: raise RuntimeError('keyframe not set') kwargs['validate'] = False return TiffPage.asrgb(self, *args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end false return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier
Read image data from file and return RGB image as numpy array.
def clear_components(self): ComponentRegistry._component_overlays = {} for key in self.list_components(): self.remove_component(key)
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier
Clear all of the registered components
def draw_canvas(): for x in range(len(world)): for y in range(len(world[x])): if world[x][y].value: color = world[x][y].color_alive.get_as_hex() else: color = world[x][y].color_dead.get_as_hex() canvas.itemconfig(canvas_grid[x][y], fill=color)
module function_definition identifier parameters block for_statement identifier call identifier argument_list call identifier argument_list identifier block for_statement identifier call identifier argument_list call identifier argument_list subscript identifier identifier block if_statement attribute subscript subscript identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute subscript subscript identifier identifier identifier identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute attribute subscript subscript identifier identifier identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list subscript subscript identifier identifier identifier keyword_argument identifier identifier
Render the tkinter canvas based on the state of ``world``
def decode_network_packet(buf): off = 0 blen = len(buf) while off < blen: ptype, plen = header.unpack_from(buf, off) if plen > blen - off: raise ValueError("Packet longer than amount of data in buffer") if ptype not in _decoders: raise ValueError("Message type %i not recognized" % ptype) yield ptype, _decoders[ptype](ptype, plen, buf[off:]) off += plen
module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement assignment identifier call identifier argument_list identifier while_statement comparison_operator identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator identifier binary_operator identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement yield expression_list identifier call subscript identifier identifier argument_list identifier identifier subscript identifier slice identifier expression_statement augmented_assignment identifier identifier
Decodes a network packet in collectd format.
def __start(self): assert not self.dispatcher_thread self.dispatcher_thread = threading.Thread(target=self.__run_dispatcher, name='clearly-dispatcher') self.dispatcher_thread.daemon = True self.running = True self.dispatcher_thread.start()
module function_definition identifier parameters identifier block assert_statement not_operator attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment attribute attribute identifier identifier identifier true expression_statement assignment attribute identifier identifier true expression_statement call attribute attribute identifier identifier identifier argument_list
Starts the real-time engine that captures tasks.
def delete(self): 'Delete this file and return the new, deleted JFSFile' r = self.jfs.post(url=self.path, params={'dl':'true'}) return r
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier dictionary pair string string_start string_content string_end string string_start string_content string_end return_statement identifier
Delete this file and return the new, deleted JFSFile
def parse_file(infile, exit_on_error=True): try: a, b, mag = np.atleast_2d( np.genfromtxt( infile, usecols=[0, 1, 2], delimiter=',' ) ).T except IOError as e: if exit_on_error: logger.error("There seems to be a problem with the input file, " "the format should be: RA_degrees (J2000), Dec_degrees (J2000), " "Magnitude. There should be no header, columns should be " "separated by a comma") sys.exit(1) else: raise e return a, b, mag
module function_definition identifier parameters identifier default_parameter identifier true block try_statement block expression_statement assignment pattern_list identifier identifier identifier attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier list integer integer integer keyword_argument identifier string string_start string_content string_end identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list 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 expression_statement call attribute identifier identifier argument_list integer else_clause block raise_statement identifier return_statement expression_list identifier identifier identifier
Parse a comma-separated file with columns "ra,dec,magnitude".
def windowed_iterable(self): effective_offset = max(0,self.item_view.iterable_index) for i,item in enumerate(self.iterable): if i<effective_offset: continue elif i>=(effective_offset+self.item_view.iterable_fetch_size): return yield item
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list integer attribute attribute identifier identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier identifier block continue_statement elif_clause comparison_operator identifier parenthesized_expression binary_operator identifier attribute attribute identifier identifier identifier block return_statement expression_statement yield identifier
That returns only the window
def focused_data_item(self) -> typing.Optional[DataItem.DataItem]: return self.__focused_display_item.data_item if self.__focused_display_item else None
module function_definition identifier parameters identifier type subscript attribute identifier identifier attribute identifier identifier block return_statement conditional_expression attribute attribute identifier identifier identifier attribute identifier identifier none
Return the data item with keyboard focus.
def mount(cls, mount_point, lower_dir, upper_dir, mount_table=None): ensure_directories(mount_point, lower_dir, upper_dir) if not mount_table: mount_table = MountTable.load() if mount_table.is_mounted(mount_point): raise AlreadyMounted() options = "rw,lowerdir=%s,upperdir=%s" % (lower_dir, upper_dir) subwrap.run(['mount', '-t', 'overlayfs', '-o', options, 'olyfs%s' % random_name(), mount_point]) return cls(mount_point, lower_dir, upper_dir)
module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none block expression_statement call identifier argument_list identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier expression_statement call attribute identifier identifier argument_list list 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 identifier binary_operator string string_start string_content string_end call identifier argument_list identifier return_statement call identifier argument_list identifier identifier identifier
Execute the mount. This requires root
def _get_on_demand_syllabus(self, class_name): url = OPENCOURSE_ONDEMAND_COURSE_MATERIALS_V2.format( class_name=class_name) page = get_page(self._session, url) logging.debug('Downloaded %s (%d bytes)', url, len(page)) return page
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier call identifier argument_list identifier return_statement identifier
Get the on-demand course listing webpage.
def write_capability_list(self, capabilities=None, outfile=None, links=None): capl = CapabilityList(ln=links) capl.pretty_xml = self.pretty_xml if (capabilities is not None): for name in capabilities.keys(): capl.add_capability(name=name, uri=capabilities[name]) if (outfile is None): print(capl.as_xml()) else: capl.write(basename=outfile)
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement parenthesized_expression comparison_operator identifier none block for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier subscript identifier identifier if_statement parenthesized_expression comparison_operator identifier none block expression_statement call identifier argument_list call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier
Write a Capability List to outfile or STDOUT.
def cli(config_path, verbose): global config, store if not config_path: config_path = '/etc/record_recommender.yml' config = get_config(config_path) setup_logging(config) store = FileStore(config)
module function_definition identifier parameters identifier identifier block global_statement identifier identifier if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier
Record-Recommender command line version.
def open(self, auto_commit=None, schema=None): if schema is None: schema = self.schema ac = auto_commit if auto_commit is not None else schema.auto_commit exe = ExecutionContext(self.path, schema=schema, auto_commit=ac) if not os.path.isfile(self.path) or os.path.getsize(self.path) == 0: getLogger().warning("DB does not exist at {}. Setup is required.".format(self.path)) if schema is not None and schema.setup_files: for file_path in schema.setup_files: getLogger().debug("Executing script file: {}".format(file_path)) exe.cur.executescript(self.read_file(file_path)) if schema.setup_scripts: for script in schema.setup_scripts: exe.cur.executescript(script) return exe
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier conditional_expression identifier comparison_operator identifier none attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement boolean_operator not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier comparison_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer block expression_statement call attribute call identifier argument_list identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier if_statement boolean_operator comparison_operator identifier none attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute call identifier argument_list identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier if_statement attribute identifier identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier
Create a context to execute queries
def create(cls, data=None, api_key=None, endpoint=None, add_headers=None, **kwargs): cls.validate(data) inst = cls(api_key=api_key) endpoint = '' return inst.request('POST', endpoint=endpoint, data=data, query_params=kwargs, add_headers=add_headers, )
module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier string string_start string_end return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Create an event on your PagerDuty account.
def template_to_text(tmpl, debug=0): tarr = [] for item in tmpl.itertext(): tarr.append(item) text = "{{%s}}" % "|".join(tarr).strip() if debug > 1: print("+ template_to_text:") print(" %s" % text) return text
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator string string_start string_content string_end call attribute call attribute string string_start string_content string_end identifier argument_list identifier identifier argument_list if_statement comparison_operator identifier integer block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement identifier
convert parse tree template to text
def delete_policy(self, pol_id): if pol_id not in self.policies: LOG.error("Invalid policy %s", pol_id) return del self.policies[pol_id] self.policy_cnt -= 1
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement delete_statement subscript attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier integer
Deletes the policy from the local dictionary.
def sbo_list(): sbo_packages = [] for pkg in os.listdir(_meta_.pkg_path): if pkg.endswith("_SBo"): sbo_packages.append(pkg) return sbo_packages
module function_definition identifier parameters block expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Return all SBo packages
def bech32_polymod(values): generator = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3] chk = 1 for value in values: top = chk >> 25 chk = (chk & 0x1ffffff) << 5 ^ value for i in range(5): chk ^= generator[i] if ((top >> i) & 1) else 0 return chk
module function_definition identifier parameters identifier block expression_statement assignment identifier list integer integer integer integer integer expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator binary_operator parenthesized_expression binary_operator identifier integer integer identifier for_statement identifier call identifier argument_list integer block expression_statement augmented_assignment identifier conditional_expression subscript identifier identifier parenthesized_expression binary_operator parenthesized_expression binary_operator identifier identifier integer integer return_statement identifier
Internal function that computes the Bech32 checksum.
def process_format(self, kind, context): result = None while True: chunk = yield result if chunk is None: return split = -1 line = chunk.line try: ast.parse(line) except SyntaxError as e: split = line.rfind(' ', 0, e.offset) result = chunk.clone(line='_bless(' + line[:split].rstrip() + ').format(' + line[split:].lstrip() + ')')
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier none while_statement true block expression_statement assignment identifier yield identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier unary_operator integer expression_statement assignment identifier attribute identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end call attribute subscript identifier slice identifier identifier argument_list string string_start string_content string_end call attribute subscript identifier slice identifier identifier argument_list string string_start string_content string_end
Handle transforming format string + arguments into Python code.
def _parse_service_env_vars(self, env_vars): env = {} for var in env_vars: k, v = var.split('=') env.update({k: v}) return env
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list dictionary pair identifier identifier return_statement identifier
Return a dict based on `key=value` pair strings.
def setRepoData(self, searchString, category="", extension="", math=False, game=False, searchFiles=False): self.searchString = searchString self.category = category self.math = math self.game = game self.searchFiles = searchFiles self.extension = extension
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier false default_parameter identifier false default_parameter identifier false block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier
Call this function with all the settings to use for future operations on a repository, must be called FIRST
def locale_escape(string, errors='replace'): encoding = locale.getpreferredencoding() string = string.encode(encoding, errors).decode('utf8') return string
module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list string string_start string_content string_end return_statement identifier
Mangle non-supported characters, for savages with ascii terminals.
def compute(self): self._compute_window_size() smooth = [] residual = [] x, y = self.x, self.y self._update_values_in_window() self._update_mean_in_window() self._update_variance_in_window() for i, (xi, yi) in enumerate(zip(x, y)): if ((i - self._neighbors_on_each_side) > 0.0 and (i + self._neighbors_on_each_side) < len(x)): self._advance_window() smooth_here = self._compute_smooth_during_construction(xi) residual_here = self._compute_cross_validated_residual_here(xi, yi, smooth_here) smooth.append(smooth_here) residual.append(residual_here) self._store_unsorted_results(smooth, residual)
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier list expression_statement assignment identifier list expression_statement assignment pattern_list identifier identifier expression_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list call identifier argument_list identifier identifier block if_statement parenthesized_expression boolean_operator comparison_operator parenthesized_expression binary_operator identifier attribute identifier identifier float comparison_operator parenthesized_expression binary_operator identifier attribute identifier identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier 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 identifier
Perform the smoothing operations.
def resource_urls(request): url_parsed = urlparse(settings.SEARCH_URL) defaults = dict( APP_NAME=__description__, APP_VERSION=__version__, SITE_URL=settings.SITE_URL.rstrip('/'), SEARCH_TYPE=settings.SEARCH_TYPE, SEARCH_URL=settings.SEARCH_URL, SEARCH_IP='%s://%s:%s' % (url_parsed.scheme, url_parsed.hostname, url_parsed.port) ) return defaults
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier return_statement identifier
Global values to pass to templates
def find(self, path, all=False): try: start, _, extn = path.rsplit('.', 2) except ValueError: return [] path = '.'.join((start, extn)) return find(path, all=all) or []
module function_definition identifier parameters identifier identifier default_parameter identifier false block try_statement block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end integer except_clause identifier block return_statement list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple identifier identifier return_statement boolean_operator call identifier argument_list identifier keyword_argument identifier identifier list
Work out the uncached name of the file and look that up instead
def _is_valid_id(self, inpt): from dlkit.abstract_osid.id.primitives import Id as abc_id if isinstance(inpt, abc_id): return True else: return False
module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier identifier aliased_import dotted_name identifier identifier if_statement call identifier argument_list identifier identifier block return_statement true else_clause block return_statement false
Checks if input is a valid Id
def workbook_data(self): document = XML( fn=os.path.splitext(self.fn)[0]+'.xml', root=Element.workbook()) shared_strings = [ str(t.text) for t in self.xml('xl/sharedStrings.xml') .root.xpath(".//xl:t", namespaces=self.NS)] for key in self.sheets.keys(): worksheet = self.sheets[key].transform(XT, shared_strings=shared_strings) document.root.append(worksheet.root) return document
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier binary_operator subscript call attribute attribute identifier identifier identifier argument_list attribute identifier identifier integer string string_start string_content string_end keyword_argument identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension call identifier argument_list attribute identifier identifier for_in_clause identifier call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute subscript attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement identifier
return a readable XML form of the data.
def _get_manifest_list(self, image): if image in self.manifest_list_cache: return self.manifest_list_cache[image] manifest_list = get_manifest_list(image, image.registry, insecure=self.parent_registry_insecure, dockercfg_path=self.parent_registry_dockercfg_path) if '@sha256:' in str(image) and not manifest_list: image = image.copy() try: config_blob = get_config_from_registry( image, image.registry, image.tag, insecure=self.parent_registry_insecure, dockercfg_path=self.parent_registry_dockercfg_path ) except (HTTPError, RetryError, Timeout) as ex: self.log.warning('Unable to fetch config for %s, got error %s', image, ex.response.status_code) raise RuntimeError('Unable to fetch config for base image') release = config_blob['config']['Labels']['release'] version = config_blob['config']['Labels']['version'] docker_tag = "%s-%s" % (version, release) image.tag = docker_tag manifest_list = get_manifest_list(image, image.registry, insecure=self.parent_registry_insecure, dockercfg_path=self.parent_registry_dockercfg_path) self.manifest_list_cache[image] = manifest_list return self.manifest_list_cache[image]
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement subscript attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier if_statement boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list identifier not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier except_clause as_pattern tuple identifier identifier identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier attribute attribute identifier identifier identifier raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript subscript subscript identifier 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 subscript subscript subscript identifier 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 binary_operator string string_start string_content string_end tuple identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement subscript attribute identifier identifier identifier
try to figure out manifest list
def created_slices(self, user_id=None): if not user_id: user_id = g.user.id Slice = models.Slice qry = ( db.session.query(Slice) .filter( sqla.or_( Slice.created_by_fk == user_id, Slice.changed_by_fk == user_id, ), ) .order_by(Slice.changed_on.desc()) ) payload = [{ 'id': o.id, 'title': o.slice_name, 'url': o.slice_url, 'dttm': o.changed_on, 'viz_type': o.viz_type, } for o in qry.all()] return json_success( json.dumps(payload, default=utils.json_int_dttm_ser))
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier parenthesized_expression call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list call attribute identifier identifier argument_list comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier list_comprehension dictionary 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 attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier for_in_clause identifier call attribute identifier identifier argument_list return_statement call identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier
List of slices created by this user
def regions(self): url = "%s/regions" % self.root params = {"f": "json"} return self._get(url=url, param_dict=params, proxy_url=self._proxy_url, proxy_port=self._proxy_port)
module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier
gets the regions value
def consume_queue(queue, cascade_stop): while True: try: item = queue.get(timeout=0.1) except Empty: yield None continue except thread.error: raise ShutdownException() if item.exc: raise item.exc if item.is_stop: if cascade_stop: raise StopIteration else: continue yield item.item
module function_definition identifier parameters identifier identifier block while_statement true block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier float except_clause identifier block expression_statement yield none continue_statement except_clause attribute identifier identifier block raise_statement call identifier argument_list if_statement attribute identifier identifier block raise_statement attribute identifier identifier if_statement attribute identifier identifier block if_statement identifier block raise_statement identifier else_clause block continue_statement expression_statement yield attribute identifier identifier
Consume the queue by reading lines off of it and yielding them.
def natsorted(seq, cmp=natcmp): "Returns a copy of seq, sorted by natural string sort." import copy temp = copy.copy(seq) natsort(temp, cmp) return temp
module function_definition identifier parameters identifier default_parameter identifier identifier block expression_statement string string_start string_content string_end import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier identifier return_statement identifier
Returns a copy of seq, sorted by natural string sort.
def shape(self): try: return self.__shape except AttributeError: shape = tuple(len(vec) for vec in self.coord_vectors) self.__shape = shape return shape
module function_definition identifier parameters identifier block try_statement block return_statement attribute identifier identifier except_clause identifier block expression_statement assignment identifier call identifier generator_expression call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier
Number of grid points per axis.
def tcp_server(tcp_addr, settings): family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP) sock.bind(tcp_addr) sock.listen(1) logging.info("Waiting for connection on %s", tcp_addr) conn, addr = sock.accept() logging.info("Accepted connection from %s", Addr(*addr)) write_tcp(conn, settings["map_data"]) send_settings = {k: v for k, v in settings.items() if k != "map_data"} logging.debug("settings: %s", send_settings) write_tcp(conn, json.dumps(send_settings).encode()) return conn
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list list_splat identifier expression_statement call identifier argument_list identifier subscript identifier string string_start string_content string_end 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 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 call identifier argument_list identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list return_statement identifier
Start up the tcp server, send the settings.
def dry(self, *args, **kwargs): return 'Would have executed:\n%s%s' % ( self.name, Args(self.spec).explain(*args, **kwargs))
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement binary_operator string string_start string_content escape_sequence string_end tuple attribute identifier identifier call attribute call identifier argument_list attribute identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier
Perform a dry-run of the task
def stop_video_recording(self): self.runner.info_log("Stopping video recording...") self.execute_command("./stop_recording.sh") sleep(5) self.scp_file_remote_to_local( self.remote_video_recording_file_path, self.local_video_recording_file_path )
module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier 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 expression_statement call identifier argument_list integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier
Stop the video recording
def asyncStarMap(asyncCallable, iterable): deferreds = starmap(asyncCallable, iterable) return gatherResults(deferreds, consumeErrors=True)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier true
itertools.starmap for deferred callables
def save(self, *args, **kwargs): if self.created is None: self.created = tz_now() if self.modified is None: self.modified = self.created super(Thread, self).save(*args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list_splat identifier dictionary_splat identifier
Fill 'created' and 'modified' attributes on first create
def _clean_fields(allowed_fields: dict, fields: FieldsParam) -> Iterable[str]: if fields == ALL: fields = allowed_fields.keys() else: fields = tuple(fields) unknown_fields = set(fields) - allowed_fields.keys() if unknown_fields: raise ValueError('Unknown fields: {}'.format(unknown_fields)) return fields
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block if_statement comparison_operator identifier 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 assignment identifier binary_operator call identifier argument_list identifier call attribute identifier identifier argument_list if_statement identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier
Clean lookup fields and check for errors.
def validateFilepath( self ): if ( not self.isValidated() ): return valid = self.isValid() if ( not valid ): fg = self.invalidForeground() bg = self.invalidBackground() else: fg = self.validForeground() bg = self.validBackground() palette = self.palette() palette.setColor(palette.Base, bg) palette.setColor(palette.Text, fg) self._filepathEdit.setPalette(palette)
module function_definition identifier parameters identifier block if_statement parenthesized_expression not_operator call attribute identifier identifier argument_list block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list if_statement parenthesized_expression not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Alters the color scheme based on the validation settings.
def topic_path(cls, project, topic): return google.api_core.path_template.expand( "projects/{project}/topics/{topic}", project=project, topic=topic )
module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier
Return a fully-qualified topic string.
def np2model_tensor(a): "Tranform numpy array `a` to a tensor of the same type." dtype = model_type(a.dtype) res = as_tensor(a) if not dtype: return res return res.type(dtype)
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block return_statement identifier return_statement call attribute identifier identifier argument_list identifier
Tranform numpy array `a` to a tensor of the same type.
def And(*args: Union[Bool, bool]) -> Bool: union = [] args_list = [arg if isinstance(arg, Bool) else Bool(arg) for arg in args] for arg in args_list: union.append(arg.annotations) return Bool(z3.And([a.raw for a in args_list]), union)
module function_definition identifier parameters typed_parameter list_splat_pattern identifier type generic_type identifier type_parameter type identifier type identifier type identifier block expression_statement assignment identifier list expression_statement assignment identifier list_comprehension conditional_expression identifier call identifier argument_list identifier identifier call identifier argument_list identifier for_in_clause identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement call identifier argument_list call attribute identifier identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier identifier identifier
Create an And expression.
def queue_resize(self): self._children_resize_queued = True parent = getattr(self, "parent", None) if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"): parent.queue_resize()
module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement boolean_operator boolean_operator identifier call identifier argument_list identifier attribute identifier identifier call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list
request the element to re-check it's child sprite sizes
def client_list_entries_multi_project( client, to_delete ): PROJECT_IDS = ["one-project", "another-project"] for entry in client.list_entries(project_ids=PROJECT_IDS): do_something_with(entry)
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier identifier block expression_statement call identifier argument_list identifier
List entries via client across multiple projects.
def strict_logical(self, value): if value is not None: if not isinstance(value, bool): raise TypeError( 'f90nml: error: strict_logical must be a logical value.') else: self._strict_logical = value
module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment attribute identifier identifier identifier
Validate and set the strict logical flag.
def _distance_stats_sqr_fast_generic(x, y, dcov_function): covariance_xy_sqr = dcov_function(x, y) variance_x_sqr = dcov_function(x, x) variance_y_sqr = dcov_function(y, y) denominator_sqr_signed = variance_x_sqr * variance_y_sqr denominator_sqr = np.absolute(denominator_sqr_signed) denominator = _sqrt(denominator_sqr) if denominator == 0.0: correlation_xy_sqr = denominator.dtype.type(0) else: correlation_xy_sqr = covariance_xy_sqr / denominator return Stats(covariance_xy=covariance_xy_sqr, correlation_xy=correlation_xy_sqr, variance_x=variance_x_sqr, variance_y=variance_y_sqr)
module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier float block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer else_clause block expression_statement assignment identifier binary_operator identifier identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Compute the distance stats using the fast algorithm.
def save(self, resq=None): if not resq: resq = ResQ() data = { 'failed_at' : datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), 'payload' : self._payload, 'exception' : self._exception.__class__.__name__, 'error' : self._parse_message(self._exception), 'backtrace' : self._parse_traceback(self._traceback), 'queue' : self._queue } if self._worker: data['worker'] = self._worker data = ResQ.encode(data) resq.redis.rpush('resque:failed', data)
module function_definition identifier parameters identifier default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier
Saves the failed Job into a "failed" Redis queue preserving all its original enqueud info.
def google_get_data(self, config, response): params = { 'access_token': response['access_token'], } payload = urlencode(params) url = self.google_api_url + 'userinfo?' + payload req = Request(url) 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 subscript identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list 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 profile data for the user.
def contains_circle(self, pt, radius): return (self.l < pt.x - radius and self.r > pt.x + radius and self.t < pt.y - radius and self.b > pt.y + radius)
module function_definition identifier parameters identifier identifier identifier block return_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator attribute identifier identifier binary_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier binary_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier binary_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier binary_operator attribute identifier identifier identifier
Is the circle completely inside this rect?
def colorize(self, string, rgb=None, ansi=None, bg=None, ansi_bg=None): if not isinstance(string, str): string = str(string) if rgb is None and ansi is None: raise TerminalColorMapException( 'colorize: must specify one named parameter: rgb or ansi') if rgb is not None and ansi is not None: raise TerminalColorMapException( 'colorize: must specify only one named parameter: rgb or ansi') if bg is not None and ansi_bg is not None: raise TerminalColorMapException( 'colorize: must specify only one named parameter: bg or ansi_bg') if rgb is not None: (closestAnsi, closestRgb) = self.convert(rgb) elif ansi is not None: (closestAnsi, closestRgb) = (ansi, self.colors[ansi]) if bg is None and ansi_bg is None: return "\033[38;5;{ansiCode:d}m{string:s}\033[0m".format(ansiCode=closestAnsi, string=string) if bg is not None: (closestBgAnsi, unused) = self.convert(bg) elif ansi_bg is not None: (closestBgAnsi, unused) = (ansi_bg, self.colors[ansi_bg]) return "\033[38;5;{ansiCode:d}m\033[48;5;{bf:d}m{string:s}\033[0m".format(ansiCode=closestAnsi, bf=closestBgAnsi, string=string)
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier none block expression_statement assignment tuple_pattern identifier identifier tuple identifier subscript attribute identifier identifier identifier if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block return_statement call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier if_statement comparison_operator identifier none block expression_statement assignment tuple_pattern identifier identifier call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier none block expression_statement assignment tuple_pattern identifier identifier tuple identifier subscript attribute identifier identifier identifier return_statement call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier
Returns the colored string
def to_json(self, *args, **kwargs): return json.dumps(self.serialize(), *args, **kwargs)
module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier
Convert Entity to JSON.
def contains_one_of(*fields): message = 'Must contain any one of the following fields: {0}'.format(', '.join(fields)) def check_contains(endpoint_fields): for field in fields: if field in endpoint_fields: return errors = {} for field in fields: errors[field] = 'one of these must have a value' return errors check_contains.__doc__ = message return check_contains
module function_definition identifier parameters list_splat_pattern identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier function_definition identifier parameters identifier block for_statement identifier identifier block if_statement comparison_operator identifier identifier block return_statement expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment subscript identifier identifier string string_start string_content string_end return_statement identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier
Enables ensuring that one of multiple optional fields is set
def publish(self, distribution, storage=""): try: return self._publishes[distribution] except KeyError: self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.storage)) return self._publishes[distribution]
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block try_statement block return_statement subscript attribute identifier identifier identifier except_clause identifier block expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier parenthesized_expression boolean_operator identifier attribute identifier identifier return_statement subscript attribute identifier identifier identifier
Get or create publish
def _explain(self, tree): self._explaining = True self._call_list = [] old_call = self.connection.call def fake_call(command, **kwargs): if command == "describe_table": return old_call(command, **kwargs) self._call_list.append((command, kwargs)) raise ExplainSignal self.connection.call = fake_call try: ret = self._run(tree[1]) try: list(ret) except TypeError: pass finally: self.connection.call = old_call self._explaining = False
module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier list expression_statement assignment identifier attribute attribute identifier identifier identifier function_definition identifier parameters identifier dictionary_splat_pattern identifier block if_statement comparison_operator identifier string string_start string_content string_end block return_statement call identifier argument_list identifier dictionary_splat identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier raise_statement identifier expression_statement assignment attribute attribute identifier identifier identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier integer try_statement block expression_statement call identifier argument_list identifier except_clause identifier block pass_statement finally_clause block expression_statement assignment attribute attribute identifier identifier identifier identifier expression_statement assignment attribute identifier identifier false
Set up the engine to do a dry run of a query
def create(pid_type, pid_value, status, object_type, object_uuid): from .models import PersistentIdentifier if bool(object_type) ^ bool(object_uuid): raise click.BadParameter('Speficy both or any of --type and --uuid.') new_pid = PersistentIdentifier.create( pid_type, pid_value, status=status, object_type=object_type, object_uuid=object_uuid, ) db.session.commit() click.echo( '{0.pid_type} {0.pid_value} {0.pid_provider}'.format(new_pid) )
module function_definition identifier parameters identifier identifier identifier identifier identifier block import_from_statement relative_import import_prefix dotted_name identifier dotted_name identifier if_statement binary_operator call identifier argument_list identifier call identifier argument_list identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier
Create new persistent identifier.
def disable_hidden_api_blacklist(self): version_codename = self._ad.adb.getprop('ro.build.version.codename') sdk_version = int(self._ad.adb.getprop('ro.build.version.sdk')) if self._ad.is_rootable and (sdk_version >= 28 or version_codename == 'P'): self._ad.adb.shell( 'settings put global hidden_api_blacklist_exemptions "*"')
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator attribute attribute identifier identifier identifier parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end
If necessary and possible, disables hidden api blacklist.
def reload(self): pid = self._read_pidfile() if pid is None or pid != os.getpid(): raise DaemonError( 'Daemon.reload() should only be called by the daemon process ' 'itself') new_environ = os.environ.copy() new_environ['DAEMONOCLE_RELOAD'] = 'true' subprocess.call( [sys.executable] + sys.argv, cwd=self._orig_workdir, env=new_environ) self._shutdown('Shutting down for reload')
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator identifier none comparison_operator identifier call attribute identifier identifier argument_list block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator list attribute identifier identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end
Make the daemon reload itself.
def _save_settings(self): if self._autosettings_path == None: return gui_settings_dir = _os.path.join(_cwd, 'egg_settings') if not _os.path.exists(gui_settings_dir): _os.mkdir(gui_settings_dir) path = _os.path.join(gui_settings_dir, self._autosettings_path) settings = _g.QtCore.QSettings(path, _g.QtCore.QSettings.IniFormat) settings.clear() if hasattr_safe(self._window, "saveState"): settings.setValue('State',self._window.saveState()) settings.setValue('Geometry', self._window.saveGeometry())
module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute attribute attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list if_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list
Saves all the parameters to a text file.
def append(self, child): if not (isinstance(child, CP2KSection) or isinstance(child, CP2KKeyword)): raise TypeError("The child must be a CP2KSection or a CP2KKeyword, got: %s." % child) l = self.__index.setdefault(child.name, []) l.append(child) self.__order.append(child)
module function_definition identifier parameters identifier identifier block if_statement not_operator parenthesized_expression boolean_operator call identifier argument_list identifier identifier call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier
Add a child section or keyword
def mean_se(series, mult=1): m = np.mean(series) se = mult * np.sqrt(np.var(series) / len(series)) return pd.DataFrame({'y': [m], 'ymin': m-se, 'ymax': m+se})
module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end list identifier pair string string_start string_content string_end binary_operator identifier identifier pair string string_start string_content string_end binary_operator identifier identifier
Calculate mean and standard errors on either side
def uninitialize(cls) -> None: if not cls._initialized: return signal.signal(signal.SIGCHLD, cls._old_sigchld) cls._initialized = False
module function_definition identifier parameters identifier type none block if_statement not_operator attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier false
Removes the ``SIGCHLD`` handler.
async def upcoming(self, details: bool = False) -> list: endpoint = 'dailystats' key = 'DailyStats' if details: endpoint += '/details' key = 'DailyStatsDetails' data = await self._request('get', endpoint) return data[key]
module function_definition identifier parameters identifier typed_default_parameter identifier type identifier false type identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_statement identifier block expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier await call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement subscript identifier identifier
Return watering statistics for the next 6 days.
def _parse_date_input(date_input, default_offset=0): if date_input: try: return parse_date_input(date_input) except ValueError as err: raise CommandError(force_text(err)) else: return get_midnight() - timedelta(days=default_offset)
module function_definition identifier parameters identifier default_parameter identifier integer block if_statement identifier block try_statement block return_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call identifier argument_list identifier else_clause block return_statement binary_operator call identifier argument_list call identifier argument_list keyword_argument identifier identifier
Parses a date input.
def pandoc_process(app, what, name, obj, options, lines): if not lines: return None input_format = app.config.mkdsupport_use_parser output_format = 'rst' text = SEP.join(lines) text = pypandoc.convert_text(text, output_format, format=input_format) del lines[:] lines.extend(text.split(SEP))
module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement not_operator identifier block return_statement none expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier delete_statement subscript identifier slice expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier
Convert docstrings in Markdown into reStructureText using pandoc
def _get(self, q, params=''): if (q[-1] == '/'): q = q[:-1] headers = {'Content-Type': 'application/json'} r = requests.get('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params), headers=headers) ret = DotDict(r.json()) if (not r.ok or ('error' in ret and ret.error == True)): raise Exception(r.url, r.reason, r.status_code, r.json()) return DotDict(r.json())
module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_end block if_statement parenthesized_expression comparison_operator subscript identifier unary_operator integer string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end 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 attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement parenthesized_expression boolean_operator not_operator attribute identifier identifier parenthesized_expression boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator attribute identifier identifier true block raise_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list return_statement call identifier argument_list call attribute identifier identifier argument_list
Generic GET wrapper including the api_key
def close(self): "Stop the output stream, but further download will still perform" if self.stream: self.stream.close(self.scheduler) self.stream = None
module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier none
Stop the output stream, but further download will still perform
def numpy_to_texture(image): if not isinstance(image, np.ndarray): raise TypeError('Unknown input type ({})'.format(type(image))) if image.ndim != 3 or image.shape[2] != 3: raise AssertionError('Input image must be nn by nm by RGB') grid = vtki.UniformGrid((image.shape[1], image.shape[0], 1)) grid.point_arrays['Image'] = np.flip(image.swapaxes(0,1), axis=1).reshape((-1, 3), order='F') grid.set_active_scalar('Image') return image_to_texture(grid)
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator subscript attribute identifier identifier integer integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list tuple subscript attribute identifier identifier integer subscript attribute identifier identifier integer integer expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer integer keyword_argument identifier integer identifier argument_list tuple unary_operator integer integer 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 return_statement call identifier argument_list identifier
Convert a NumPy image array to a vtk.vtkTexture
def load(cls, keys): conversations = [] for key in keys: conversation = unitdata.kv().get(key) if conversation: conversations.append(cls.deserialize(conversation)) return conversations
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier
Load a set of conversations by their keys.
def s3_get(url: str, temp_file: IO) -> None: s3_resource = boto3.resource("s3") bucket_name, s3_path = split_s3_path(url) s3_resource.Bucket(bucket_name).download_fileobj(s3_path, temp_file)
module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type none block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier identifier
Pull a file directly from S3.
def pull_from_origin(repo_path): LOG.info("Pulling from origin at %s." % repo_path) command = GIT_PULL_CMD.format(repo_path) resp = envoy.run(command) if resp.status_code != 0: LOG.exception("Pull failed.") raise GitException(resp.std_err) else: LOG.info("Pull successful.")
module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement call identifier argument_list attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end
Execute 'git pull' at the provided repo_path.
def _change_volume(self, increase): sign = "+" if increase else "-" delta = "%d%%%s" % (self.volume_tick, sign) self._run(["amixer", "-q", "sset", "Master", delta])
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list list 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 identifier
Change volume using amixer
def saveProfile( self ): manager = self.parent() prof = manager.currentProfile() save_prof = manager.viewWidget().saveProfile() prof.setXmlElement(save_prof.xmlElement())
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list
Saves the current profile to the current settings from the view widget.
async def async_discovery(session): bridges = [] response = await async_request(session.get, URL_DISCOVER) if not response: _LOGGER.info("No discoverable bridges available.") return bridges for bridge in response: bridges.append({'bridgeid': bridge['id'], 'host': bridge['internalipaddress'], 'port': bridge['internalport']}) _LOGGER.info("Discovered the following bridges: %s.", bridges) return bridges
module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier await call identifier argument_list attribute identifier identifier identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list 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 pair string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier
Find bridges allowing gateway discovery.
def _getTypename(self, defn): return 'REAL' if defn.type.float or 'TIME' in defn.type.name or defn.dntoeu else 'INTEGER'
module function_definition identifier parameters identifier identifier block return_statement conditional_expression string string_start string_content string_end boolean_operator boolean_operator attribute attribute identifier identifier identifier comparison_operator string string_start string_content string_end attribute attribute identifier identifier identifier attribute identifier identifier string string_start string_content string_end
Returns the SQL typename required to store the given FieldDefinition
def raise_msg_to_str(msg): if not is_string_like(msg): msg = '\n'.join(map(str, msg)) return msg
module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier block expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list call identifier argument_list identifier identifier return_statement identifier
msg is a return arg from a raise. Join with new lines
def main(): options = handle_options() elecs, d_obs = readin_volt(options.d_obs) elecs, d_est = readin_volt(options.d_est) elecs, d_estTC = readin_volt(options.d_estTC) volt_corr = calc_correction(d_obs, d_est, d_estTC, ) save_volt(elecs, volt_corr, options.output, )
module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list identifier identifier attribute identifier identifier
Function to remove temperature effect from field data
def read_epilogue(self): with open(self.filename, "rb") as fp_: fp_.seek(self.mda['total_header_length']) data = np.fromfile(fp_, dtype=hrit_epilogue, count=1) self.epilogue.update(recarray2dict(data))
module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier
Read the epilogue metadata.
def _merge_cluster(old, new): logger.debug("_merge_cluster: %s to %s" % (old.id, new.id)) logger.debug("_merge_cluster: add idls %s" % old.loci2seq.keys()) for idl in old.loci2seq: new.add_id_member(old.loci2seq[idl], idl) return new
module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier identifier return_statement identifier
merge one cluster to another
def create(self): data = self._node_data() data["node_id"] = self._id if self._node_type == "docker": timeout = None else: timeout = 1200 trial = 0 while trial != 6: try: response = yield from self._compute.post("/projects/{}/{}/nodes".format(self._project.id, self._node_type), data=data, timeout=timeout) except ComputeConflict as e: if e.response.get("exception") == "ImageMissingError": res = yield from self._upload_missing_image(self._node_type, e.response["image"]) if not res: raise e else: raise e else: yield from self.parse_node_response(response.json) return True trial += 1
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier none else_clause block expression_statement assignment identifier integer expression_statement assignment identifier integer while_statement comparison_operator identifier integer block try_statement block expression_statement assignment identifier yield call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute attribute identifier identifier identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier yield call attribute identifier identifier argument_list attribute identifier identifier subscript attribute identifier identifier string string_start string_content string_end if_statement not_operator identifier block raise_statement identifier else_clause block raise_statement identifier else_clause block expression_statement yield call attribute identifier identifier argument_list attribute identifier identifier return_statement true expression_statement augmented_assignment identifier integer
Create the node on the compute server
def resume(self, data): 'Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object' if not hasattr(data, 'read'): data = six.BytesIO(data) if self.size == -1: log.debug('%r is an incomplete file, but .size is unknown. Refreshing the file object from server', self.path) self.f = self.jfs.get(self.path) md5 = calculate_md5(data) if md5 != self.md5: raise JFSError() log.debug('Resuming %s from offset %s', self.path, self.size) return self.jfs.up(self.path, data, resume_offset=self.size)
module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier unary_operator integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier
Resume uploading an incomplete file, after a previous upload was interrupted. Returns new file object
def GetUnreachableHosts(hostnames, ssh_key): ssh_status = AreHostsReachable(hostnames, ssh_key) assert(len(hostnames) == len(ssh_status)) nonresponsive_hostnames = [host for (host, ssh_ok) in zip(hostnames, ssh_status) if not ssh_ok] return nonresponsive_hostnames
module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier assert_statement parenthesized_expression comparison_operator call identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause tuple_pattern identifier identifier call identifier argument_list identifier identifier if_clause not_operator identifier return_statement identifier
Returns list of hosts unreachable via ssh.
def server_list_min(self): nt_ks = self.compute_conn ret = {} for item in nt_ks.servers.list(detailed=False): try: ret[item.name] = { 'id': item.id, 'state': 'Running' } except TypeError: pass return ret
module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier dictionary for_statement identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false block try_statement block expression_statement assignment subscript identifier attribute identifier identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end except_clause identifier block pass_statement return_statement identifier
List minimal information about servers
def poll_for_server_running(job_id): sys.stdout.write('Waiting for server in {0} to initialize ...'.format(job_id)) sys.stdout.flush() desc = dxpy.describe(job_id) while(SERVER_READY_TAG not in desc['tags'] and desc['state'] != 'failed'): time.sleep(SLEEP_PERIOD) sys.stdout.write('.') sys.stdout.flush() desc = dxpy.describe(job_id) if desc['state'] == 'failed': msg = RED('Error:') + ' Server failed to run.\n' msg += 'You may want to check the job logs by running:' msg += BOLD('dx watch {0}'.format(job_id)) err_exit(msg)
module function_definition identifier parameters identifier block 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 attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier while_statement parenthesized_expression boolean_operator comparison_operator identifier subscript identifier string string_start string_content string_end comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end string string_start string_content escape_sequence string_end expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement augmented_assignment identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier
Poll for the job to start running and post the SERVER_READY_TAG.
def application_unauthenticated(request, token, state=None, label=None): application = base.get_application(secret_token=token) if application.expires < datetime.datetime.now(): return render( template_name='kgapplications/common_expired.html', context={'application': application}, request=request) roles = {'is_applicant', 'is_authorised'} if request.user.is_authenticated: if request.user == application.applicant: url = base.get_url( request, application, roles, label) return HttpResponseRedirect(url) state_machine = base.get_state_machine(application) return state_machine.process( request, application, state, label, roles)
module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier call attribute attribute identifier identifier identifier argument_list block return_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end identifier keyword_argument identifier identifier expression_statement assignment identifier set string string_start string_content string_end string string_start string_content string_end if_statement attribute attribute identifier identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier return_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier
An somebody is trying to access an application.
def _encode_mapping(name, value, check_keys, opts): data = b"".join([_element_to_bson(key, val, check_keys, opts) for key, val in iteritems(value)]) return b"\x03" + name + _PACK_INT(len(data) + 5) + data + b"\x00"
module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute string string_start string_end identifier argument_list list_comprehension call identifier argument_list identifier identifier identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier return_statement binary_operator binary_operator binary_operator binary_operator string string_start string_content escape_sequence string_end identifier call identifier argument_list binary_operator call identifier argument_list identifier integer identifier string string_start string_content escape_sequence string_end
Encode a mapping type.
def clean_docstring(docstring): docstring = docstring.strip() if '\n' in docstring: if docstring[0].isspace(): return textwrap.dedent(docstring) else: first, _, rest = docstring.partition('\n') return first + '\n' + textwrap.dedent(rest) return docstring
module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator string string_start string_content escape_sequence string_end identifier block if_statement call attribute subscript identifier integer identifier argument_list block return_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end return_statement binary_operator binary_operator identifier string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list identifier return_statement identifier
Dedent docstring, special casing the first line.
def _skip(options): values = [options.missing_direct_deps, options.unnecessary_deps] return all(v == 'off' for v in values)
module function_definition identifier parameters identifier block expression_statement assignment identifier list attribute identifier identifier attribute identifier identifier return_statement call identifier generator_expression comparison_operator identifier string string_start string_content string_end for_in_clause identifier identifier
Return true if the task should be entirely skipped, and thus have no product requirements.
def close(self): if self.read_option('save_pointer'): self._update_last_pointer() super(S3Writer, self).close()
module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list
Called to clean all possible tmp files created during the process.
def shutdown(self) -> None: self._is_handshake_completed = False try: self._flush_ssl_engine() except IOError: pass try: self._ssl.shutdown() except OpenSSLError as e: if 'SSL_shutdown:uninitialized' not in str(e) and 'shutdown while in init' not in str(e): raise if self._sock: self._sock.close()
module function_definition identifier parameters identifier type none block expression_statement assignment attribute identifier identifier false try_statement block expression_statement call attribute identifier identifier argument_list except_clause identifier block pass_statement try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end call identifier argument_list identifier comparison_operator string string_start string_content string_end call identifier argument_list identifier block raise_statement if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list
Close the TLS connection and the underlying network socket.
def verifymessage(self, address, signature, message): return self.req("verifymessage", [address, signature, message])
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 list identifier identifier identifier
Verify a signed message.
def tar_and_copy_usr_dir(usr_dir, train_dir): tf.logging.info("Tarring and pushing t2t_usr_dir.") usr_dir = os.path.abspath(os.path.expanduser(usr_dir)) top_dir = os.path.join(tempfile.gettempdir(), "t2t_usr_container") tmp_usr_dir = os.path.join(top_dir, usr_dir_lib.INTERNAL_USR_DIR_PACKAGE) shutil.rmtree(top_dir, ignore_errors=True) shutil.copytree(usr_dir, tmp_usr_dir) top_setup_fname = os.path.join(top_dir, "setup.py") setup_file_str = get_setup_file( name="DummyUsrDirPackage", packages=get_requirements(usr_dir) ) with tf.gfile.Open(top_setup_fname, "w") as f: f.write(setup_file_str) usr_tar = _tar_and_copy(top_dir, train_dir) return usr_tar
module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier true expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier call identifier argument_list identifier with_statement with_clause with_item as_pattern call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement identifier
Package, tar, and copy usr_dir to GCS train_dir.
def file_length(in_file): fid = open(in_file) data = fid.readlines() fid.close() return len(data)
module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list return_statement call identifier argument_list identifier
Function to return the length of a file.
def scoped_connection(func): def _with(series, *args, **kwargs): connection = None try: connection = series._connection() return func(series, connection, *args, **kwargs) finally: series._return( connection ) return _with
module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier none try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list return_statement call identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier finally_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier
Decorator that gives out connections.
def rar3_type(btype): if btype < rf.RAR_BLOCK_MARK or btype > rf.RAR_BLOCK_ENDARC: return "*UNKNOWN*" return block_strs[btype - rf.RAR_BLOCK_MARK]
module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier block return_statement string string_start string_content string_end return_statement subscript identifier binary_operator identifier attribute identifier identifier
RAR3 type code as string.