code
stringlengths
75
104k
code_sememe
stringlengths
47
309k
token_type
stringlengths
215
214k
code_dependency
stringlengths
75
155k
def array_stack(arrays): """Stack arrays""" shapes = np.array([a.shape for a in arrays]) if not np.all(np.roll(shapes[:, 1:], 1, axis=0) == shapes[:, 1:]): raise ValueError( "All input arrays must have the same height and width for this mode" ) width = arrays[0].shape[-1] height = arrays[0].shape[-2] return np.array([a for subarray in arrays for a in subarray]).reshape( shapes[:, 0].sum(), height, width )
def function[array_stack, parameter[arrays]]: constant[Stack arrays] variable[shapes] assign[=] call[name[np].array, parameter[<ast.ListComp object at 0x7da1b07b9ba0>]] if <ast.UnaryOp object at 0x7da1b07b9fc0> begin[:] <ast.Raise object at 0x7da1b07b9600> variable[width] assign[=] call[call[name[arrays]][constant[0]].shape][<ast.UnaryOp object at 0x7da1b07baa40>] variable[height] assign[=] call[call[name[arrays]][constant[0]].shape][<ast.UnaryOp object at 0x7da1b07b9840>] return[call[call[name[np].array, parameter[<ast.ListComp object at 0x7da1b07b8130>]].reshape, parameter[call[call[name[shapes]][tuple[[<ast.Slice object at 0x7da1b07bb2e0>, <ast.Constant object at 0x7da1b07b98a0>]]].sum, parameter[]], name[height], name[width]]]]
keyword[def] identifier[array_stack] ( identifier[arrays] ): literal[string] identifier[shapes] = identifier[np] . identifier[array] ([ identifier[a] . identifier[shape] keyword[for] identifier[a] keyword[in] identifier[arrays] ]) keyword[if] keyword[not] identifier[np] . identifier[all] ( identifier[np] . identifier[roll] ( identifier[shapes] [:, literal[int] :], literal[int] , identifier[axis] = literal[int] )== identifier[shapes] [:, literal[int] :]): keyword[raise] identifier[ValueError] ( literal[string] ) identifier[width] = identifier[arrays] [ literal[int] ]. identifier[shape] [- literal[int] ] identifier[height] = identifier[arrays] [ literal[int] ]. identifier[shape] [- literal[int] ] keyword[return] identifier[np] . identifier[array] ([ identifier[a] keyword[for] identifier[subarray] keyword[in] identifier[arrays] keyword[for] identifier[a] keyword[in] identifier[subarray] ]). identifier[reshape] ( identifier[shapes] [:, literal[int] ]. identifier[sum] (), identifier[height] , identifier[width] )
def array_stack(arrays): """Stack arrays""" shapes = np.array([a.shape for a in arrays]) if not np.all(np.roll(shapes[:, 1:], 1, axis=0) == shapes[:, 1:]): raise ValueError('All input arrays must have the same height and width for this mode') # depends on [control=['if'], data=[]] width = arrays[0].shape[-1] height = arrays[0].shape[-2] return np.array([a for subarray in arrays for a in subarray]).reshape(shapes[:, 0].sum(), height, width)
def parse_package(package_string, arch_included=True): """Parse an RPM version string to get name, version, and arch Splits most (all tested) RPM version strings into name, epoch, version, release, and architecture. Epoch (also called serial) is an optional component of RPM versioning and is also optional in version strings provided to this function. RPM assumes the epoch to be 0 if it is not provided, so that behavior is mirrored here. **Deprecated** since version 0.2.0. Use :any:`rpm.package` instead. :param str package_string: an RPM version string of the form returned by the ``rpm -q`` command :param bool arch_included: default True - version strings may optionally be provided without the trailing architecture. If providing such strings, set this option to False :return: a dictionary with all parsed package information :rtype: dict """ # Yum sets epoch values to 0 if they are not specified logger.debug('parse_package(%s, %s)', package_string, arch_included) default_epoch = '0' arch = None if arch_included: char_list = list(package_string) arch = _pop_arch(char_list) package_string = ''.join(char_list) logger.debug('updated version_string: %s', package_string) try: name, epoch, version, release = _rpm_re.match(package_string).groups() except AttributeError: raise RpmError('Could not parse package string: %s' % package_string) if epoch == '' or epoch is None: epoch = default_epoch info = { 'name': name, 'EVR': (epoch, version, release), 'arch': arch } logger.debug('parsed information: %s', info) return info
def function[parse_package, parameter[package_string, arch_included]]: constant[Parse an RPM version string to get name, version, and arch Splits most (all tested) RPM version strings into name, epoch, version, release, and architecture. Epoch (also called serial) is an optional component of RPM versioning and is also optional in version strings provided to this function. RPM assumes the epoch to be 0 if it is not provided, so that behavior is mirrored here. **Deprecated** since version 0.2.0. Use :any:`rpm.package` instead. :param str package_string: an RPM version string of the form returned by the ``rpm -q`` command :param bool arch_included: default True - version strings may optionally be provided without the trailing architecture. If providing such strings, set this option to False :return: a dictionary with all parsed package information :rtype: dict ] call[name[logger].debug, parameter[constant[parse_package(%s, %s)], name[package_string], name[arch_included]]] variable[default_epoch] assign[=] constant[0] variable[arch] assign[=] constant[None] if name[arch_included] begin[:] variable[char_list] assign[=] call[name[list], parameter[name[package_string]]] variable[arch] assign[=] call[name[_pop_arch], parameter[name[char_list]]] variable[package_string] assign[=] call[constant[].join, parameter[name[char_list]]] call[name[logger].debug, parameter[constant[updated version_string: %s], name[package_string]]] <ast.Try object at 0x7da1b23b2c80> if <ast.BoolOp object at 0x7da1b23b0a60> begin[:] variable[epoch] assign[=] name[default_epoch] variable[info] assign[=] dictionary[[<ast.Constant object at 0x7da1b25053c0>, <ast.Constant object at 0x7da1b2505330>, <ast.Constant object at 0x7da1b2504f70>], [<ast.Name object at 0x7da1b2504250>, <ast.Tuple object at 0x7da1b2504100>, <ast.Name object at 0x7da1b25059c0>]] call[name[logger].debug, parameter[constant[parsed information: %s], name[info]]] return[name[info]]
keyword[def] identifier[parse_package] ( identifier[package_string] , identifier[arch_included] = keyword[True] ): literal[string] identifier[logger] . identifier[debug] ( literal[string] , identifier[package_string] , identifier[arch_included] ) identifier[default_epoch] = literal[string] identifier[arch] = keyword[None] keyword[if] identifier[arch_included] : identifier[char_list] = identifier[list] ( identifier[package_string] ) identifier[arch] = identifier[_pop_arch] ( identifier[char_list] ) identifier[package_string] = literal[string] . identifier[join] ( identifier[char_list] ) identifier[logger] . identifier[debug] ( literal[string] , identifier[package_string] ) keyword[try] : identifier[name] , identifier[epoch] , identifier[version] , identifier[release] = identifier[_rpm_re] . identifier[match] ( identifier[package_string] ). identifier[groups] () keyword[except] identifier[AttributeError] : keyword[raise] identifier[RpmError] ( literal[string] % identifier[package_string] ) keyword[if] identifier[epoch] == literal[string] keyword[or] identifier[epoch] keyword[is] keyword[None] : identifier[epoch] = identifier[default_epoch] identifier[info] ={ literal[string] : identifier[name] , literal[string] :( identifier[epoch] , identifier[version] , identifier[release] ), literal[string] : identifier[arch] } identifier[logger] . identifier[debug] ( literal[string] , identifier[info] ) keyword[return] identifier[info]
def parse_package(package_string, arch_included=True): """Parse an RPM version string to get name, version, and arch Splits most (all tested) RPM version strings into name, epoch, version, release, and architecture. Epoch (also called serial) is an optional component of RPM versioning and is also optional in version strings provided to this function. RPM assumes the epoch to be 0 if it is not provided, so that behavior is mirrored here. **Deprecated** since version 0.2.0. Use :any:`rpm.package` instead. :param str package_string: an RPM version string of the form returned by the ``rpm -q`` command :param bool arch_included: default True - version strings may optionally be provided without the trailing architecture. If providing such strings, set this option to False :return: a dictionary with all parsed package information :rtype: dict """ # Yum sets epoch values to 0 if they are not specified logger.debug('parse_package(%s, %s)', package_string, arch_included) default_epoch = '0' arch = None if arch_included: char_list = list(package_string) arch = _pop_arch(char_list) package_string = ''.join(char_list) logger.debug('updated version_string: %s', package_string) # depends on [control=['if'], data=[]] try: (name, epoch, version, release) = _rpm_re.match(package_string).groups() # depends on [control=['try'], data=[]] except AttributeError: raise RpmError('Could not parse package string: %s' % package_string) # depends on [control=['except'], data=[]] if epoch == '' or epoch is None: epoch = default_epoch # depends on [control=['if'], data=[]] info = {'name': name, 'EVR': (epoch, version, release), 'arch': arch} logger.debug('parsed information: %s', info) return info
def download(self, url, dest_path=None): """ :param url: :type url: str :param dest_path: :type dest_path: str """ if os.path.exists(dest_path): os.remove(dest_path) resp = get(url, stream=True) size = int(resp.headers.get("content-length")) label = "Downloading {filename} ({size:.2f}MB)".format( filename=os.path.basename(dest_path), size=size / float(self.chunk_size) / self.chunk_size ) with open_file(dest_path, 'wb') as file: content_iter = resp.iter_content(chunk_size=self.chunk_size) with progressbar(content_iter, length=size / self.chunk_size, label=label) as bar: for chunk in bar: if chunk: file.write(chunk) file.flush()
def function[download, parameter[self, url, dest_path]]: constant[ :param url: :type url: str :param dest_path: :type dest_path: str ] if call[name[os].path.exists, parameter[name[dest_path]]] begin[:] call[name[os].remove, parameter[name[dest_path]]] variable[resp] assign[=] call[name[get], parameter[name[url]]] variable[size] assign[=] call[name[int], parameter[call[name[resp].headers.get, parameter[constant[content-length]]]]] variable[label] assign[=] call[constant[Downloading {filename} ({size:.2f}MB)].format, parameter[]] with call[name[open_file], parameter[name[dest_path], constant[wb]]] begin[:] variable[content_iter] assign[=] call[name[resp].iter_content, parameter[]] with call[name[progressbar], parameter[name[content_iter]]] begin[:] for taget[name[chunk]] in starred[name[bar]] begin[:] if name[chunk] begin[:] call[name[file].write, parameter[name[chunk]]] call[name[file].flush, parameter[]]
keyword[def] identifier[download] ( identifier[self] , identifier[url] , identifier[dest_path] = keyword[None] ): literal[string] keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[dest_path] ): identifier[os] . identifier[remove] ( identifier[dest_path] ) identifier[resp] = identifier[get] ( identifier[url] , identifier[stream] = keyword[True] ) identifier[size] = identifier[int] ( identifier[resp] . identifier[headers] . identifier[get] ( literal[string] )) identifier[label] = literal[string] . identifier[format] ( identifier[filename] = identifier[os] . identifier[path] . identifier[basename] ( identifier[dest_path] ), identifier[size] = identifier[size] / identifier[float] ( identifier[self] . identifier[chunk_size] )/ identifier[self] . identifier[chunk_size] ) keyword[with] identifier[open_file] ( identifier[dest_path] , literal[string] ) keyword[as] identifier[file] : identifier[content_iter] = identifier[resp] . identifier[iter_content] ( identifier[chunk_size] = identifier[self] . identifier[chunk_size] ) keyword[with] identifier[progressbar] ( identifier[content_iter] , identifier[length] = identifier[size] / identifier[self] . identifier[chunk_size] , identifier[label] = identifier[label] ) keyword[as] identifier[bar] : keyword[for] identifier[chunk] keyword[in] identifier[bar] : keyword[if] identifier[chunk] : identifier[file] . identifier[write] ( identifier[chunk] ) identifier[file] . identifier[flush] ()
def download(self, url, dest_path=None): """ :param url: :type url: str :param dest_path: :type dest_path: str """ if os.path.exists(dest_path): os.remove(dest_path) # depends on [control=['if'], data=[]] resp = get(url, stream=True) size = int(resp.headers.get('content-length')) label = 'Downloading {filename} ({size:.2f}MB)'.format(filename=os.path.basename(dest_path), size=size / float(self.chunk_size) / self.chunk_size) with open_file(dest_path, 'wb') as file: content_iter = resp.iter_content(chunk_size=self.chunk_size) with progressbar(content_iter, length=size / self.chunk_size, label=label) as bar: for chunk in bar: if chunk: file.write(chunk) file.flush() # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['chunk']] # depends on [control=['with'], data=['bar']] # depends on [control=['with'], data=['file']]
def parse_cov(cov_table, scaffold2genome): """ calculate genome coverage from scaffold coverage table """ size = {} # size[genome] = genome size mapped = {} # mapped[genome][sample] = mapped bases # parse coverage files for line in open(cov_table): line = line.strip().split('\t') if line[0].startswith('#'): samples = line[1:] samples = [i.rsplit('/', 1)[-1].split('.', 1)[0] for i in samples] continue scaffold, length = line[0].split(': ') length = float(length) covs = [float(i) for i in line[1:]] bases = [c * length for c in covs] if scaffold not in scaffold2genome: continue genome = scaffold2genome[scaffold] if genome not in size: size[genome] = 0 mapped[genome] = {sample:0 for sample in samples} # keep track of genome size size[genome] += length # keep track of number of mapped bases for sample, count in zip(samples, bases): mapped[genome][sample] += count # calculate coverage from base counts and genome size coverage = {'genome':[], 'genome size (bp)':[], 'sample':[], 'coverage':[]} for genome, length in size.items(): for sample in samples: cov = mapped[genome][sample] / length coverage['genome'].append(genome) coverage['genome size (bp)'].append(length) coverage['sample'].append(sample) coverage['coverage'].append(cov) return pd.DataFrame(coverage)
def function[parse_cov, parameter[cov_table, scaffold2genome]]: constant[ calculate genome coverage from scaffold coverage table ] variable[size] assign[=] dictionary[[], []] variable[mapped] assign[=] dictionary[[], []] for taget[name[line]] in starred[call[name[open], parameter[name[cov_table]]]] begin[:] variable[line] assign[=] call[call[name[line].strip, parameter[]].split, parameter[constant[ ]]] if call[call[name[line]][constant[0]].startswith, parameter[constant[#]]] begin[:] variable[samples] assign[=] call[name[line]][<ast.Slice object at 0x7da20c76c220>] variable[samples] assign[=] <ast.ListComp object at 0x7da20c76f610> continue <ast.Tuple object at 0x7da20c76eb90> assign[=] call[call[name[line]][constant[0]].split, parameter[constant[: ]]] variable[length] assign[=] call[name[float], parameter[name[length]]] variable[covs] assign[=] <ast.ListComp object at 0x7da207f02e30> variable[bases] assign[=] <ast.ListComp object at 0x7da207f038e0> if compare[name[scaffold] <ast.NotIn object at 0x7da2590d7190> name[scaffold2genome]] begin[:] continue variable[genome] assign[=] call[name[scaffold2genome]][name[scaffold]] if compare[name[genome] <ast.NotIn object at 0x7da2590d7190> name[size]] begin[:] call[name[size]][name[genome]] assign[=] constant[0] call[name[mapped]][name[genome]] assign[=] <ast.DictComp object at 0x7da207f01270> <ast.AugAssign object at 0x7da207f01420> for taget[tuple[[<ast.Name object at 0x7da207f01630>, <ast.Name object at 0x7da207f00700>]]] in starred[call[name[zip], parameter[name[samples], name[bases]]]] begin[:] <ast.AugAssign object at 0x7da207f03580> variable[coverage] assign[=] dictionary[[<ast.Constant object at 0x7da18f720c40>, <ast.Constant object at 0x7da18f7206d0>, <ast.Constant object at 0x7da18f721f30>, <ast.Constant object at 0x7da18f7220b0>], [<ast.List object at 0x7da18f721780>, <ast.List object at 0x7da18f720a60>, <ast.List object at 0x7da18f720340>, <ast.List object at 0x7da18f7205b0>]] for taget[tuple[[<ast.Name object at 0x7da18f720550>, <ast.Name object at 0x7da18f721c30>]]] in starred[call[name[size].items, parameter[]]] begin[:] for taget[name[sample]] in starred[name[samples]] begin[:] variable[cov] assign[=] binary_operation[call[call[name[mapped]][name[genome]]][name[sample]] / name[length]] call[call[name[coverage]][constant[genome]].append, parameter[name[genome]]] call[call[name[coverage]][constant[genome size (bp)]].append, parameter[name[length]]] call[call[name[coverage]][constant[sample]].append, parameter[name[sample]]] call[call[name[coverage]][constant[coverage]].append, parameter[name[cov]]] return[call[name[pd].DataFrame, parameter[name[coverage]]]]
keyword[def] identifier[parse_cov] ( identifier[cov_table] , identifier[scaffold2genome] ): literal[string] identifier[size] ={} identifier[mapped] ={} keyword[for] identifier[line] keyword[in] identifier[open] ( identifier[cov_table] ): identifier[line] = identifier[line] . identifier[strip] (). identifier[split] ( literal[string] ) keyword[if] identifier[line] [ literal[int] ]. identifier[startswith] ( literal[string] ): identifier[samples] = identifier[line] [ literal[int] :] identifier[samples] =[ identifier[i] . identifier[rsplit] ( literal[string] , literal[int] )[- literal[int] ]. identifier[split] ( literal[string] , literal[int] )[ literal[int] ] keyword[for] identifier[i] keyword[in] identifier[samples] ] keyword[continue] identifier[scaffold] , identifier[length] = identifier[line] [ literal[int] ]. identifier[split] ( literal[string] ) identifier[length] = identifier[float] ( identifier[length] ) identifier[covs] =[ identifier[float] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[line] [ literal[int] :]] identifier[bases] =[ identifier[c] * identifier[length] keyword[for] identifier[c] keyword[in] identifier[covs] ] keyword[if] identifier[scaffold] keyword[not] keyword[in] identifier[scaffold2genome] : keyword[continue] identifier[genome] = identifier[scaffold2genome] [ identifier[scaffold] ] keyword[if] identifier[genome] keyword[not] keyword[in] identifier[size] : identifier[size] [ identifier[genome] ]= literal[int] identifier[mapped] [ identifier[genome] ]={ identifier[sample] : literal[int] keyword[for] identifier[sample] keyword[in] identifier[samples] } identifier[size] [ identifier[genome] ]+= identifier[length] keyword[for] identifier[sample] , identifier[count] keyword[in] identifier[zip] ( identifier[samples] , identifier[bases] ): identifier[mapped] [ identifier[genome] ][ identifier[sample] ]+= identifier[count] identifier[coverage] ={ literal[string] :[], literal[string] :[], literal[string] :[], literal[string] :[]} keyword[for] identifier[genome] , identifier[length] keyword[in] identifier[size] . identifier[items] (): keyword[for] identifier[sample] keyword[in] identifier[samples] : identifier[cov] = identifier[mapped] [ identifier[genome] ][ identifier[sample] ]/ identifier[length] identifier[coverage] [ literal[string] ]. identifier[append] ( identifier[genome] ) identifier[coverage] [ literal[string] ]. identifier[append] ( identifier[length] ) identifier[coverage] [ literal[string] ]. identifier[append] ( identifier[sample] ) identifier[coverage] [ literal[string] ]. identifier[append] ( identifier[cov] ) keyword[return] identifier[pd] . identifier[DataFrame] ( identifier[coverage] )
def parse_cov(cov_table, scaffold2genome): """ calculate genome coverage from scaffold coverage table """ size = {} # size[genome] = genome size mapped = {} # mapped[genome][sample] = mapped bases # parse coverage files for line in open(cov_table): line = line.strip().split('\t') if line[0].startswith('#'): samples = line[1:] samples = [i.rsplit('/', 1)[-1].split('.', 1)[0] for i in samples] continue # depends on [control=['if'], data=[]] (scaffold, length) = line[0].split(': ') length = float(length) covs = [float(i) for i in line[1:]] bases = [c * length for c in covs] if scaffold not in scaffold2genome: continue # depends on [control=['if'], data=[]] genome = scaffold2genome[scaffold] if genome not in size: size[genome] = 0 mapped[genome] = {sample: 0 for sample in samples} # depends on [control=['if'], data=['genome', 'size']] # keep track of genome size size[genome] += length # keep track of number of mapped bases for (sample, count) in zip(samples, bases): mapped[genome][sample] += count # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['line']] # calculate coverage from base counts and genome size coverage = {'genome': [], 'genome size (bp)': [], 'sample': [], 'coverage': []} for (genome, length) in size.items(): for sample in samples: cov = mapped[genome][sample] / length coverage['genome'].append(genome) coverage['genome size (bp)'].append(length) coverage['sample'].append(sample) coverage['coverage'].append(cov) # depends on [control=['for'], data=['sample']] # depends on [control=['for'], data=[]] return pd.DataFrame(coverage)
def _CreateRoutesFolder(self, schedule, doc, route_type=None): """Create a KML Folder containing routes in a schedule. The folder contains a subfolder for each route in the schedule of type route_type. If route_type is None, then all routes are selected. Each subfolder contains a flattened graph placemark, a route shapes placemark and, if show_trips is True, a subfolder containing placemarks for each of the trips in the route. If there are no routes in the schedule then no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. route_type: The route type integer or None. Returns: The Folder ElementTree.Element instance or None. """ def GetRouteName(route): """Return a placemark name for the route. Args: route: The transitfeed.Route instance. Returns: The name as a string. """ name_parts = [] if route.route_short_name: name_parts.append('<b>%s</b>' % route.route_short_name) if route.route_long_name: name_parts.append(route.route_long_name) return ' - '.join(name_parts) or route.route_id def GetRouteDescription(route): """Return a placemark description for the route. Args: route: The transitfeed.Route instance. Returns: The description as a string. """ desc_items = [] if route.route_desc: desc_items.append(route.route_desc) if route.route_url: desc_items.append('Route info page: <a href="%s">%s</a>' % ( route.route_url, route.route_url)) description = '<br/>'.join(desc_items) return description or None routes = [route for route in schedule.GetRouteList() if route_type is None or route.route_type == route_type] if not routes: return None routes.sort(key=lambda x: GetRouteName(x)) if route_type is not None: route_type_names = {0: 'Tram, Streetcar or Light rail', 1: 'Subway or Metro', 2: 'Rail', 3: 'Bus', 4: 'Ferry', 5: 'Cable car', 6: 'Gondola or suspended cable car', 7: 'Funicular'} type_name = route_type_names.get(route_type, str(route_type)) folder_name = 'Routes - %s' % type_name else: folder_name = 'Routes' routes_folder = self._CreateFolder(doc, folder_name, visible=False) for route in routes: style_id = self._CreateStyleForRoute(doc, route) route_folder = self._CreateFolder(routes_folder, GetRouteName(route), description=GetRouteDescription(route)) self._CreateRouteShapesFolder(schedule, route_folder, route, style_id, False) self._CreateRoutePatternsFolder(route_folder, route, style_id, False) if self.show_trips: self._CreateRouteTripsFolder(route_folder, route, style_id, schedule) return routes_folder
def function[_CreateRoutesFolder, parameter[self, schedule, doc, route_type]]: constant[Create a KML Folder containing routes in a schedule. The folder contains a subfolder for each route in the schedule of type route_type. If route_type is None, then all routes are selected. Each subfolder contains a flattened graph placemark, a route shapes placemark and, if show_trips is True, a subfolder containing placemarks for each of the trips in the route. If there are no routes in the schedule then no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. route_type: The route type integer or None. Returns: The Folder ElementTree.Element instance or None. ] def function[GetRouteName, parameter[route]]: constant[Return a placemark name for the route. Args: route: The transitfeed.Route instance. Returns: The name as a string. ] variable[name_parts] assign[=] list[[]] if name[route].route_short_name begin[:] call[name[name_parts].append, parameter[binary_operation[constant[<b>%s</b>] <ast.Mod object at 0x7da2590d6920> name[route].route_short_name]]] if name[route].route_long_name begin[:] call[name[name_parts].append, parameter[name[route].route_long_name]] return[<ast.BoolOp object at 0x7da1b2345d50>] def function[GetRouteDescription, parameter[route]]: constant[Return a placemark description for the route. Args: route: The transitfeed.Route instance. Returns: The description as a string. ] variable[desc_items] assign[=] list[[]] if name[route].route_desc begin[:] call[name[desc_items].append, parameter[name[route].route_desc]] if name[route].route_url begin[:] call[name[desc_items].append, parameter[binary_operation[constant[Route info page: <a href="%s">%s</a>] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b2347160>, <ast.Attribute object at 0x7da1b23459c0>]]]]] variable[description] assign[=] call[constant[<br/>].join, parameter[name[desc_items]]] return[<ast.BoolOp object at 0x7da1b23470d0>] variable[routes] assign[=] <ast.ListComp object at 0x7da1b23472b0> if <ast.UnaryOp object at 0x7da1b2344ee0> begin[:] return[constant[None]] call[name[routes].sort, parameter[]] if compare[name[route_type] is_not constant[None]] begin[:] variable[route_type_names] assign[=] dictionary[[<ast.Constant object at 0x7da1b2347dc0>, <ast.Constant object at 0x7da1b23460e0>, <ast.Constant object at 0x7da1b23446d0>, <ast.Constant object at 0x7da1b2347b20>, <ast.Constant object at 0x7da1b2347820>, <ast.Constant object at 0x7da1b2344e80>, <ast.Constant object at 0x7da1b23453c0>, <ast.Constant object at 0x7da1b2345f60>], [<ast.Constant object at 0x7da1b2345a20>, <ast.Constant object at 0x7da1b23473d0>, <ast.Constant object at 0x7da1b23469b0>, <ast.Constant object at 0x7da1b23451b0>, <ast.Constant object at 0x7da1b2345f30>, <ast.Constant object at 0x7da1b2344040>, <ast.Constant object at 0x7da1b23452a0>, <ast.Constant object at 0x7da1b2346590>]] variable[type_name] assign[=] call[name[route_type_names].get, parameter[name[route_type], call[name[str], parameter[name[route_type]]]]] variable[folder_name] assign[=] binary_operation[constant[Routes - %s] <ast.Mod object at 0x7da2590d6920> name[type_name]] variable[routes_folder] assign[=] call[name[self]._CreateFolder, parameter[name[doc], name[folder_name]]] for taget[name[route]] in starred[name[routes]] begin[:] variable[style_id] assign[=] call[name[self]._CreateStyleForRoute, parameter[name[doc], name[route]]] variable[route_folder] assign[=] call[name[self]._CreateFolder, parameter[name[routes_folder], call[name[GetRouteName], parameter[name[route]]]]] call[name[self]._CreateRouteShapesFolder, parameter[name[schedule], name[route_folder], name[route], name[style_id], constant[False]]] call[name[self]._CreateRoutePatternsFolder, parameter[name[route_folder], name[route], name[style_id], constant[False]]] if name[self].show_trips begin[:] call[name[self]._CreateRouteTripsFolder, parameter[name[route_folder], name[route], name[style_id], name[schedule]]] return[name[routes_folder]]
keyword[def] identifier[_CreateRoutesFolder] ( identifier[self] , identifier[schedule] , identifier[doc] , identifier[route_type] = keyword[None] ): literal[string] keyword[def] identifier[GetRouteName] ( identifier[route] ): literal[string] identifier[name_parts] =[] keyword[if] identifier[route] . identifier[route_short_name] : identifier[name_parts] . identifier[append] ( literal[string] % identifier[route] . identifier[route_short_name] ) keyword[if] identifier[route] . identifier[route_long_name] : identifier[name_parts] . identifier[append] ( identifier[route] . identifier[route_long_name] ) keyword[return] literal[string] . identifier[join] ( identifier[name_parts] ) keyword[or] identifier[route] . identifier[route_id] keyword[def] identifier[GetRouteDescription] ( identifier[route] ): literal[string] identifier[desc_items] =[] keyword[if] identifier[route] . identifier[route_desc] : identifier[desc_items] . identifier[append] ( identifier[route] . identifier[route_desc] ) keyword[if] identifier[route] . identifier[route_url] : identifier[desc_items] . identifier[append] ( literal[string] %( identifier[route] . identifier[route_url] , identifier[route] . identifier[route_url] )) identifier[description] = literal[string] . identifier[join] ( identifier[desc_items] ) keyword[return] identifier[description] keyword[or] keyword[None] identifier[routes] =[ identifier[route] keyword[for] identifier[route] keyword[in] identifier[schedule] . identifier[GetRouteList] () keyword[if] identifier[route_type] keyword[is] keyword[None] keyword[or] identifier[route] . identifier[route_type] == identifier[route_type] ] keyword[if] keyword[not] identifier[routes] : keyword[return] keyword[None] identifier[routes] . identifier[sort] ( identifier[key] = keyword[lambda] identifier[x] : identifier[GetRouteName] ( identifier[x] )) keyword[if] identifier[route_type] keyword[is] keyword[not] keyword[None] : identifier[route_type_names] ={ literal[int] : literal[string] , literal[int] : literal[string] , literal[int] : literal[string] , literal[int] : literal[string] , literal[int] : literal[string] , literal[int] : literal[string] , literal[int] : literal[string] , literal[int] : literal[string] } identifier[type_name] = identifier[route_type_names] . identifier[get] ( identifier[route_type] , identifier[str] ( identifier[route_type] )) identifier[folder_name] = literal[string] % identifier[type_name] keyword[else] : identifier[folder_name] = literal[string] identifier[routes_folder] = identifier[self] . identifier[_CreateFolder] ( identifier[doc] , identifier[folder_name] , identifier[visible] = keyword[False] ) keyword[for] identifier[route] keyword[in] identifier[routes] : identifier[style_id] = identifier[self] . identifier[_CreateStyleForRoute] ( identifier[doc] , identifier[route] ) identifier[route_folder] = identifier[self] . identifier[_CreateFolder] ( identifier[routes_folder] , identifier[GetRouteName] ( identifier[route] ), identifier[description] = identifier[GetRouteDescription] ( identifier[route] )) identifier[self] . identifier[_CreateRouteShapesFolder] ( identifier[schedule] , identifier[route_folder] , identifier[route] , identifier[style_id] , keyword[False] ) identifier[self] . identifier[_CreateRoutePatternsFolder] ( identifier[route_folder] , identifier[route] , identifier[style_id] , keyword[False] ) keyword[if] identifier[self] . identifier[show_trips] : identifier[self] . identifier[_CreateRouteTripsFolder] ( identifier[route_folder] , identifier[route] , identifier[style_id] , identifier[schedule] ) keyword[return] identifier[routes_folder]
def _CreateRoutesFolder(self, schedule, doc, route_type=None): """Create a KML Folder containing routes in a schedule. The folder contains a subfolder for each route in the schedule of type route_type. If route_type is None, then all routes are selected. Each subfolder contains a flattened graph placemark, a route shapes placemark and, if show_trips is True, a subfolder containing placemarks for each of the trips in the route. If there are no routes in the schedule then no folder is created and None is returned. Args: schedule: The transitfeed.Schedule instance. doc: The KML Document ElementTree.Element instance. route_type: The route type integer or None. Returns: The Folder ElementTree.Element instance or None. """ def GetRouteName(route): """Return a placemark name for the route. Args: route: The transitfeed.Route instance. Returns: The name as a string. """ name_parts = [] if route.route_short_name: name_parts.append('<b>%s</b>' % route.route_short_name) # depends on [control=['if'], data=[]] if route.route_long_name: name_parts.append(route.route_long_name) # depends on [control=['if'], data=[]] return ' - '.join(name_parts) or route.route_id def GetRouteDescription(route): """Return a placemark description for the route. Args: route: The transitfeed.Route instance. Returns: The description as a string. """ desc_items = [] if route.route_desc: desc_items.append(route.route_desc) # depends on [control=['if'], data=[]] if route.route_url: desc_items.append('Route info page: <a href="%s">%s</a>' % (route.route_url, route.route_url)) # depends on [control=['if'], data=[]] description = '<br/>'.join(desc_items) return description or None routes = [route for route in schedule.GetRouteList() if route_type is None or route.route_type == route_type] if not routes: return None # depends on [control=['if'], data=[]] routes.sort(key=lambda x: GetRouteName(x)) if route_type is not None: route_type_names = {0: 'Tram, Streetcar or Light rail', 1: 'Subway or Metro', 2: 'Rail', 3: 'Bus', 4: 'Ferry', 5: 'Cable car', 6: 'Gondola or suspended cable car', 7: 'Funicular'} type_name = route_type_names.get(route_type, str(route_type)) folder_name = 'Routes - %s' % type_name # depends on [control=['if'], data=['route_type']] else: folder_name = 'Routes' routes_folder = self._CreateFolder(doc, folder_name, visible=False) for route in routes: style_id = self._CreateStyleForRoute(doc, route) route_folder = self._CreateFolder(routes_folder, GetRouteName(route), description=GetRouteDescription(route)) self._CreateRouteShapesFolder(schedule, route_folder, route, style_id, False) self._CreateRoutePatternsFolder(route_folder, route, style_id, False) if self.show_trips: self._CreateRouteTripsFolder(route_folder, route, style_id, schedule) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['route']] return routes_folder
def set_parent(self, parent): """Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None :raises: None """ if self._parent == parent: return if self._parent: self._parent.remove_child(self) self._parent = parent if parent: parent.add_child(self)
def function[set_parent, parameter[self, parent]]: constant[Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None :raises: None ] if compare[name[self]._parent equal[==] name[parent]] begin[:] return[None] if name[self]._parent begin[:] call[name[self]._parent.remove_child, parameter[name[self]]] name[self]._parent assign[=] name[parent] if name[parent] begin[:] call[name[parent].add_child, parameter[name[self]]]
keyword[def] identifier[set_parent] ( identifier[self] , identifier[parent] ): literal[string] keyword[if] identifier[self] . identifier[_parent] == identifier[parent] : keyword[return] keyword[if] identifier[self] . identifier[_parent] : identifier[self] . identifier[_parent] . identifier[remove_child] ( identifier[self] ) identifier[self] . identifier[_parent] = identifier[parent] keyword[if] identifier[parent] : identifier[parent] . identifier[add_child] ( identifier[self] )
def set_parent(self, parent): """Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None :raises: None """ if self._parent == parent: return # depends on [control=['if'], data=[]] if self._parent: self._parent.remove_child(self) # depends on [control=['if'], data=[]] self._parent = parent if parent: parent.add_child(self) # depends on [control=['if'], data=[]]
def calculate_offset(cls, labels): '''Return the maximum length of the provided strings that have a nice variant in DapFormatter._nice_strings''' used_strings = set(cls._nice_strings.keys()) & set(labels) return max([len(cls._nice_strings[s]) for s in used_strings])
def function[calculate_offset, parameter[cls, labels]]: constant[Return the maximum length of the provided strings that have a nice variant in DapFormatter._nice_strings] variable[used_strings] assign[=] binary_operation[call[name[set], parameter[call[name[cls]._nice_strings.keys, parameter[]]]] <ast.BitAnd object at 0x7da2590d6b60> call[name[set], parameter[name[labels]]]] return[call[name[max], parameter[<ast.ListComp object at 0x7da20c6e43d0>]]]
keyword[def] identifier[calculate_offset] ( identifier[cls] , identifier[labels] ): literal[string] identifier[used_strings] = identifier[set] ( identifier[cls] . identifier[_nice_strings] . identifier[keys] ())& identifier[set] ( identifier[labels] ) keyword[return] identifier[max] ([ identifier[len] ( identifier[cls] . identifier[_nice_strings] [ identifier[s] ]) keyword[for] identifier[s] keyword[in] identifier[used_strings] ])
def calculate_offset(cls, labels): """Return the maximum length of the provided strings that have a nice variant in DapFormatter._nice_strings""" used_strings = set(cls._nice_strings.keys()) & set(labels) return max([len(cls._nice_strings[s]) for s in used_strings])
def chgrp(path, group): ''' Change the group of a file Under Windows, this will do nothing. While a file in Windows does have a 'primary group', this rarely used attribute generally has no bearing on permissions unless intentionally configured and is only used to support Unix compatibility features (e.g. Services For Unix, NFS services). Salt, therefore, remaps this function to do nothing while still being compatible with Unix behavior. When managing Windows systems, this function is superfluous and will generate an info level log entry if used directly. If you do actually want to set the 'primary group' of a file, use ``file .chpgrp``. To set group permissions use ``file.set_perms`` Args: path (str): The path to the file or directory group (str): The group (unused) Returns: None CLI Example: .. code-block:: bash salt '*' file.chpgrp c:\\temp\\test.txt administrators ''' func_name = '{0}.chgrp'.format(__virtualname__) if __opts__.get('fun', '') == func_name: log.info('The function %s should not be used on Windows systems; see ' 'function docs for details.', func_name) log.debug('win_file.py %s Doing nothing for %s', func_name, path) return None
def function[chgrp, parameter[path, group]]: constant[ Change the group of a file Under Windows, this will do nothing. While a file in Windows does have a 'primary group', this rarely used attribute generally has no bearing on permissions unless intentionally configured and is only used to support Unix compatibility features (e.g. Services For Unix, NFS services). Salt, therefore, remaps this function to do nothing while still being compatible with Unix behavior. When managing Windows systems, this function is superfluous and will generate an info level log entry if used directly. If you do actually want to set the 'primary group' of a file, use ``file .chpgrp``. To set group permissions use ``file.set_perms`` Args: path (str): The path to the file or directory group (str): The group (unused) Returns: None CLI Example: .. code-block:: bash salt '*' file.chpgrp c:\temp\test.txt administrators ] variable[func_name] assign[=] call[constant[{0}.chgrp].format, parameter[name[__virtualname__]]] if compare[call[name[__opts__].get, parameter[constant[fun], constant[]]] equal[==] name[func_name]] begin[:] call[name[log].info, parameter[constant[The function %s should not be used on Windows systems; see function docs for details.], name[func_name]]] call[name[log].debug, parameter[constant[win_file.py %s Doing nothing for %s], name[func_name], name[path]]] return[constant[None]]
keyword[def] identifier[chgrp] ( identifier[path] , identifier[group] ): literal[string] identifier[func_name] = literal[string] . identifier[format] ( identifier[__virtualname__] ) keyword[if] identifier[__opts__] . identifier[get] ( literal[string] , literal[string] )== identifier[func_name] : identifier[log] . identifier[info] ( literal[string] literal[string] , identifier[func_name] ) identifier[log] . identifier[debug] ( literal[string] , identifier[func_name] , identifier[path] ) keyword[return] keyword[None]
def chgrp(path, group): """ Change the group of a file Under Windows, this will do nothing. While a file in Windows does have a 'primary group', this rarely used attribute generally has no bearing on permissions unless intentionally configured and is only used to support Unix compatibility features (e.g. Services For Unix, NFS services). Salt, therefore, remaps this function to do nothing while still being compatible with Unix behavior. When managing Windows systems, this function is superfluous and will generate an info level log entry if used directly. If you do actually want to set the 'primary group' of a file, use ``file .chpgrp``. To set group permissions use ``file.set_perms`` Args: path (str): The path to the file or directory group (str): The group (unused) Returns: None CLI Example: .. code-block:: bash salt '*' file.chpgrp c:\\temp\\test.txt administrators """ func_name = '{0}.chgrp'.format(__virtualname__) if __opts__.get('fun', '') == func_name: log.info('The function %s should not be used on Windows systems; see function docs for details.', func_name) # depends on [control=['if'], data=['func_name']] log.debug('win_file.py %s Doing nothing for %s', func_name, path) return None
def fetch(self): """ Fetch a CompositionSettingsInstance :returns: Fetched CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, params=params, ) return CompositionSettingsInstance(self._version, payload, )
def function[fetch, parameter[self]]: constant[ Fetch a CompositionSettingsInstance :returns: Fetched CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance ] variable[params] assign[=] call[name[values].of, parameter[dictionary[[], []]]] variable[payload] assign[=] call[name[self]._version.fetch, parameter[constant[GET], name[self]._uri]] return[call[name[CompositionSettingsInstance], parameter[name[self]._version, name[payload]]]]
keyword[def] identifier[fetch] ( identifier[self] ): literal[string] identifier[params] = identifier[values] . identifier[of] ({}) identifier[payload] = identifier[self] . identifier[_version] . identifier[fetch] ( literal[string] , identifier[self] . identifier[_uri] , identifier[params] = identifier[params] , ) keyword[return] identifier[CompositionSettingsInstance] ( identifier[self] . identifier[_version] , identifier[payload] ,)
def fetch(self): """ Fetch a CompositionSettingsInstance :returns: Fetched CompositionSettingsInstance :rtype: twilio.rest.video.v1.composition_settings.CompositionSettingsInstance """ params = values.of({}) payload = self._version.fetch('GET', self._uri, params=params) return CompositionSettingsInstance(self._version, payload)
def _old_epd_magseries(times, mags, errs, fsv, fdv, fkv, xcc, ycc, bgv, bge, epdsmooth_windowsize=21, epdsmooth_sigclip=3.0, epdsmooth_func=smooth_magseries_signal_medfilt, epdsmooth_extraparams=None): ''' Detrends a magnitude series given in mag using accompanying values of S in fsv, D in fdv, K in fkv, x coords in xcc, y coords in ycc, background in bgv, and background error in bge. smooth is used to set a smoothing parameter for the fit function. Does EPD voodoo. ''' # find all the finite values of the magsnitude finiteind = np.isfinite(mags) # calculate median and stdev mags_median = np.median(mags[finiteind]) mags_stdev = np.nanstd(mags) # if we're supposed to sigma clip, do so if epdsmooth_sigclip: excludeind = abs(mags - mags_median) < epdsmooth_sigclip*mags_stdev finalind = finiteind & excludeind else: finalind = finiteind final_mags = mags[finalind] final_len = len(final_mags) # smooth the signal if isinstance(epdsmooth_extraparams, dict): smoothedmags = epdsmooth_func(final_mags, epdsmooth_windowsize, **epdsmooth_extraparams) else: smoothedmags = epdsmooth_func(final_mags, epdsmooth_windowsize) # make the linear equation matrix epdmatrix = np.c_[fsv[finalind]**2.0, fsv[finalind], fdv[finalind]**2.0, fdv[finalind], fkv[finalind]**2.0, fkv[finalind], np.ones(final_len), fsv[finalind]*fdv[finalind], fsv[finalind]*fkv[finalind], fdv[finalind]*fkv[finalind], np.sin(2*np.pi*xcc[finalind]), np.cos(2*np.pi*xcc[finalind]), np.sin(2*np.pi*ycc[finalind]), np.cos(2*np.pi*ycc[finalind]), np.sin(4*np.pi*xcc[finalind]), np.cos(4*np.pi*xcc[finalind]), np.sin(4*np.pi*ycc[finalind]), np.cos(4*np.pi*ycc[finalind]), bgv[finalind], bge[finalind]] # solve the matrix equation [epdmatrix] . [x] = [smoothedmags] # return the EPD differential magss if the solution succeeds try: coeffs, residuals, rank, singulars = lstsq(epdmatrix, smoothedmags, rcond=None) if DEBUG: print('coeffs = %s, residuals = %s' % (coeffs, residuals)) retdict = {'times':times, 'mags':(mags_median + _old_epd_diffmags(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, mags)), 'errs':errs, 'fitcoeffs':coeffs, 'residuals':residuals} return retdict # if the solution fails, return nothing except Exception as e: LOGEXCEPTION('EPD solution did not converge') retdict = {'times':times, 'mags':np.full_like(mags, np.nan), 'errs':errs, 'fitcoeffs':coeffs, 'residuals':residuals} return retdict
def function[_old_epd_magseries, parameter[times, mags, errs, fsv, fdv, fkv, xcc, ycc, bgv, bge, epdsmooth_windowsize, epdsmooth_sigclip, epdsmooth_func, epdsmooth_extraparams]]: constant[ Detrends a magnitude series given in mag using accompanying values of S in fsv, D in fdv, K in fkv, x coords in xcc, y coords in ycc, background in bgv, and background error in bge. smooth is used to set a smoothing parameter for the fit function. Does EPD voodoo. ] variable[finiteind] assign[=] call[name[np].isfinite, parameter[name[mags]]] variable[mags_median] assign[=] call[name[np].median, parameter[call[name[mags]][name[finiteind]]]] variable[mags_stdev] assign[=] call[name[np].nanstd, parameter[name[mags]]] if name[epdsmooth_sigclip] begin[:] variable[excludeind] assign[=] compare[call[name[abs], parameter[binary_operation[name[mags] - name[mags_median]]]] less[<] binary_operation[name[epdsmooth_sigclip] * name[mags_stdev]]] variable[finalind] assign[=] binary_operation[name[finiteind] <ast.BitAnd object at 0x7da2590d6b60> name[excludeind]] variable[final_mags] assign[=] call[name[mags]][name[finalind]] variable[final_len] assign[=] call[name[len], parameter[name[final_mags]]] if call[name[isinstance], parameter[name[epdsmooth_extraparams], name[dict]]] begin[:] variable[smoothedmags] assign[=] call[name[epdsmooth_func], parameter[name[final_mags], name[epdsmooth_windowsize]]] variable[epdmatrix] assign[=] call[name[np].c_][tuple[[<ast.BinOp object at 0x7da18f09f130>, <ast.Subscript object at 0x7da18f09cd00>, <ast.BinOp object at 0x7da18f09cee0>, <ast.Subscript object at 0x7da18f09e710>, <ast.BinOp object at 0x7da18f09dae0>, <ast.Subscript object at 0x7da18f09e500>, <ast.Call object at 0x7da18f09de10>, <ast.BinOp object at 0x7da18f09c9a0>, <ast.BinOp object at 0x7da2041db820>, <ast.BinOp object at 0x7da2041da080>, <ast.Call object at 0x7da2041dbeb0>, <ast.Call object at 0x7da2041da350>, <ast.Call object at 0x7da2041db970>, <ast.Call object at 0x7da2041dbe80>, <ast.Call object at 0x7da2041dac50>, <ast.Call object at 0x7da2041da740>, <ast.Call object at 0x7da2041db880>, <ast.Call object at 0x7da2041d8820>, <ast.Subscript object at 0x7da2041db1c0>, <ast.Subscript object at 0x7da2041d8850>]]] <ast.Try object at 0x7da2041d9810>
keyword[def] identifier[_old_epd_magseries] ( identifier[times] , identifier[mags] , identifier[errs] , identifier[fsv] , identifier[fdv] , identifier[fkv] , identifier[xcc] , identifier[ycc] , identifier[bgv] , identifier[bge] , identifier[epdsmooth_windowsize] = literal[int] , identifier[epdsmooth_sigclip] = literal[int] , identifier[epdsmooth_func] = identifier[smooth_magseries_signal_medfilt] , identifier[epdsmooth_extraparams] = keyword[None] ): literal[string] identifier[finiteind] = identifier[np] . identifier[isfinite] ( identifier[mags] ) identifier[mags_median] = identifier[np] . identifier[median] ( identifier[mags] [ identifier[finiteind] ]) identifier[mags_stdev] = identifier[np] . identifier[nanstd] ( identifier[mags] ) keyword[if] identifier[epdsmooth_sigclip] : identifier[excludeind] = identifier[abs] ( identifier[mags] - identifier[mags_median] )< identifier[epdsmooth_sigclip] * identifier[mags_stdev] identifier[finalind] = identifier[finiteind] & identifier[excludeind] keyword[else] : identifier[finalind] = identifier[finiteind] identifier[final_mags] = identifier[mags] [ identifier[finalind] ] identifier[final_len] = identifier[len] ( identifier[final_mags] ) keyword[if] identifier[isinstance] ( identifier[epdsmooth_extraparams] , identifier[dict] ): identifier[smoothedmags] = identifier[epdsmooth_func] ( identifier[final_mags] , identifier[epdsmooth_windowsize] , ** identifier[epdsmooth_extraparams] ) keyword[else] : identifier[smoothedmags] = identifier[epdsmooth_func] ( identifier[final_mags] , identifier[epdsmooth_windowsize] ) identifier[epdmatrix] = identifier[np] . identifier[c_] [ identifier[fsv] [ identifier[finalind] ]** literal[int] , identifier[fsv] [ identifier[finalind] ], identifier[fdv] [ identifier[finalind] ]** literal[int] , identifier[fdv] [ identifier[finalind] ], identifier[fkv] [ identifier[finalind] ]** literal[int] , identifier[fkv] [ identifier[finalind] ], identifier[np] . identifier[ones] ( identifier[final_len] ), identifier[fsv] [ identifier[finalind] ]* identifier[fdv] [ identifier[finalind] ], identifier[fsv] [ identifier[finalind] ]* identifier[fkv] [ identifier[finalind] ], identifier[fdv] [ identifier[finalind] ]* identifier[fkv] [ identifier[finalind] ], identifier[np] . identifier[sin] ( literal[int] * identifier[np] . identifier[pi] * identifier[xcc] [ identifier[finalind] ]), identifier[np] . identifier[cos] ( literal[int] * identifier[np] . identifier[pi] * identifier[xcc] [ identifier[finalind] ]), identifier[np] . identifier[sin] ( literal[int] * identifier[np] . identifier[pi] * identifier[ycc] [ identifier[finalind] ]), identifier[np] . identifier[cos] ( literal[int] * identifier[np] . identifier[pi] * identifier[ycc] [ identifier[finalind] ]), identifier[np] . identifier[sin] ( literal[int] * identifier[np] . identifier[pi] * identifier[xcc] [ identifier[finalind] ]), identifier[np] . identifier[cos] ( literal[int] * identifier[np] . identifier[pi] * identifier[xcc] [ identifier[finalind] ]), identifier[np] . identifier[sin] ( literal[int] * identifier[np] . identifier[pi] * identifier[ycc] [ identifier[finalind] ]), identifier[np] . identifier[cos] ( literal[int] * identifier[np] . identifier[pi] * identifier[ycc] [ identifier[finalind] ]), identifier[bgv] [ identifier[finalind] ], identifier[bge] [ identifier[finalind] ]] keyword[try] : identifier[coeffs] , identifier[residuals] , identifier[rank] , identifier[singulars] = identifier[lstsq] ( identifier[epdmatrix] , identifier[smoothedmags] , identifier[rcond] = keyword[None] ) keyword[if] identifier[DEBUG] : identifier[print] ( literal[string] %( identifier[coeffs] , identifier[residuals] )) identifier[retdict] ={ literal[string] : identifier[times] , literal[string] :( identifier[mags_median] + identifier[_old_epd_diffmags] ( identifier[coeffs] , identifier[fsv] , identifier[fdv] , identifier[fkv] , identifier[xcc] , identifier[ycc] , identifier[bgv] , identifier[bge] , identifier[mags] )), literal[string] : identifier[errs] , literal[string] : identifier[coeffs] , literal[string] : identifier[residuals] } keyword[return] identifier[retdict] keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[LOGEXCEPTION] ( literal[string] ) identifier[retdict] ={ literal[string] : identifier[times] , literal[string] : identifier[np] . identifier[full_like] ( identifier[mags] , identifier[np] . identifier[nan] ), literal[string] : identifier[errs] , literal[string] : identifier[coeffs] , literal[string] : identifier[residuals] } keyword[return] identifier[retdict]
def _old_epd_magseries(times, mags, errs, fsv, fdv, fkv, xcc, ycc, bgv, bge, epdsmooth_windowsize=21, epdsmooth_sigclip=3.0, epdsmooth_func=smooth_magseries_signal_medfilt, epdsmooth_extraparams=None): """ Detrends a magnitude series given in mag using accompanying values of S in fsv, D in fdv, K in fkv, x coords in xcc, y coords in ycc, background in bgv, and background error in bge. smooth is used to set a smoothing parameter for the fit function. Does EPD voodoo. """ # find all the finite values of the magsnitude finiteind = np.isfinite(mags) # calculate median and stdev mags_median = np.median(mags[finiteind]) mags_stdev = np.nanstd(mags) # if we're supposed to sigma clip, do so if epdsmooth_sigclip: excludeind = abs(mags - mags_median) < epdsmooth_sigclip * mags_stdev finalind = finiteind & excludeind # depends on [control=['if'], data=[]] else: finalind = finiteind final_mags = mags[finalind] final_len = len(final_mags) # smooth the signal if isinstance(epdsmooth_extraparams, dict): smoothedmags = epdsmooth_func(final_mags, epdsmooth_windowsize, **epdsmooth_extraparams) # depends on [control=['if'], data=[]] else: smoothedmags = epdsmooth_func(final_mags, epdsmooth_windowsize) # make the linear equation matrix epdmatrix = np.c_[fsv[finalind] ** 2.0, fsv[finalind], fdv[finalind] ** 2.0, fdv[finalind], fkv[finalind] ** 2.0, fkv[finalind], np.ones(final_len), fsv[finalind] * fdv[finalind], fsv[finalind] * fkv[finalind], fdv[finalind] * fkv[finalind], np.sin(2 * np.pi * xcc[finalind]), np.cos(2 * np.pi * xcc[finalind]), np.sin(2 * np.pi * ycc[finalind]), np.cos(2 * np.pi * ycc[finalind]), np.sin(4 * np.pi * xcc[finalind]), np.cos(4 * np.pi * xcc[finalind]), np.sin(4 * np.pi * ycc[finalind]), np.cos(4 * np.pi * ycc[finalind]), bgv[finalind], bge[finalind]] # solve the matrix equation [epdmatrix] . [x] = [smoothedmags] # return the EPD differential magss if the solution succeeds try: (coeffs, residuals, rank, singulars) = lstsq(epdmatrix, smoothedmags, rcond=None) if DEBUG: print('coeffs = %s, residuals = %s' % (coeffs, residuals)) # depends on [control=['if'], data=[]] retdict = {'times': times, 'mags': mags_median + _old_epd_diffmags(coeffs, fsv, fdv, fkv, xcc, ycc, bgv, bge, mags), 'errs': errs, 'fitcoeffs': coeffs, 'residuals': residuals} return retdict # depends on [control=['try'], data=[]] # if the solution fails, return nothing except Exception as e: LOGEXCEPTION('EPD solution did not converge') retdict = {'times': times, 'mags': np.full_like(mags, np.nan), 'errs': errs, 'fitcoeffs': coeffs, 'residuals': residuals} return retdict # depends on [control=['except'], data=[]]
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True): """ Bootstrap by adding noise """ boot_dist = [] arr = N.zeros(data.shape) for i in range(n): if symmetric: # Noise on all three axes arr = N.random.randn(*data.shape)*std else: # Only z-coordinate noise arr[:,-1] = N.random.randn(data.shape[0])*std boot_dist.append(func(data+arr)) return N.array(boot_dist)
def function[bootstrap_noise, parameter[data, func, n, std, symmetric]]: constant[ Bootstrap by adding noise ] variable[boot_dist] assign[=] list[[]] variable[arr] assign[=] call[name[N].zeros, parameter[name[data].shape]] for taget[name[i]] in starred[call[name[range], parameter[name[n]]]] begin[:] if name[symmetric] begin[:] variable[arr] assign[=] binary_operation[call[name[N].random.randn, parameter[<ast.Starred object at 0x7da1b17093f0>]] * name[std]] call[name[boot_dist].append, parameter[call[name[func], parameter[binary_operation[name[data] + name[arr]]]]]] return[call[name[N].array, parameter[name[boot_dist]]]]
keyword[def] identifier[bootstrap_noise] ( identifier[data] , identifier[func] , identifier[n] = literal[int] , identifier[std] = literal[int] , identifier[symmetric] = keyword[True] ): literal[string] identifier[boot_dist] =[] identifier[arr] = identifier[N] . identifier[zeros] ( identifier[data] . identifier[shape] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[n] ): keyword[if] identifier[symmetric] : identifier[arr] = identifier[N] . identifier[random] . identifier[randn] (* identifier[data] . identifier[shape] )* identifier[std] keyword[else] : identifier[arr] [:,- literal[int] ]= identifier[N] . identifier[random] . identifier[randn] ( identifier[data] . identifier[shape] [ literal[int] ])* identifier[std] identifier[boot_dist] . identifier[append] ( identifier[func] ( identifier[data] + identifier[arr] )) keyword[return] identifier[N] . identifier[array] ( identifier[boot_dist] )
def bootstrap_noise(data, func, n=10000, std=1, symmetric=True): """ Bootstrap by adding noise """ boot_dist = [] arr = N.zeros(data.shape) for i in range(n): if symmetric: # Noise on all three axes arr = N.random.randn(*data.shape) * std # depends on [control=['if'], data=[]] else: # Only z-coordinate noise arr[:, -1] = N.random.randn(data.shape[0]) * std boot_dist.append(func(data + arr)) # depends on [control=['for'], data=[]] return N.array(boot_dist)
def get_console(request, console_type, instance): """Get a tuple of console url and console type.""" if console_type == 'AUTO': check_consoles = CONSOLES else: try: check_consoles = {console_type: CONSOLES[console_type]} except KeyError: msg = _('Console type "%s" not supported.') % console_type raise exceptions.NotAvailable(msg) # Ugly workaround due novaclient API change from 2.17 to 2.18. try: httpnotimplemented = nova_exception.HttpNotImplemented except AttributeError: httpnotimplemented = nova_exception.HTTPNotImplemented for con_type, api_call in check_consoles.items(): try: console = api_call(request, instance.id) # If not supported, don't log it to avoid lot of errors in case # of AUTO. except httpnotimplemented: continue except Exception: LOG.debug('Console not available', exc_info=True) continue if con_type == 'SERIAL': console_url = console.url else: console_url = "%s&%s(%s)" % ( console.url, urlencode({'title': getattr(instance, "name", "")}), instance.id) return (con_type, console_url) raise exceptions.NotAvailable(_('No available console found.'))
def function[get_console, parameter[request, console_type, instance]]: constant[Get a tuple of console url and console type.] if compare[name[console_type] equal[==] constant[AUTO]] begin[:] variable[check_consoles] assign[=] name[CONSOLES] <ast.Try object at 0x7da18ede42e0> for taget[tuple[[<ast.Name object at 0x7da18ede4d60>, <ast.Name object at 0x7da18ede59c0>]]] in starred[call[name[check_consoles].items, parameter[]]] begin[:] <ast.Try object at 0x7da18ede5390> if compare[name[con_type] equal[==] constant[SERIAL]] begin[:] variable[console_url] assign[=] name[console].url return[tuple[[<ast.Name object at 0x7da1b1985000>, <ast.Name object at 0x7da1b1985390>]]] <ast.Raise object at 0x7da1b1985b70>
keyword[def] identifier[get_console] ( identifier[request] , identifier[console_type] , identifier[instance] ): literal[string] keyword[if] identifier[console_type] == literal[string] : identifier[check_consoles] = identifier[CONSOLES] keyword[else] : keyword[try] : identifier[check_consoles] ={ identifier[console_type] : identifier[CONSOLES] [ identifier[console_type] ]} keyword[except] identifier[KeyError] : identifier[msg] = identifier[_] ( literal[string] )% identifier[console_type] keyword[raise] identifier[exceptions] . identifier[NotAvailable] ( identifier[msg] ) keyword[try] : identifier[httpnotimplemented] = identifier[nova_exception] . identifier[HttpNotImplemented] keyword[except] identifier[AttributeError] : identifier[httpnotimplemented] = identifier[nova_exception] . identifier[HTTPNotImplemented] keyword[for] identifier[con_type] , identifier[api_call] keyword[in] identifier[check_consoles] . identifier[items] (): keyword[try] : identifier[console] = identifier[api_call] ( identifier[request] , identifier[instance] . identifier[id] ) keyword[except] identifier[httpnotimplemented] : keyword[continue] keyword[except] identifier[Exception] : identifier[LOG] . identifier[debug] ( literal[string] , identifier[exc_info] = keyword[True] ) keyword[continue] keyword[if] identifier[con_type] == literal[string] : identifier[console_url] = identifier[console] . identifier[url] keyword[else] : identifier[console_url] = literal[string] %( identifier[console] . identifier[url] , identifier[urlencode] ({ literal[string] : identifier[getattr] ( identifier[instance] , literal[string] , literal[string] )}), identifier[instance] . identifier[id] ) keyword[return] ( identifier[con_type] , identifier[console_url] ) keyword[raise] identifier[exceptions] . identifier[NotAvailable] ( identifier[_] ( literal[string] ))
def get_console(request, console_type, instance): """Get a tuple of console url and console type.""" if console_type == 'AUTO': check_consoles = CONSOLES # depends on [control=['if'], data=[]] else: try: check_consoles = {console_type: CONSOLES[console_type]} # depends on [control=['try'], data=[]] except KeyError: msg = _('Console type "%s" not supported.') % console_type raise exceptions.NotAvailable(msg) # depends on [control=['except'], data=[]] # Ugly workaround due novaclient API change from 2.17 to 2.18. try: httpnotimplemented = nova_exception.HttpNotImplemented # depends on [control=['try'], data=[]] except AttributeError: httpnotimplemented = nova_exception.HTTPNotImplemented # depends on [control=['except'], data=[]] for (con_type, api_call) in check_consoles.items(): try: console = api_call(request, instance.id) # depends on [control=['try'], data=[]] # If not supported, don't log it to avoid lot of errors in case # of AUTO. except httpnotimplemented: continue # depends on [control=['except'], data=[]] except Exception: LOG.debug('Console not available', exc_info=True) continue # depends on [control=['except'], data=[]] if con_type == 'SERIAL': console_url = console.url # depends on [control=['if'], data=[]] else: console_url = '%s&%s(%s)' % (console.url, urlencode({'title': getattr(instance, 'name', '')}), instance.id) return (con_type, console_url) # depends on [control=['for'], data=[]] raise exceptions.NotAvailable(_('No available console found.'))
def update_item(self, payload, last_modified=None): """ Update an existing item Accepts one argument, a dict containing Item data """ to_send = self.check_items([payload])[0] if last_modified is None: modified = payload["version"] else: modified = last_modified ident = payload["key"] headers = {"If-Unmodified-Since-Version": str(modified)} headers.update(self.default_headers()) req = requests.patch( url=self.endpoint + "/{t}/{u}/items/{id}".format( t=self.library_type, u=self.library_id, id=ident ), headers=headers, data=json.dumps(to_send), ) self.request = req try: req.raise_for_status() except requests.exceptions.HTTPError: error_handler(req) return True
def function[update_item, parameter[self, payload, last_modified]]: constant[ Update an existing item Accepts one argument, a dict containing Item data ] variable[to_send] assign[=] call[call[name[self].check_items, parameter[list[[<ast.Name object at 0x7da207f9ab90>]]]]][constant[0]] if compare[name[last_modified] is constant[None]] begin[:] variable[modified] assign[=] call[name[payload]][constant[version]] variable[ident] assign[=] call[name[payload]][constant[key]] variable[headers] assign[=] dictionary[[<ast.Constant object at 0x7da207f9b6d0>], [<ast.Call object at 0x7da207f9bd90>]] call[name[headers].update, parameter[call[name[self].default_headers, parameter[]]]] variable[req] assign[=] call[name[requests].patch, parameter[]] name[self].request assign[=] name[req] <ast.Try object at 0x7da207f98580> return[constant[True]]
keyword[def] identifier[update_item] ( identifier[self] , identifier[payload] , identifier[last_modified] = keyword[None] ): literal[string] identifier[to_send] = identifier[self] . identifier[check_items] ([ identifier[payload] ])[ literal[int] ] keyword[if] identifier[last_modified] keyword[is] keyword[None] : identifier[modified] = identifier[payload] [ literal[string] ] keyword[else] : identifier[modified] = identifier[last_modified] identifier[ident] = identifier[payload] [ literal[string] ] identifier[headers] ={ literal[string] : identifier[str] ( identifier[modified] )} identifier[headers] . identifier[update] ( identifier[self] . identifier[default_headers] ()) identifier[req] = identifier[requests] . identifier[patch] ( identifier[url] = identifier[self] . identifier[endpoint] + literal[string] . identifier[format] ( identifier[t] = identifier[self] . identifier[library_type] , identifier[u] = identifier[self] . identifier[library_id] , identifier[id] = identifier[ident] ), identifier[headers] = identifier[headers] , identifier[data] = identifier[json] . identifier[dumps] ( identifier[to_send] ), ) identifier[self] . identifier[request] = identifier[req] keyword[try] : identifier[req] . identifier[raise_for_status] () keyword[except] identifier[requests] . identifier[exceptions] . identifier[HTTPError] : identifier[error_handler] ( identifier[req] ) keyword[return] keyword[True]
def update_item(self, payload, last_modified=None): """ Update an existing item Accepts one argument, a dict containing Item data """ to_send = self.check_items([payload])[0] if last_modified is None: modified = payload['version'] # depends on [control=['if'], data=[]] else: modified = last_modified ident = payload['key'] headers = {'If-Unmodified-Since-Version': str(modified)} headers.update(self.default_headers()) req = requests.patch(url=self.endpoint + '/{t}/{u}/items/{id}'.format(t=self.library_type, u=self.library_id, id=ident), headers=headers, data=json.dumps(to_send)) self.request = req try: req.raise_for_status() # depends on [control=['try'], data=[]] except requests.exceptions.HTTPError: error_handler(req) # depends on [control=['except'], data=[]] return True
def __scan_func(self, args_info): """Collect information about accepted arguments in following format: ( (<argument name>, <accepted types and values>), (<argument name>, <accepted types and values>), ... ) Args: args_info (inspect.FullArgSpec): Information about function arguments. """ # Process args. for i, accepted_arg_vals in enumerate(self.accepted_arg_values): # Wrap each accepted value in the list if yet not wrapped. accepted_arg_vals = self.__wrap_accepted_val(accepted_arg_vals) # Add default value (if exists) in list of accepted values. if args_info.defaults: def_range = len(args_info.defaults) - len(args_info.args[i:]) if def_range >= 0: self.optional_args.append(i) accepted_value = args_info.defaults[def_range] accepted_arg_vals.append(accepted_value) # Try to detect current argument name. if len(args_info.args) > i: arg_name = args_info.args[i] else: arg_name = None self.optional_args.append(i) # Save info about current argument and his accepted values. self.accepted_args.append((arg_name, accepted_arg_vals)) # Process kwargs. for arg_name, accepted_arg_vals in self.accepted_kwargs_values.items(): # Wrap each accepted value in the list if yet not wrapped. accepted_arg_vals = self.__wrap_accepted_val(accepted_arg_vals) # Mark current argument as optional. i = len(self.accepted_args) self.optional_args.append(i) # Save info about current argument and his accepted values. self.accepted_args.append((arg_name, accepted_arg_vals))
def function[__scan_func, parameter[self, args_info]]: constant[Collect information about accepted arguments in following format: ( (<argument name>, <accepted types and values>), (<argument name>, <accepted types and values>), ... ) Args: args_info (inspect.FullArgSpec): Information about function arguments. ] for taget[tuple[[<ast.Name object at 0x7da1b25564d0>, <ast.Name object at 0x7da1b2555f00>]]] in starred[call[name[enumerate], parameter[name[self].accepted_arg_values]]] begin[:] variable[accepted_arg_vals] assign[=] call[name[self].__wrap_accepted_val, parameter[name[accepted_arg_vals]]] if name[args_info].defaults begin[:] variable[def_range] assign[=] binary_operation[call[name[len], parameter[name[args_info].defaults]] - call[name[len], parameter[call[name[args_info].args][<ast.Slice object at 0x7da1b2506110>]]]] if compare[name[def_range] greater_or_equal[>=] constant[0]] begin[:] call[name[self].optional_args.append, parameter[name[i]]] variable[accepted_value] assign[=] call[name[args_info].defaults][name[def_range]] call[name[accepted_arg_vals].append, parameter[name[accepted_value]]] if compare[call[name[len], parameter[name[args_info].args]] greater[>] name[i]] begin[:] variable[arg_name] assign[=] call[name[args_info].args][name[i]] call[name[self].accepted_args.append, parameter[tuple[[<ast.Name object at 0x7da1b221fe50>, <ast.Name object at 0x7da1b221c370>]]]] for taget[tuple[[<ast.Name object at 0x7da1b221c3a0>, <ast.Name object at 0x7da1b221c5e0>]]] in starred[call[name[self].accepted_kwargs_values.items, parameter[]]] begin[:] variable[accepted_arg_vals] assign[=] call[name[self].__wrap_accepted_val, parameter[name[accepted_arg_vals]]] variable[i] assign[=] call[name[len], parameter[name[self].accepted_args]] call[name[self].optional_args.append, parameter[name[i]]] call[name[self].accepted_args.append, parameter[tuple[[<ast.Name object at 0x7da1b2381fc0>, <ast.Name object at 0x7da1b2381900>]]]]
keyword[def] identifier[__scan_func] ( identifier[self] , identifier[args_info] ): literal[string] keyword[for] identifier[i] , identifier[accepted_arg_vals] keyword[in] identifier[enumerate] ( identifier[self] . identifier[accepted_arg_values] ): identifier[accepted_arg_vals] = identifier[self] . identifier[__wrap_accepted_val] ( identifier[accepted_arg_vals] ) keyword[if] identifier[args_info] . identifier[defaults] : identifier[def_range] = identifier[len] ( identifier[args_info] . identifier[defaults] )- identifier[len] ( identifier[args_info] . identifier[args] [ identifier[i] :]) keyword[if] identifier[def_range] >= literal[int] : identifier[self] . identifier[optional_args] . identifier[append] ( identifier[i] ) identifier[accepted_value] = identifier[args_info] . identifier[defaults] [ identifier[def_range] ] identifier[accepted_arg_vals] . identifier[append] ( identifier[accepted_value] ) keyword[if] identifier[len] ( identifier[args_info] . identifier[args] )> identifier[i] : identifier[arg_name] = identifier[args_info] . identifier[args] [ identifier[i] ] keyword[else] : identifier[arg_name] = keyword[None] identifier[self] . identifier[optional_args] . identifier[append] ( identifier[i] ) identifier[self] . identifier[accepted_args] . identifier[append] (( identifier[arg_name] , identifier[accepted_arg_vals] )) keyword[for] identifier[arg_name] , identifier[accepted_arg_vals] keyword[in] identifier[self] . identifier[accepted_kwargs_values] . identifier[items] (): identifier[accepted_arg_vals] = identifier[self] . identifier[__wrap_accepted_val] ( identifier[accepted_arg_vals] ) identifier[i] = identifier[len] ( identifier[self] . identifier[accepted_args] ) identifier[self] . identifier[optional_args] . identifier[append] ( identifier[i] ) identifier[self] . identifier[accepted_args] . identifier[append] (( identifier[arg_name] , identifier[accepted_arg_vals] ))
def __scan_func(self, args_info): """Collect information about accepted arguments in following format: ( (<argument name>, <accepted types and values>), (<argument name>, <accepted types and values>), ... ) Args: args_info (inspect.FullArgSpec): Information about function arguments. """ # Process args. for (i, accepted_arg_vals) in enumerate(self.accepted_arg_values): # Wrap each accepted value in the list if yet not wrapped. accepted_arg_vals = self.__wrap_accepted_val(accepted_arg_vals) # Add default value (if exists) in list of accepted values. if args_info.defaults: def_range = len(args_info.defaults) - len(args_info.args[i:]) if def_range >= 0: self.optional_args.append(i) accepted_value = args_info.defaults[def_range] accepted_arg_vals.append(accepted_value) # depends on [control=['if'], data=['def_range']] # depends on [control=['if'], data=[]] # Try to detect current argument name. if len(args_info.args) > i: arg_name = args_info.args[i] # depends on [control=['if'], data=['i']] else: arg_name = None self.optional_args.append(i) # Save info about current argument and his accepted values. self.accepted_args.append((arg_name, accepted_arg_vals)) # depends on [control=['for'], data=[]] # Process kwargs. for (arg_name, accepted_arg_vals) in self.accepted_kwargs_values.items(): # Wrap each accepted value in the list if yet not wrapped. accepted_arg_vals = self.__wrap_accepted_val(accepted_arg_vals) # Mark current argument as optional. i = len(self.accepted_args) self.optional_args.append(i) # Save info about current argument and his accepted values. self.accepted_args.append((arg_name, accepted_arg_vals)) # depends on [control=['for'], data=[]]
def atlas_peer_get_request_count( peer_hostport, peer_table=None ): """ How many times have we contacted this peer? """ with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return 0 count = 0 for (t, r) in ptbl[peer_hostport]['time']: if r: count += 1 return count
def function[atlas_peer_get_request_count, parameter[peer_hostport, peer_table]]: constant[ How many times have we contacted this peer? ] with call[name[AtlasPeerTableLocked], parameter[name[peer_table]]] begin[:] if compare[name[peer_hostport] <ast.NotIn object at 0x7da2590d7190> call[name[ptbl].keys, parameter[]]] begin[:] return[constant[0]] variable[count] assign[=] constant[0] for taget[tuple[[<ast.Name object at 0x7da1b1633e50>, <ast.Name object at 0x7da1b16307c0>]]] in starred[call[call[name[ptbl]][name[peer_hostport]]][constant[time]]] begin[:] if name[r] begin[:] <ast.AugAssign object at 0x7da1b16d1d50> return[name[count]]
keyword[def] identifier[atlas_peer_get_request_count] ( identifier[peer_hostport] , identifier[peer_table] = keyword[None] ): literal[string] keyword[with] identifier[AtlasPeerTableLocked] ( identifier[peer_table] ) keyword[as] identifier[ptbl] : keyword[if] identifier[peer_hostport] keyword[not] keyword[in] identifier[ptbl] . identifier[keys] (): keyword[return] literal[int] identifier[count] = literal[int] keyword[for] ( identifier[t] , identifier[r] ) keyword[in] identifier[ptbl] [ identifier[peer_hostport] ][ literal[string] ]: keyword[if] identifier[r] : identifier[count] += literal[int] keyword[return] identifier[count]
def atlas_peer_get_request_count(peer_hostport, peer_table=None): """ How many times have we contacted this peer? """ with AtlasPeerTableLocked(peer_table) as ptbl: if peer_hostport not in ptbl.keys(): return 0 # depends on [control=['if'], data=[]] count = 0 for (t, r) in ptbl[peer_hostport]['time']: if r: count += 1 # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] # depends on [control=['with'], data=['ptbl']] return count
async def insertTask(self, *args, **kwargs): """ Insert Task into Index Insert a task into the index. If the new rank is less than the existing rank at the given index path, the task is not indexed but the response is still 200 OK. Please see the introduction above for information about indexing successfully completed tasks automatically using custom routes. This method takes input: ``v1/insert-task-request.json#`` This method gives output: ``v1/indexed-task-response.json#`` This method is ``stable`` """ return await self._makeApiCall(self.funcinfo["insertTask"], *args, **kwargs)
<ast.AsyncFunctionDef object at 0x7da18f00c1c0>
keyword[async] keyword[def] identifier[insertTask] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ): literal[string] keyword[return] keyword[await] identifier[self] . identifier[_makeApiCall] ( identifier[self] . identifier[funcinfo] [ literal[string] ],* identifier[args] ,** identifier[kwargs] )
async def insertTask(self, *args, **kwargs): """ Insert Task into Index Insert a task into the index. If the new rank is less than the existing rank at the given index path, the task is not indexed but the response is still 200 OK. Please see the introduction above for information about indexing successfully completed tasks automatically using custom routes. This method takes input: ``v1/insert-task-request.json#`` This method gives output: ``v1/indexed-task-response.json#`` This method is ``stable`` """ return await self._makeApiCall(self.funcinfo['insertTask'], *args, **kwargs)
def is_valid_article_slug(article, language, slug): """Validates given slug depending on settings. """ from ..models import Title qs = Title.objects.filter(slug=slug, language=language) if article.pk: qs = qs.exclude(Q(language=language) & Q(article=article)) qs = qs.exclude(article__publisher_public=article) if qs.count(): return False return True
def function[is_valid_article_slug, parameter[article, language, slug]]: constant[Validates given slug depending on settings. ] from relative_module[models] import module[Title] variable[qs] assign[=] call[name[Title].objects.filter, parameter[]] if name[article].pk begin[:] variable[qs] assign[=] call[name[qs].exclude, parameter[binary_operation[call[name[Q], parameter[]] <ast.BitAnd object at 0x7da2590d6b60> call[name[Q], parameter[]]]]] variable[qs] assign[=] call[name[qs].exclude, parameter[]] if call[name[qs].count, parameter[]] begin[:] return[constant[False]] return[constant[True]]
keyword[def] identifier[is_valid_article_slug] ( identifier[article] , identifier[language] , identifier[slug] ): literal[string] keyword[from] .. identifier[models] keyword[import] identifier[Title] identifier[qs] = identifier[Title] . identifier[objects] . identifier[filter] ( identifier[slug] = identifier[slug] , identifier[language] = identifier[language] ) keyword[if] identifier[article] . identifier[pk] : identifier[qs] = identifier[qs] . identifier[exclude] ( identifier[Q] ( identifier[language] = identifier[language] )& identifier[Q] ( identifier[article] = identifier[article] )) identifier[qs] = identifier[qs] . identifier[exclude] ( identifier[article__publisher_public] = identifier[article] ) keyword[if] identifier[qs] . identifier[count] (): keyword[return] keyword[False] keyword[return] keyword[True]
def is_valid_article_slug(article, language, slug): """Validates given slug depending on settings. """ from ..models import Title qs = Title.objects.filter(slug=slug, language=language) if article.pk: qs = qs.exclude(Q(language=language) & Q(article=article)) qs = qs.exclude(article__publisher_public=article) # depends on [control=['if'], data=[]] if qs.count(): return False # depends on [control=['if'], data=[]] return True
def advance(self, blocksize): """ Add blocksize seconds more to the buffer, push blocksize seconds from the beginning. Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel Returns ------- status: boolean Returns True if all of the status information if valid, False if any is not. """ try: if self.increment_update_cache: self.update_cache_by_increment(blocksize) ts = DataBuffer.advance(self, blocksize) return self.check_valid(ts) except RuntimeError: self.null_advance(blocksize) return False
def function[advance, parameter[self, blocksize]]: constant[ Add blocksize seconds more to the buffer, push blocksize seconds from the beginning. Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel Returns ------- status: boolean Returns True if all of the status information if valid, False if any is not. ] <ast.Try object at 0x7da20c6e5c00>
keyword[def] identifier[advance] ( identifier[self] , identifier[blocksize] ): literal[string] keyword[try] : keyword[if] identifier[self] . identifier[increment_update_cache] : identifier[self] . identifier[update_cache_by_increment] ( identifier[blocksize] ) identifier[ts] = identifier[DataBuffer] . identifier[advance] ( identifier[self] , identifier[blocksize] ) keyword[return] identifier[self] . identifier[check_valid] ( identifier[ts] ) keyword[except] identifier[RuntimeError] : identifier[self] . identifier[null_advance] ( identifier[blocksize] ) keyword[return] keyword[False]
def advance(self, blocksize): """ Add blocksize seconds more to the buffer, push blocksize seconds from the beginning. Parameters ---------- blocksize: int The number of seconds to attempt to read from the channel Returns ------- status: boolean Returns True if all of the status information if valid, False if any is not. """ try: if self.increment_update_cache: self.update_cache_by_increment(blocksize) # depends on [control=['if'], data=[]] ts = DataBuffer.advance(self, blocksize) return self.check_valid(ts) # depends on [control=['try'], data=[]] except RuntimeError: self.null_advance(blocksize) return False # depends on [control=['except'], data=[]]
def validate_address(self, addr, **kwargs): """ Validates if the considered string is a valid NEO address. :param hex: string containing a potential NEO address :type hex: str :return: dictionary containing the result of the verification :rtype: dictionary """ return self._call(JSONRPCMethods.VALIDATE_ADDRESS.value, [addr, ], **kwargs)
def function[validate_address, parameter[self, addr]]: constant[ Validates if the considered string is a valid NEO address. :param hex: string containing a potential NEO address :type hex: str :return: dictionary containing the result of the verification :rtype: dictionary ] return[call[name[self]._call, parameter[name[JSONRPCMethods].VALIDATE_ADDRESS.value, list[[<ast.Name object at 0x7da20c6ab250>]]]]]
keyword[def] identifier[validate_address] ( identifier[self] , identifier[addr] ,** identifier[kwargs] ): literal[string] keyword[return] identifier[self] . identifier[_call] ( identifier[JSONRPCMethods] . identifier[VALIDATE_ADDRESS] . identifier[value] ,[ identifier[addr] ,],** identifier[kwargs] )
def validate_address(self, addr, **kwargs): """ Validates if the considered string is a valid NEO address. :param hex: string containing a potential NEO address :type hex: str :return: dictionary containing the result of the verification :rtype: dictionary """ return self._call(JSONRPCMethods.VALIDATE_ADDRESS.value, [addr], **kwargs)
def external_system_identifiers2marc(self, key, value): """Populate the ``035`` MARC field. Also populates the ``970`` MARC field through side effects and an extra ``id_dict`` dictionary that holds potentially duplicate IDs that are post-processed in a filter. """ def _is_scheme_cernkey(id_, schema): return schema == 'CERNKEY' def _is_scheme_spires(id_, schema): return schema == 'SPIRES' result_035 = self.get('035', []) id_dict = self.get('id_dict', defaultdict(list)) result_970 = self.get('970', []) values = force_list(value) for value in values: id_ = value.get('value') schema = value.get('schema') if _is_scheme_spires(id_, schema): result_970.append({ 'a': id_, }) elif _is_scheme_cernkey(id_, schema): result_035.append({ '9': 'CERNKEY', 'z': id_, }) else: id_dict[schema].append(id_) self['970'] = result_970 self['id_dict'] = id_dict return result_035
def function[external_system_identifiers2marc, parameter[self, key, value]]: constant[Populate the ``035`` MARC field. Also populates the ``970`` MARC field through side effects and an extra ``id_dict`` dictionary that holds potentially duplicate IDs that are post-processed in a filter. ] def function[_is_scheme_cernkey, parameter[id_, schema]]: return[compare[name[schema] equal[==] constant[CERNKEY]]] def function[_is_scheme_spires, parameter[id_, schema]]: return[compare[name[schema] equal[==] constant[SPIRES]]] variable[result_035] assign[=] call[name[self].get, parameter[constant[035], list[[]]]] variable[id_dict] assign[=] call[name[self].get, parameter[constant[id_dict], call[name[defaultdict], parameter[name[list]]]]] variable[result_970] assign[=] call[name[self].get, parameter[constant[970], list[[]]]] variable[values] assign[=] call[name[force_list], parameter[name[value]]] for taget[name[value]] in starred[name[values]] begin[:] variable[id_] assign[=] call[name[value].get, parameter[constant[value]]] variable[schema] assign[=] call[name[value].get, parameter[constant[schema]]] if call[name[_is_scheme_spires], parameter[name[id_], name[schema]]] begin[:] call[name[result_970].append, parameter[dictionary[[<ast.Constant object at 0x7da20e9567d0>], [<ast.Name object at 0x7da20e955a20>]]]] call[name[self]][constant[970]] assign[=] name[result_970] call[name[self]][constant[id_dict]] assign[=] name[id_dict] return[name[result_035]]
keyword[def] identifier[external_system_identifiers2marc] ( identifier[self] , identifier[key] , identifier[value] ): literal[string] keyword[def] identifier[_is_scheme_cernkey] ( identifier[id_] , identifier[schema] ): keyword[return] identifier[schema] == literal[string] keyword[def] identifier[_is_scheme_spires] ( identifier[id_] , identifier[schema] ): keyword[return] identifier[schema] == literal[string] identifier[result_035] = identifier[self] . identifier[get] ( literal[string] ,[]) identifier[id_dict] = identifier[self] . identifier[get] ( literal[string] , identifier[defaultdict] ( identifier[list] )) identifier[result_970] = identifier[self] . identifier[get] ( literal[string] ,[]) identifier[values] = identifier[force_list] ( identifier[value] ) keyword[for] identifier[value] keyword[in] identifier[values] : identifier[id_] = identifier[value] . identifier[get] ( literal[string] ) identifier[schema] = identifier[value] . identifier[get] ( literal[string] ) keyword[if] identifier[_is_scheme_spires] ( identifier[id_] , identifier[schema] ): identifier[result_970] . identifier[append] ({ literal[string] : identifier[id_] , }) keyword[elif] identifier[_is_scheme_cernkey] ( identifier[id_] , identifier[schema] ): identifier[result_035] . identifier[append] ({ literal[string] : literal[string] , literal[string] : identifier[id_] , }) keyword[else] : identifier[id_dict] [ identifier[schema] ]. identifier[append] ( identifier[id_] ) identifier[self] [ literal[string] ]= identifier[result_970] identifier[self] [ literal[string] ]= identifier[id_dict] keyword[return] identifier[result_035]
def external_system_identifiers2marc(self, key, value): """Populate the ``035`` MARC field. Also populates the ``970`` MARC field through side effects and an extra ``id_dict`` dictionary that holds potentially duplicate IDs that are post-processed in a filter. """ def _is_scheme_cernkey(id_, schema): return schema == 'CERNKEY' def _is_scheme_spires(id_, schema): return schema == 'SPIRES' result_035 = self.get('035', []) id_dict = self.get('id_dict', defaultdict(list)) result_970 = self.get('970', []) values = force_list(value) for value in values: id_ = value.get('value') schema = value.get('schema') if _is_scheme_spires(id_, schema): result_970.append({'a': id_}) # depends on [control=['if'], data=[]] elif _is_scheme_cernkey(id_, schema): result_035.append({'9': 'CERNKEY', 'z': id_}) # depends on [control=['if'], data=[]] else: id_dict[schema].append(id_) # depends on [control=['for'], data=['value']] self['970'] = result_970 self['id_dict'] = id_dict return result_035
def sorted_nicely(l): """ Sort the given iterable in the way that humans expect. http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ] return sorted(l, key = alphanum_key)
def function[sorted_nicely, parameter[l]]: constant[ Sort the given iterable in the way that humans expect. http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ ] variable[convert] assign[=] <ast.Lambda object at 0x7da18f58f2e0> variable[alphanum_key] assign[=] <ast.Lambda object at 0x7da2043456f0> return[call[name[sorted], parameter[name[l]]]]
keyword[def] identifier[sorted_nicely] ( identifier[l] ): literal[string] identifier[convert] = keyword[lambda] identifier[text] : identifier[int] ( identifier[text] ) keyword[if] identifier[text] . identifier[isdigit] () keyword[else] identifier[text] identifier[alphanum_key] = keyword[lambda] identifier[key] :[ identifier[convert] ( identifier[c] ) keyword[for] identifier[c] keyword[in] identifier[re] . identifier[split] ( literal[string] , identifier[key] )] keyword[return] identifier[sorted] ( identifier[l] , identifier[key] = identifier[alphanum_key] )
def sorted_nicely(l): """ Sort the given iterable in the way that humans expect. http://blog.codinghorror.com/sorting-for-humans-natural-sort-order/ """ convert = lambda text: int(text) if text.isdigit() else text alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] return sorted(l, key=alphanum_key)
def _reset_flow_uow(self, freerun_entry, uow, flow_request): """ there can be multiple freeruns for a single combination of workflow+step+timeperiod hence, we have to *recycle* finished UOW """ process_entry = context.process_context[freerun_entry.process_name] arguments = process_entry.arguments arguments.update(freerun_entry.arguments) arguments.update(flow_request.arguments) uow.created_at = datetime.utcnow() uow.submitted_at = datetime.utcnow() uow.state = unit_of_work.STATE_REQUESTED uow.unit_of_work_type = unit_of_work.TYPE_FREERUN del uow.started_at del uow.finished_at del uow.number_of_aggregated_documents del uow.number_of_processed_documents uow.number_of_retries = 0 uow.arguments = arguments self.uow_dao.update(uow)
def function[_reset_flow_uow, parameter[self, freerun_entry, uow, flow_request]]: constant[ there can be multiple freeruns for a single combination of workflow+step+timeperiod hence, we have to *recycle* finished UOW ] variable[process_entry] assign[=] call[name[context].process_context][name[freerun_entry].process_name] variable[arguments] assign[=] name[process_entry].arguments call[name[arguments].update, parameter[name[freerun_entry].arguments]] call[name[arguments].update, parameter[name[flow_request].arguments]] name[uow].created_at assign[=] call[name[datetime].utcnow, parameter[]] name[uow].submitted_at assign[=] call[name[datetime].utcnow, parameter[]] name[uow].state assign[=] name[unit_of_work].STATE_REQUESTED name[uow].unit_of_work_type assign[=] name[unit_of_work].TYPE_FREERUN <ast.Delete object at 0x7da207f98520> <ast.Delete object at 0x7da207f9a620> <ast.Delete object at 0x7da207f9ace0> <ast.Delete object at 0x7da207f9a920> name[uow].number_of_retries assign[=] constant[0] name[uow].arguments assign[=] name[arguments] call[name[self].uow_dao.update, parameter[name[uow]]]
keyword[def] identifier[_reset_flow_uow] ( identifier[self] , identifier[freerun_entry] , identifier[uow] , identifier[flow_request] ): literal[string] identifier[process_entry] = identifier[context] . identifier[process_context] [ identifier[freerun_entry] . identifier[process_name] ] identifier[arguments] = identifier[process_entry] . identifier[arguments] identifier[arguments] . identifier[update] ( identifier[freerun_entry] . identifier[arguments] ) identifier[arguments] . identifier[update] ( identifier[flow_request] . identifier[arguments] ) identifier[uow] . identifier[created_at] = identifier[datetime] . identifier[utcnow] () identifier[uow] . identifier[submitted_at] = identifier[datetime] . identifier[utcnow] () identifier[uow] . identifier[state] = identifier[unit_of_work] . identifier[STATE_REQUESTED] identifier[uow] . identifier[unit_of_work_type] = identifier[unit_of_work] . identifier[TYPE_FREERUN] keyword[del] identifier[uow] . identifier[started_at] keyword[del] identifier[uow] . identifier[finished_at] keyword[del] identifier[uow] . identifier[number_of_aggregated_documents] keyword[del] identifier[uow] . identifier[number_of_processed_documents] identifier[uow] . identifier[number_of_retries] = literal[int] identifier[uow] . identifier[arguments] = identifier[arguments] identifier[self] . identifier[uow_dao] . identifier[update] ( identifier[uow] )
def _reset_flow_uow(self, freerun_entry, uow, flow_request): """ there can be multiple freeruns for a single combination of workflow+step+timeperiod hence, we have to *recycle* finished UOW """ process_entry = context.process_context[freerun_entry.process_name] arguments = process_entry.arguments arguments.update(freerun_entry.arguments) arguments.update(flow_request.arguments) uow.created_at = datetime.utcnow() uow.submitted_at = datetime.utcnow() uow.state = unit_of_work.STATE_REQUESTED uow.unit_of_work_type = unit_of_work.TYPE_FREERUN del uow.started_at del uow.finished_at del uow.number_of_aggregated_documents del uow.number_of_processed_documents uow.number_of_retries = 0 uow.arguments = arguments self.uow_dao.update(uow)
def qos_map_dscp_cos_mark_to(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos") map = ET.SubElement(qos, "map") dscp_cos = ET.SubElement(map, "dscp-cos") dscp_cos_map_name_key = ET.SubElement(dscp_cos, "dscp-cos-map-name") dscp_cos_map_name_key.text = kwargs.pop('dscp_cos_map_name') mark = ET.SubElement(dscp_cos, "mark") dscp_in_values_key = ET.SubElement(mark, "dscp-in-values") dscp_in_values_key.text = kwargs.pop('dscp_in_values') to = ET.SubElement(mark, "to") to.text = kwargs.pop('to') callback = kwargs.pop('callback', self._callback) return callback(config)
def function[qos_map_dscp_cos_mark_to, parameter[self]]: constant[Auto Generated Code ] variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]] variable[qos] assign[=] call[name[ET].SubElement, parameter[name[config], constant[qos]]] variable[map] assign[=] call[name[ET].SubElement, parameter[name[qos], constant[map]]] variable[dscp_cos] assign[=] call[name[ET].SubElement, parameter[name[map], constant[dscp-cos]]] variable[dscp_cos_map_name_key] assign[=] call[name[ET].SubElement, parameter[name[dscp_cos], constant[dscp-cos-map-name]]] name[dscp_cos_map_name_key].text assign[=] call[name[kwargs].pop, parameter[constant[dscp_cos_map_name]]] variable[mark] assign[=] call[name[ET].SubElement, parameter[name[dscp_cos], constant[mark]]] variable[dscp_in_values_key] assign[=] call[name[ET].SubElement, parameter[name[mark], constant[dscp-in-values]]] name[dscp_in_values_key].text assign[=] call[name[kwargs].pop, parameter[constant[dscp_in_values]]] variable[to] assign[=] call[name[ET].SubElement, parameter[name[mark], constant[to]]] name[to].text assign[=] call[name[kwargs].pop, parameter[constant[to]]] variable[callback] assign[=] call[name[kwargs].pop, parameter[constant[callback], name[self]._callback]] return[call[name[callback], parameter[name[config]]]]
keyword[def] identifier[qos_map_dscp_cos_mark_to] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[config] = identifier[ET] . identifier[Element] ( literal[string] ) identifier[qos] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , identifier[xmlns] = literal[string] ) identifier[map] = identifier[ET] . identifier[SubElement] ( identifier[qos] , literal[string] ) identifier[dscp_cos] = identifier[ET] . identifier[SubElement] ( identifier[map] , literal[string] ) identifier[dscp_cos_map_name_key] = identifier[ET] . identifier[SubElement] ( identifier[dscp_cos] , literal[string] ) identifier[dscp_cos_map_name_key] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[mark] = identifier[ET] . identifier[SubElement] ( identifier[dscp_cos] , literal[string] ) identifier[dscp_in_values_key] = identifier[ET] . identifier[SubElement] ( identifier[mark] , literal[string] ) identifier[dscp_in_values_key] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[to] = identifier[ET] . identifier[SubElement] ( identifier[mark] , literal[string] ) identifier[to] . identifier[text] = identifier[kwargs] . identifier[pop] ( literal[string] ) identifier[callback] = identifier[kwargs] . identifier[pop] ( literal[string] , identifier[self] . identifier[_callback] ) keyword[return] identifier[callback] ( identifier[config] )
def qos_map_dscp_cos_mark_to(self, **kwargs): """Auto Generated Code """ config = ET.Element('config') qos = ET.SubElement(config, 'qos', xmlns='urn:brocade.com:mgmt:brocade-qos') map = ET.SubElement(qos, 'map') dscp_cos = ET.SubElement(map, 'dscp-cos') dscp_cos_map_name_key = ET.SubElement(dscp_cos, 'dscp-cos-map-name') dscp_cos_map_name_key.text = kwargs.pop('dscp_cos_map_name') mark = ET.SubElement(dscp_cos, 'mark') dscp_in_values_key = ET.SubElement(mark, 'dscp-in-values') dscp_in_values_key.text = kwargs.pop('dscp_in_values') to = ET.SubElement(mark, 'to') to.text = kwargs.pop('to') callback = kwargs.pop('callback', self._callback) return callback(config)
def list_security_groups(self, retrieve_all=True, **_params): """Fetches a list of all security groups for a project.""" return self.list('security_groups', self.security_groups_path, retrieve_all, **_params)
def function[list_security_groups, parameter[self, retrieve_all]]: constant[Fetches a list of all security groups for a project.] return[call[name[self].list, parameter[constant[security_groups], name[self].security_groups_path, name[retrieve_all]]]]
keyword[def] identifier[list_security_groups] ( identifier[self] , identifier[retrieve_all] = keyword[True] ,** identifier[_params] ): literal[string] keyword[return] identifier[self] . identifier[list] ( literal[string] , identifier[self] . identifier[security_groups_path] , identifier[retrieve_all] ,** identifier[_params] )
def list_security_groups(self, retrieve_all=True, **_params): """Fetches a list of all security groups for a project.""" return self.list('security_groups', self.security_groups_path, retrieve_all, **_params)
def virtual_network_get(name, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 Get details about a specific virtual network. :param name: The name of the virtual network to query. :param resource_group: The resource group name assigned to the virtual network. CLI Example: .. code-block:: bash salt-call azurearm_network.virtual_network_get testnet testgroup ''' netconn = __utils__['azurearm.get_client']('network', **kwargs) try: vnet = netconn.virtual_networks.get( virtual_network_name=name, resource_group_name=resource_group ) result = vnet.as_dict() except CloudError as exc: __utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs) result = {'error': str(exc)} return result
def function[virtual_network_get, parameter[name, resource_group]]: constant[ .. versionadded:: 2019.2.0 Get details about a specific virtual network. :param name: The name of the virtual network to query. :param resource_group: The resource group name assigned to the virtual network. CLI Example: .. code-block:: bash salt-call azurearm_network.virtual_network_get testnet testgroup ] variable[netconn] assign[=] call[call[name[__utils__]][constant[azurearm.get_client]], parameter[constant[network]]] <ast.Try object at 0x7da18c4cfb20> return[name[result]]
keyword[def] identifier[virtual_network_get] ( identifier[name] , identifier[resource_group] ,** identifier[kwargs] ): literal[string] identifier[netconn] = identifier[__utils__] [ literal[string] ]( literal[string] ,** identifier[kwargs] ) keyword[try] : identifier[vnet] = identifier[netconn] . identifier[virtual_networks] . identifier[get] ( identifier[virtual_network_name] = identifier[name] , identifier[resource_group_name] = identifier[resource_group] ) identifier[result] = identifier[vnet] . identifier[as_dict] () keyword[except] identifier[CloudError] keyword[as] identifier[exc] : identifier[__utils__] [ literal[string] ]( literal[string] , identifier[str] ( identifier[exc] ),** identifier[kwargs] ) identifier[result] ={ literal[string] : identifier[str] ( identifier[exc] )} keyword[return] identifier[result]
def virtual_network_get(name, resource_group, **kwargs): """ .. versionadded:: 2019.2.0 Get details about a specific virtual network. :param name: The name of the virtual network to query. :param resource_group: The resource group name assigned to the virtual network. CLI Example: .. code-block:: bash salt-call azurearm_network.virtual_network_get testnet testgroup """ netconn = __utils__['azurearm.get_client']('network', **kwargs) try: vnet = netconn.virtual_networks.get(virtual_network_name=name, resource_group_name=resource_group) result = vnet.as_dict() # depends on [control=['try'], data=[]] except CloudError as exc: __utils__['azurearm.log_cloud_error']('network', str(exc), **kwargs) result = {'error': str(exc)} # depends on [control=['except'], data=['exc']] return result
def event_handler(self, event_type, src_path): """Re-render templates if they are modified. :param event_type: a string, representing the type of event :param src_path: the path to the file that triggered the event. """ filename = os.path.relpath(src_path, self.searchpath) if self.should_handle(event_type, src_path): print("%s %s" % (event_type, filename)) if self.site.is_static(filename): files = self.site.get_dependencies(filename) self.site.copy_static(files) else: templates = self.site.get_dependencies(filename) self.site.render_templates(templates)
def function[event_handler, parameter[self, event_type, src_path]]: constant[Re-render templates if they are modified. :param event_type: a string, representing the type of event :param src_path: the path to the file that triggered the event. ] variable[filename] assign[=] call[name[os].path.relpath, parameter[name[src_path], name[self].searchpath]] if call[name[self].should_handle, parameter[name[event_type], name[src_path]]] begin[:] call[name[print], parameter[binary_operation[constant[%s %s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b19124d0>, <ast.Name object at 0x7da1b1913370>]]]]] if call[name[self].site.is_static, parameter[name[filename]]] begin[:] variable[files] assign[=] call[name[self].site.get_dependencies, parameter[name[filename]]] call[name[self].site.copy_static, parameter[name[files]]]
keyword[def] identifier[event_handler] ( identifier[self] , identifier[event_type] , identifier[src_path] ): literal[string] identifier[filename] = identifier[os] . identifier[path] . identifier[relpath] ( identifier[src_path] , identifier[self] . identifier[searchpath] ) keyword[if] identifier[self] . identifier[should_handle] ( identifier[event_type] , identifier[src_path] ): identifier[print] ( literal[string] %( identifier[event_type] , identifier[filename] )) keyword[if] identifier[self] . identifier[site] . identifier[is_static] ( identifier[filename] ): identifier[files] = identifier[self] . identifier[site] . identifier[get_dependencies] ( identifier[filename] ) identifier[self] . identifier[site] . identifier[copy_static] ( identifier[files] ) keyword[else] : identifier[templates] = identifier[self] . identifier[site] . identifier[get_dependencies] ( identifier[filename] ) identifier[self] . identifier[site] . identifier[render_templates] ( identifier[templates] )
def event_handler(self, event_type, src_path): """Re-render templates if they are modified. :param event_type: a string, representing the type of event :param src_path: the path to the file that triggered the event. """ filename = os.path.relpath(src_path, self.searchpath) if self.should_handle(event_type, src_path): print('%s %s' % (event_type, filename)) if self.site.is_static(filename): files = self.site.get_dependencies(filename) self.site.copy_static(files) # depends on [control=['if'], data=[]] else: templates = self.site.get_dependencies(filename) self.site.render_templates(templates) # depends on [control=['if'], data=[]]
def go_to_line(self): """ Moves current **Script_Editor_tabWidget** Widget tab Model editor cursor to user defined line. :return: Method success. :rtype: bool :note: May require user interaction. """ editor = self.get_current_editor() if not editor: return False line, state = QInputDialog.getInt(self, "Goto Line Number", "Line number:", min=1) if not state: return False LOGGER.debug("> Chosen line number: '{0}'.".format(line)) return editor.go_to_line(line)
def function[go_to_line, parameter[self]]: constant[ Moves current **Script_Editor_tabWidget** Widget tab Model editor cursor to user defined line. :return: Method success. :rtype: bool :note: May require user interaction. ] variable[editor] assign[=] call[name[self].get_current_editor, parameter[]] if <ast.UnaryOp object at 0x7da18bcc9570> begin[:] return[constant[False]] <ast.Tuple object at 0x7da18bcca890> assign[=] call[name[QInputDialog].getInt, parameter[name[self], constant[Goto Line Number], constant[Line number:]]] if <ast.UnaryOp object at 0x7da18bcca4a0> begin[:] return[constant[False]] call[name[LOGGER].debug, parameter[call[constant[> Chosen line number: '{0}'.].format, parameter[name[line]]]]] return[call[name[editor].go_to_line, parameter[name[line]]]]
keyword[def] identifier[go_to_line] ( identifier[self] ): literal[string] identifier[editor] = identifier[self] . identifier[get_current_editor] () keyword[if] keyword[not] identifier[editor] : keyword[return] keyword[False] identifier[line] , identifier[state] = identifier[QInputDialog] . identifier[getInt] ( identifier[self] , literal[string] , literal[string] , identifier[min] = literal[int] ) keyword[if] keyword[not] identifier[state] : keyword[return] keyword[False] identifier[LOGGER] . identifier[debug] ( literal[string] . identifier[format] ( identifier[line] )) keyword[return] identifier[editor] . identifier[go_to_line] ( identifier[line] )
def go_to_line(self): """ Moves current **Script_Editor_tabWidget** Widget tab Model editor cursor to user defined line. :return: Method success. :rtype: bool :note: May require user interaction. """ editor = self.get_current_editor() if not editor: return False # depends on [control=['if'], data=[]] (line, state) = QInputDialog.getInt(self, 'Goto Line Number', 'Line number:', min=1) if not state: return False # depends on [control=['if'], data=[]] LOGGER.debug("> Chosen line number: '{0}'.".format(line)) return editor.go_to_line(line)
def reporter(self): """ Create a .csv file with the strain name, and the number of core genes present/the total number of core genes """ with open(os.path.join(self.reportpath, 'Escherichia_core.csv'), 'w') as report: data = 'Strain,Genes Present/Total\n' for sample in self.runmetadata.samples: # Convert the set to a list for JSON serialization sample[self.analysistype].coreset = list(sample[self.analysistype].coreset) sample[self.analysistype].coreresults = '{cs}/{cg}'.format(cs=len(sample[self.analysistype].coreset), cg=len(self.coregenomes)) # Add strain name, the number of core genes present, and the number of total core genes to the string data += '{sn},{cr}\n'.format(sn=sample.name, cr=sample[self.analysistype].coreresults) report.write(data) for sample in self.metadata: # Remove the messy blast results and set/list of core genes from the object try: delattr(sample[self.analysistype], "blastresults") except AttributeError: pass try: delattr(sample[self.analysistype], 'coreset') except AttributeError: pass
def function[reporter, parameter[self]]: constant[ Create a .csv file with the strain name, and the number of core genes present/the total number of core genes ] with call[name[open], parameter[call[name[os].path.join, parameter[name[self].reportpath, constant[Escherichia_core.csv]]], constant[w]]] begin[:] variable[data] assign[=] constant[Strain,Genes Present/Total ] for taget[name[sample]] in starred[name[self].runmetadata.samples] begin[:] call[name[sample]][name[self].analysistype].coreset assign[=] call[name[list], parameter[call[name[sample]][name[self].analysistype].coreset]] call[name[sample]][name[self].analysistype].coreresults assign[=] call[constant[{cs}/{cg}].format, parameter[]] <ast.AugAssign object at 0x7da204623010> call[name[report].write, parameter[name[data]]] for taget[name[sample]] in starred[name[self].metadata] begin[:] <ast.Try object at 0x7da2046206d0> <ast.Try object at 0x7da204621d50>
keyword[def] identifier[reporter] ( identifier[self] ): literal[string] keyword[with] identifier[open] ( identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[reportpath] , literal[string] ), literal[string] ) keyword[as] identifier[report] : identifier[data] = literal[string] keyword[for] identifier[sample] keyword[in] identifier[self] . identifier[runmetadata] . identifier[samples] : identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[coreset] = identifier[list] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[coreset] ) identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[coreresults] = literal[string] . identifier[format] ( identifier[cs] = identifier[len] ( identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[coreset] ), identifier[cg] = identifier[len] ( identifier[self] . identifier[coregenomes] )) identifier[data] += literal[string] . identifier[format] ( identifier[sn] = identifier[sample] . identifier[name] , identifier[cr] = identifier[sample] [ identifier[self] . identifier[analysistype] ]. identifier[coreresults] ) identifier[report] . identifier[write] ( identifier[data] ) keyword[for] identifier[sample] keyword[in] identifier[self] . identifier[metadata] : keyword[try] : identifier[delattr] ( identifier[sample] [ identifier[self] . identifier[analysistype] ], literal[string] ) keyword[except] identifier[AttributeError] : keyword[pass] keyword[try] : identifier[delattr] ( identifier[sample] [ identifier[self] . identifier[analysistype] ], literal[string] ) keyword[except] identifier[AttributeError] : keyword[pass]
def reporter(self): """ Create a .csv file with the strain name, and the number of core genes present/the total number of core genes """ with open(os.path.join(self.reportpath, 'Escherichia_core.csv'), 'w') as report: data = 'Strain,Genes Present/Total\n' for sample in self.runmetadata.samples: # Convert the set to a list for JSON serialization sample[self.analysistype].coreset = list(sample[self.analysistype].coreset) sample[self.analysistype].coreresults = '{cs}/{cg}'.format(cs=len(sample[self.analysistype].coreset), cg=len(self.coregenomes)) # Add strain name, the number of core genes present, and the number of total core genes to the string data += '{sn},{cr}\n'.format(sn=sample.name, cr=sample[self.analysistype].coreresults) # depends on [control=['for'], data=['sample']] report.write(data) # depends on [control=['with'], data=['report']] for sample in self.metadata: # Remove the messy blast results and set/list of core genes from the object try: delattr(sample[self.analysistype], 'blastresults') # depends on [control=['try'], data=[]] except AttributeError: pass # depends on [control=['except'], data=[]] try: delattr(sample[self.analysistype], 'coreset') # depends on [control=['try'], data=[]] except AttributeError: pass # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['sample']]
def find_direct_metabolites(model, reaction, tolerance=1E-06): """ Return list of possible direct biomass precursor metabolites. The term direct metabolites describes metabolites that are involved only in either transport and/or boundary reactions, AND the biomass reaction(s), but not in any purely metabolic reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. reaction : cobra.Reaction The biomass reaction of the model under investigation. tolerance : float, optional Tolerance below which values will be regarded as zero. Returns ------- list Metabolites that qualify as direct metabolites i.e. biomass precursors that are taken up to be consumed by the biomass reaction only. """ biomass_rxns = set(helpers.find_biomass_reaction(model)) tra_bou_bio_rxns = helpers.find_interchange_biomass_reactions( model, biomass_rxns) try: precursors = find_biomass_precursors(model, reaction) main_comp = helpers.find_compartment_id_in_model(model, 'c') ext_space = helpers.find_compartment_id_in_model(model, 'e') except KeyError: LOGGER.error("Failed to properly identify cytosolic and extracellular " "compartments.") raise_with_traceback(KeyError("The cytosolic and/or extracellular " "compartments could not be identified.")) except RuntimeError: LOGGER.error("Failed to properly identify cytosolic and extracellular " "compartments.") raise_with_traceback(RuntimeError("The cytosolic and/or extracellular " "compartments could not be " "identified.")) else: tra_bou_bio_mets = [met for met in precursors if met.reactions.issubset(tra_bou_bio_rxns)] rxns_of_interest = set([rxn for met in tra_bou_bio_mets for rxn in met.reactions if rxn not in biomass_rxns]) solution = model.optimize(raise_error=True) if np.isclose(solution.objective_value, 0, atol=tolerance): LOGGER.error("Failed to generate a non-zero objective value with " "flux balance analysis.") raise OptimizationError( "The flux balance analysis on this model returned an " "objective value of zero. Make sure the model can " "grow! Check if the constraints are not too strict!") tra_bou_bio_fluxes = {r: solution[r.id] for r in rxns_of_interest} met_flux_sum = {m: 0 for m in tra_bou_bio_mets} return detect_false_positive_direct_metabolites( tra_bou_bio_mets, biomass_rxns, main_comp, ext_space, tra_bou_bio_fluxes, met_flux_sum)
def function[find_direct_metabolites, parameter[model, reaction, tolerance]]: constant[ Return list of possible direct biomass precursor metabolites. The term direct metabolites describes metabolites that are involved only in either transport and/or boundary reactions, AND the biomass reaction(s), but not in any purely metabolic reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. reaction : cobra.Reaction The biomass reaction of the model under investigation. tolerance : float, optional Tolerance below which values will be regarded as zero. Returns ------- list Metabolites that qualify as direct metabolites i.e. biomass precursors that are taken up to be consumed by the biomass reaction only. ] variable[biomass_rxns] assign[=] call[name[set], parameter[call[name[helpers].find_biomass_reaction, parameter[name[model]]]]] variable[tra_bou_bio_rxns] assign[=] call[name[helpers].find_interchange_biomass_reactions, parameter[name[model], name[biomass_rxns]]] <ast.Try object at 0x7da207f03e20> variable[solution] assign[=] call[name[model].optimize, parameter[]] if call[name[np].isclose, parameter[name[solution].objective_value, constant[0]]] begin[:] call[name[LOGGER].error, parameter[constant[Failed to generate a non-zero objective value with flux balance analysis.]]] <ast.Raise object at 0x7da207f00490> variable[tra_bou_bio_fluxes] assign[=] <ast.DictComp object at 0x7da207f026e0> variable[met_flux_sum] assign[=] <ast.DictComp object at 0x7da207f03310> return[call[name[detect_false_positive_direct_metabolites], parameter[name[tra_bou_bio_mets], name[biomass_rxns], name[main_comp], name[ext_space], name[tra_bou_bio_fluxes], name[met_flux_sum]]]]
keyword[def] identifier[find_direct_metabolites] ( identifier[model] , identifier[reaction] , identifier[tolerance] = literal[int] ): literal[string] identifier[biomass_rxns] = identifier[set] ( identifier[helpers] . identifier[find_biomass_reaction] ( identifier[model] )) identifier[tra_bou_bio_rxns] = identifier[helpers] . identifier[find_interchange_biomass_reactions] ( identifier[model] , identifier[biomass_rxns] ) keyword[try] : identifier[precursors] = identifier[find_biomass_precursors] ( identifier[model] , identifier[reaction] ) identifier[main_comp] = identifier[helpers] . identifier[find_compartment_id_in_model] ( identifier[model] , literal[string] ) identifier[ext_space] = identifier[helpers] . identifier[find_compartment_id_in_model] ( identifier[model] , literal[string] ) keyword[except] identifier[KeyError] : identifier[LOGGER] . identifier[error] ( literal[string] literal[string] ) identifier[raise_with_traceback] ( identifier[KeyError] ( literal[string] literal[string] )) keyword[except] identifier[RuntimeError] : identifier[LOGGER] . identifier[error] ( literal[string] literal[string] ) identifier[raise_with_traceback] ( identifier[RuntimeError] ( literal[string] literal[string] literal[string] )) keyword[else] : identifier[tra_bou_bio_mets] =[ identifier[met] keyword[for] identifier[met] keyword[in] identifier[precursors] keyword[if] identifier[met] . identifier[reactions] . identifier[issubset] ( identifier[tra_bou_bio_rxns] )] identifier[rxns_of_interest] = identifier[set] ([ identifier[rxn] keyword[for] identifier[met] keyword[in] identifier[tra_bou_bio_mets] keyword[for] identifier[rxn] keyword[in] identifier[met] . identifier[reactions] keyword[if] identifier[rxn] keyword[not] keyword[in] identifier[biomass_rxns] ]) identifier[solution] = identifier[model] . identifier[optimize] ( identifier[raise_error] = keyword[True] ) keyword[if] identifier[np] . identifier[isclose] ( identifier[solution] . identifier[objective_value] , literal[int] , identifier[atol] = identifier[tolerance] ): identifier[LOGGER] . identifier[error] ( literal[string] literal[string] ) keyword[raise] identifier[OptimizationError] ( literal[string] literal[string] literal[string] ) identifier[tra_bou_bio_fluxes] ={ identifier[r] : identifier[solution] [ identifier[r] . identifier[id] ] keyword[for] identifier[r] keyword[in] identifier[rxns_of_interest] } identifier[met_flux_sum] ={ identifier[m] : literal[int] keyword[for] identifier[m] keyword[in] identifier[tra_bou_bio_mets] } keyword[return] identifier[detect_false_positive_direct_metabolites] ( identifier[tra_bou_bio_mets] , identifier[biomass_rxns] , identifier[main_comp] , identifier[ext_space] , identifier[tra_bou_bio_fluxes] , identifier[met_flux_sum] )
def find_direct_metabolites(model, reaction, tolerance=1e-06): """ Return list of possible direct biomass precursor metabolites. The term direct metabolites describes metabolites that are involved only in either transport and/or boundary reactions, AND the biomass reaction(s), but not in any purely metabolic reactions. Parameters ---------- model : cobra.Model The metabolic model under investigation. reaction : cobra.Reaction The biomass reaction of the model under investigation. tolerance : float, optional Tolerance below which values will be regarded as zero. Returns ------- list Metabolites that qualify as direct metabolites i.e. biomass precursors that are taken up to be consumed by the biomass reaction only. """ biomass_rxns = set(helpers.find_biomass_reaction(model)) tra_bou_bio_rxns = helpers.find_interchange_biomass_reactions(model, biomass_rxns) try: precursors = find_biomass_precursors(model, reaction) main_comp = helpers.find_compartment_id_in_model(model, 'c') ext_space = helpers.find_compartment_id_in_model(model, 'e') # depends on [control=['try'], data=[]] except KeyError: LOGGER.error('Failed to properly identify cytosolic and extracellular compartments.') raise_with_traceback(KeyError('The cytosolic and/or extracellular compartments could not be identified.')) # depends on [control=['except'], data=[]] except RuntimeError: LOGGER.error('Failed to properly identify cytosolic and extracellular compartments.') raise_with_traceback(RuntimeError('The cytosolic and/or extracellular compartments could not be identified.')) # depends on [control=['except'], data=[]] else: tra_bou_bio_mets = [met for met in precursors if met.reactions.issubset(tra_bou_bio_rxns)] rxns_of_interest = set([rxn for met in tra_bou_bio_mets for rxn in met.reactions if rxn not in biomass_rxns]) solution = model.optimize(raise_error=True) if np.isclose(solution.objective_value, 0, atol=tolerance): LOGGER.error('Failed to generate a non-zero objective value with flux balance analysis.') raise OptimizationError('The flux balance analysis on this model returned an objective value of zero. Make sure the model can grow! Check if the constraints are not too strict!') # depends on [control=['if'], data=[]] tra_bou_bio_fluxes = {r: solution[r.id] for r in rxns_of_interest} met_flux_sum = {m: 0 for m in tra_bou_bio_mets} return detect_false_positive_direct_metabolites(tra_bou_bio_mets, biomass_rxns, main_comp, ext_space, tra_bou_bio_fluxes, met_flux_sum)
def node_received_infos(node_id): """Get all the infos a node has been sent and has received. You must specify the node id in the url. You can also pass the info type. """ exp = Experiment(session) # get the parameters info_type = request_parameter( parameter="info_type", parameter_type="known_class", default=models.Info ) if type(info_type) == Response: return info_type # check the node exists node = models.Node.query.get(node_id) if node is None: return error_response( error_type="/node/infos, node {} does not exist".format(node_id) ) # execute the request: infos = node.received_infos(type=info_type) try: # ping the experiment exp.info_get_request(node=node, infos=infos) session.commit() except Exception: return error_response( error_type="info_get_request error", status=403, participant=node.participant, ) return success_response(infos=[i.__json__() for i in infos])
def function[node_received_infos, parameter[node_id]]: constant[Get all the infos a node has been sent and has received. You must specify the node id in the url. You can also pass the info type. ] variable[exp] assign[=] call[name[Experiment], parameter[name[session]]] variable[info_type] assign[=] call[name[request_parameter], parameter[]] if compare[call[name[type], parameter[name[info_type]]] equal[==] name[Response]] begin[:] return[name[info_type]] variable[node] assign[=] call[name[models].Node.query.get, parameter[name[node_id]]] if compare[name[node] is constant[None]] begin[:] return[call[name[error_response], parameter[]]] variable[infos] assign[=] call[name[node].received_infos, parameter[]] <ast.Try object at 0x7da1b032e2c0> return[call[name[success_response], parameter[]]]
keyword[def] identifier[node_received_infos] ( identifier[node_id] ): literal[string] identifier[exp] = identifier[Experiment] ( identifier[session] ) identifier[info_type] = identifier[request_parameter] ( identifier[parameter] = literal[string] , identifier[parameter_type] = literal[string] , identifier[default] = identifier[models] . identifier[Info] ) keyword[if] identifier[type] ( identifier[info_type] )== identifier[Response] : keyword[return] identifier[info_type] identifier[node] = identifier[models] . identifier[Node] . identifier[query] . identifier[get] ( identifier[node_id] ) keyword[if] identifier[node] keyword[is] keyword[None] : keyword[return] identifier[error_response] ( identifier[error_type] = literal[string] . identifier[format] ( identifier[node_id] ) ) identifier[infos] = identifier[node] . identifier[received_infos] ( identifier[type] = identifier[info_type] ) keyword[try] : identifier[exp] . identifier[info_get_request] ( identifier[node] = identifier[node] , identifier[infos] = identifier[infos] ) identifier[session] . identifier[commit] () keyword[except] identifier[Exception] : keyword[return] identifier[error_response] ( identifier[error_type] = literal[string] , identifier[status] = literal[int] , identifier[participant] = identifier[node] . identifier[participant] , ) keyword[return] identifier[success_response] ( identifier[infos] =[ identifier[i] . identifier[__json__] () keyword[for] identifier[i] keyword[in] identifier[infos] ])
def node_received_infos(node_id): """Get all the infos a node has been sent and has received. You must specify the node id in the url. You can also pass the info type. """ exp = Experiment(session) # get the parameters info_type = request_parameter(parameter='info_type', parameter_type='known_class', default=models.Info) if type(info_type) == Response: return info_type # depends on [control=['if'], data=[]] # check the node exists node = models.Node.query.get(node_id) if node is None: return error_response(error_type='/node/infos, node {} does not exist'.format(node_id)) # depends on [control=['if'], data=[]] # execute the request: infos = node.received_infos(type=info_type) try: # ping the experiment exp.info_get_request(node=node, infos=infos) session.commit() # depends on [control=['try'], data=[]] except Exception: return error_response(error_type='info_get_request error', status=403, participant=node.participant) # depends on [control=['except'], data=[]] return success_response(infos=[i.__json__() for i in infos])
def get_backend_url(config, hub, group, project): """ Util method to get backend url """ if ((config is not None) and ('hub' in config) and (hub is None)): hub = config["hub"] if ((config is not None) and ('group' in config) and (group is None)): group = config["group"] if ((config is not None) and ('project' in config) and (project is None)): project = config["project"] if ((hub is not None) and (group is not None) and (project is not None)): return '/Network/{}/Groups/{}/Projects/{}/devices'.format(hub, group, project) return '/Backends'
def function[get_backend_url, parameter[config, hub, group, project]]: constant[ Util method to get backend url ] if <ast.BoolOp object at 0x7da237eee740> begin[:] variable[hub] assign[=] call[name[config]][constant[hub]] if <ast.BoolOp object at 0x7da20c6e4e50> begin[:] variable[group] assign[=] call[name[config]][constant[group]] if <ast.BoolOp object at 0x7da20c6e7dc0> begin[:] variable[project] assign[=] call[name[config]][constant[project]] if <ast.BoolOp object at 0x7da20c6e6710> begin[:] return[call[constant[/Network/{}/Groups/{}/Projects/{}/devices].format, parameter[name[hub], name[group], name[project]]]] return[constant[/Backends]]
keyword[def] identifier[get_backend_url] ( identifier[config] , identifier[hub] , identifier[group] , identifier[project] ): literal[string] keyword[if] (( identifier[config] keyword[is] keyword[not] keyword[None] ) keyword[and] ( literal[string] keyword[in] identifier[config] ) keyword[and] ( identifier[hub] keyword[is] keyword[None] )): identifier[hub] = identifier[config] [ literal[string] ] keyword[if] (( identifier[config] keyword[is] keyword[not] keyword[None] ) keyword[and] ( literal[string] keyword[in] identifier[config] ) keyword[and] ( identifier[group] keyword[is] keyword[None] )): identifier[group] = identifier[config] [ literal[string] ] keyword[if] (( identifier[config] keyword[is] keyword[not] keyword[None] ) keyword[and] ( literal[string] keyword[in] identifier[config] ) keyword[and] ( identifier[project] keyword[is] keyword[None] )): identifier[project] = identifier[config] [ literal[string] ] keyword[if] (( identifier[hub] keyword[is] keyword[not] keyword[None] ) keyword[and] ( identifier[group] keyword[is] keyword[not] keyword[None] ) keyword[and] ( identifier[project] keyword[is] keyword[not] keyword[None] )): keyword[return] literal[string] . identifier[format] ( identifier[hub] , identifier[group] , identifier[project] ) keyword[return] literal[string]
def get_backend_url(config, hub, group, project): """ Util method to get backend url """ if config is not None and 'hub' in config and (hub is None): hub = config['hub'] # depends on [control=['if'], data=[]] if config is not None and 'group' in config and (group is None): group = config['group'] # depends on [control=['if'], data=[]] if config is not None and 'project' in config and (project is None): project = config['project'] # depends on [control=['if'], data=[]] if hub is not None and group is not None and (project is not None): return '/Network/{}/Groups/{}/Projects/{}/devices'.format(hub, group, project) # depends on [control=['if'], data=[]] return '/Backends'
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool = False, include_categories: bool = False, **criteria: Dict[str, bool]) -> List[bool]: """ Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`. """ return [ drug_name_matches_criteria( dn, name_is_generic=names_are_generic, include_categories=include_categories, **criteria) for dn in drug_names ]
def function[drug_names_match_criteria, parameter[drug_names, names_are_generic, include_categories]]: constant[ Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`. ] return[<ast.ListComp object at 0x7da1b184b310>]
keyword[def] identifier[drug_names_match_criteria] ( identifier[drug_names] : identifier[List] [ identifier[str] ], identifier[names_are_generic] : identifier[bool] = keyword[False] , identifier[include_categories] : identifier[bool] = keyword[False] , ** identifier[criteria] : identifier[Dict] [ identifier[str] , identifier[bool] ])-> identifier[List] [ identifier[bool] ]: literal[string] keyword[return] [ identifier[drug_name_matches_criteria] ( identifier[dn] , identifier[name_is_generic] = identifier[names_are_generic] , identifier[include_categories] = identifier[include_categories] , ** identifier[criteria] ) keyword[for] identifier[dn] keyword[in] identifier[drug_names] ]
def drug_names_match_criteria(drug_names: List[str], names_are_generic: bool=False, include_categories: bool=False, **criteria: Dict[str, bool]) -> List[bool]: """ Establish whether multiple drugs, passed as a list of drug names, each matches the specified criteria. See :func:`drug_matches_criteria`. """ return [drug_name_matches_criteria(dn, name_is_generic=names_are_generic, include_categories=include_categories, **criteria) for dn in drug_names]
def read_int(self, signed=True): """Reads an integer (4 bytes) value.""" return int.from_bytes(self.read(4), byteorder='little', signed=signed)
def function[read_int, parameter[self, signed]]: constant[Reads an integer (4 bytes) value.] return[call[name[int].from_bytes, parameter[call[name[self].read, parameter[constant[4]]]]]]
keyword[def] identifier[read_int] ( identifier[self] , identifier[signed] = keyword[True] ): literal[string] keyword[return] identifier[int] . identifier[from_bytes] ( identifier[self] . identifier[read] ( literal[int] ), identifier[byteorder] = literal[string] , identifier[signed] = identifier[signed] )
def read_int(self, signed=True): """Reads an integer (4 bytes) value.""" return int.from_bytes(self.read(4), byteorder='little', signed=signed)
def _apply_amplification_factor(self, mean, vs30): """ Apply amplification factor to scale PGV value from 600 to 400 m/s vs30 and convert mean from base 10 to base e. The scaling factor from 600 m/s to 400 m/s was defined by NIED. The scaling factor from 600 m/s to 800m/s is valid just for the elastic case as no adjustment for kappa was considered. """ assert np.all(vs30 == vs30[0]) if abs(vs30[0]-600.) < 1e-10: return mean * np.log(10) elif abs(vs30[0]-400.) < 1e-10: return mean * np.log(10) + np.log(self.AMP_F) elif abs(vs30[0]-800.) < 1e-10: return mean * np.log(10) - np.log(1.25) else: raise ValueError('Si and Midorikawa 1999 do not support this Vs30 value')
def function[_apply_amplification_factor, parameter[self, mean, vs30]]: constant[ Apply amplification factor to scale PGV value from 600 to 400 m/s vs30 and convert mean from base 10 to base e. The scaling factor from 600 m/s to 400 m/s was defined by NIED. The scaling factor from 600 m/s to 800m/s is valid just for the elastic case as no adjustment for kappa was considered. ] assert[call[name[np].all, parameter[compare[name[vs30] equal[==] call[name[vs30]][constant[0]]]]]] if compare[call[name[abs], parameter[binary_operation[call[name[vs30]][constant[0]] - constant[600.0]]]] less[<] constant[1e-10]] begin[:] return[binary_operation[name[mean] * call[name[np].log, parameter[constant[10]]]]]
keyword[def] identifier[_apply_amplification_factor] ( identifier[self] , identifier[mean] , identifier[vs30] ): literal[string] keyword[assert] identifier[np] . identifier[all] ( identifier[vs30] == identifier[vs30] [ literal[int] ]) keyword[if] identifier[abs] ( identifier[vs30] [ literal[int] ]- literal[int] )< literal[int] : keyword[return] identifier[mean] * identifier[np] . identifier[log] ( literal[int] ) keyword[elif] identifier[abs] ( identifier[vs30] [ literal[int] ]- literal[int] )< literal[int] : keyword[return] identifier[mean] * identifier[np] . identifier[log] ( literal[int] )+ identifier[np] . identifier[log] ( identifier[self] . identifier[AMP_F] ) keyword[elif] identifier[abs] ( identifier[vs30] [ literal[int] ]- literal[int] )< literal[int] : keyword[return] identifier[mean] * identifier[np] . identifier[log] ( literal[int] )- identifier[np] . identifier[log] ( literal[int] ) keyword[else] : keyword[raise] identifier[ValueError] ( literal[string] )
def _apply_amplification_factor(self, mean, vs30): """ Apply amplification factor to scale PGV value from 600 to 400 m/s vs30 and convert mean from base 10 to base e. The scaling factor from 600 m/s to 400 m/s was defined by NIED. The scaling factor from 600 m/s to 800m/s is valid just for the elastic case as no adjustment for kappa was considered. """ assert np.all(vs30 == vs30[0]) if abs(vs30[0] - 600.0) < 1e-10: return mean * np.log(10) # depends on [control=['if'], data=[]] elif abs(vs30[0] - 400.0) < 1e-10: return mean * np.log(10) + np.log(self.AMP_F) # depends on [control=['if'], data=[]] elif abs(vs30[0] - 800.0) < 1e-10: return mean * np.log(10) - np.log(1.25) # depends on [control=['if'], data=[]] else: raise ValueError('Si and Midorikawa 1999 do not support this Vs30 value')
def disable(self): """ Disable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send` """ yield from self._check_for_feature() iq = aioxmpp.IQ( type_=aioxmpp.IQType.SET, payload=carbons_xso.Disable() ) yield from self.client.send(iq)
def function[disable, parameter[self]]: constant[ Disable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send` ] <ast.YieldFrom object at 0x7da18f58da20> variable[iq] assign[=] call[name[aioxmpp].IQ, parameter[]] <ast.YieldFrom object at 0x7da20e9b2b60>
keyword[def] identifier[disable] ( identifier[self] ): literal[string] keyword[yield] keyword[from] identifier[self] . identifier[_check_for_feature] () identifier[iq] = identifier[aioxmpp] . identifier[IQ] ( identifier[type_] = identifier[aioxmpp] . identifier[IQType] . identifier[SET] , identifier[payload] = identifier[carbons_xso] . identifier[Disable] () ) keyword[yield] keyword[from] identifier[self] . identifier[client] . identifier[send] ( identifier[iq] )
def disable(self): """ Disable message carbons. :raises RuntimeError: if the server does not support message carbons. :raises aioxmpp.XMPPError: if the server responded with an error to the request. :raises: as specified in :meth:`aioxmpp.Client.send` """ yield from self._check_for_feature() iq = aioxmpp.IQ(type_=aioxmpp.IQType.SET, payload=carbons_xso.Disable()) yield from self.client.send(iq)
def _delegate_or(smethname, func): """ Produce a method that calls either the existing method of the wrapped object with the same name or a special invocation if it's missing (see SPECIAL_METHODS in special_methods.py). Usage: OnAccessMutant(initial_object, callable_mutator) where: callable_mutator(wrapped_object) -> new_wrapped_object """ def delegated(self, *a, **kwa): # Mutate the object before access wrapped = object.__getattribute__(self, '__wrapped_object__') mutator = object.__getattribute__(self, '__wrapped_mutator__') wrapped = mutator(wrapped) object.__setattr__(self, '__wrapped_object__', wrapped) # Proxy access or use a fallback function try: meth = getattr(wrapped, smethname) except AttributeError: return func(wrapped, *a, **kwa) if not isinstance(wrapped, type): return meth(*a, **kwa) else: meth = getattr(type(wrapped), smethname) return meth(wrapped, *a, **kwa) return delegated
def function[_delegate_or, parameter[smethname, func]]: constant[ Produce a method that calls either the existing method of the wrapped object with the same name or a special invocation if it's missing (see SPECIAL_METHODS in special_methods.py). Usage: OnAccessMutant(initial_object, callable_mutator) where: callable_mutator(wrapped_object) -> new_wrapped_object ] def function[delegated, parameter[self]]: variable[wrapped] assign[=] call[name[object].__getattribute__, parameter[name[self], constant[__wrapped_object__]]] variable[mutator] assign[=] call[name[object].__getattribute__, parameter[name[self], constant[__wrapped_mutator__]]] variable[wrapped] assign[=] call[name[mutator], parameter[name[wrapped]]] call[name[object].__setattr__, parameter[name[self], constant[__wrapped_object__], name[wrapped]]] <ast.Try object at 0x7da204565a80> if <ast.UnaryOp object at 0x7da204565f90> begin[:] return[call[name[meth], parameter[<ast.Starred object at 0x7da204566dd0>]]] return[name[delegated]]
keyword[def] identifier[_delegate_or] ( identifier[smethname] , identifier[func] ): literal[string] keyword[def] identifier[delegated] ( identifier[self] ,* identifier[a] ,** identifier[kwa] ): identifier[wrapped] = identifier[object] . identifier[__getattribute__] ( identifier[self] , literal[string] ) identifier[mutator] = identifier[object] . identifier[__getattribute__] ( identifier[self] , literal[string] ) identifier[wrapped] = identifier[mutator] ( identifier[wrapped] ) identifier[object] . identifier[__setattr__] ( identifier[self] , literal[string] , identifier[wrapped] ) keyword[try] : identifier[meth] = identifier[getattr] ( identifier[wrapped] , identifier[smethname] ) keyword[except] identifier[AttributeError] : keyword[return] identifier[func] ( identifier[wrapped] ,* identifier[a] ,** identifier[kwa] ) keyword[if] keyword[not] identifier[isinstance] ( identifier[wrapped] , identifier[type] ): keyword[return] identifier[meth] (* identifier[a] ,** identifier[kwa] ) keyword[else] : identifier[meth] = identifier[getattr] ( identifier[type] ( identifier[wrapped] ), identifier[smethname] ) keyword[return] identifier[meth] ( identifier[wrapped] ,* identifier[a] ,** identifier[kwa] ) keyword[return] identifier[delegated]
def _delegate_or(smethname, func): """ Produce a method that calls either the existing method of the wrapped object with the same name or a special invocation if it's missing (see SPECIAL_METHODS in special_methods.py). Usage: OnAccessMutant(initial_object, callable_mutator) where: callable_mutator(wrapped_object) -> new_wrapped_object """ def delegated(self, *a, **kwa): # Mutate the object before access wrapped = object.__getattribute__(self, '__wrapped_object__') mutator = object.__getattribute__(self, '__wrapped_mutator__') wrapped = mutator(wrapped) object.__setattr__(self, '__wrapped_object__', wrapped) # Proxy access or use a fallback function try: meth = getattr(wrapped, smethname) # depends on [control=['try'], data=[]] except AttributeError: return func(wrapped, *a, **kwa) # depends on [control=['except'], data=[]] if not isinstance(wrapped, type): return meth(*a, **kwa) # depends on [control=['if'], data=[]] else: meth = getattr(type(wrapped), smethname) return meth(wrapped, *a, **kwa) return delegated
def mapCellsToColumns(self, cells): """ Maps cells to the columns they belong to. :param cells: (set) Cells :returns: (dict) Mapping from columns to their cells in `cells` """ cellsForColumns = defaultdict(set) for cell in cells: column = self.columnForCell(cell) cellsForColumns[column].add(cell) return cellsForColumns
def function[mapCellsToColumns, parameter[self, cells]]: constant[ Maps cells to the columns they belong to. :param cells: (set) Cells :returns: (dict) Mapping from columns to their cells in `cells` ] variable[cellsForColumns] assign[=] call[name[defaultdict], parameter[name[set]]] for taget[name[cell]] in starred[name[cells]] begin[:] variable[column] assign[=] call[name[self].columnForCell, parameter[name[cell]]] call[call[name[cellsForColumns]][name[column]].add, parameter[name[cell]]] return[name[cellsForColumns]]
keyword[def] identifier[mapCellsToColumns] ( identifier[self] , identifier[cells] ): literal[string] identifier[cellsForColumns] = identifier[defaultdict] ( identifier[set] ) keyword[for] identifier[cell] keyword[in] identifier[cells] : identifier[column] = identifier[self] . identifier[columnForCell] ( identifier[cell] ) identifier[cellsForColumns] [ identifier[column] ]. identifier[add] ( identifier[cell] ) keyword[return] identifier[cellsForColumns]
def mapCellsToColumns(self, cells): """ Maps cells to the columns they belong to. :param cells: (set) Cells :returns: (dict) Mapping from columns to their cells in `cells` """ cellsForColumns = defaultdict(set) for cell in cells: column = self.columnForCell(cell) cellsForColumns[column].add(cell) # depends on [control=['for'], data=['cell']] return cellsForColumns
def init_scheduler(db_uri): """Initialise and configure the scheduler.""" global scheduler scheduler = apscheduler.Scheduler() scheduler.misfire_grace_time = 3600 scheduler.add_jobstore( sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), 'default') scheduler.add_listener( job_listener, events.EVENT_JOB_EXECUTED | events.EVENT_JOB_MISSED | events.EVENT_JOB_ERROR) return scheduler
def function[init_scheduler, parameter[db_uri]]: constant[Initialise and configure the scheduler.] <ast.Global object at 0x7da20e9b2ce0> variable[scheduler] assign[=] call[name[apscheduler].Scheduler, parameter[]] name[scheduler].misfire_grace_time assign[=] constant[3600] call[name[scheduler].add_jobstore, parameter[call[name[sqlalchemy_store].SQLAlchemyJobStore, parameter[]], constant[default]]] call[name[scheduler].add_listener, parameter[name[job_listener], binary_operation[binary_operation[name[events].EVENT_JOB_EXECUTED <ast.BitOr object at 0x7da2590d6aa0> name[events].EVENT_JOB_MISSED] <ast.BitOr object at 0x7da2590d6aa0> name[events].EVENT_JOB_ERROR]]] return[name[scheduler]]
keyword[def] identifier[init_scheduler] ( identifier[db_uri] ): literal[string] keyword[global] identifier[scheduler] identifier[scheduler] = identifier[apscheduler] . identifier[Scheduler] () identifier[scheduler] . identifier[misfire_grace_time] = literal[int] identifier[scheduler] . identifier[add_jobstore] ( identifier[sqlalchemy_store] . identifier[SQLAlchemyJobStore] ( identifier[url] = identifier[db_uri] ), literal[string] ) identifier[scheduler] . identifier[add_listener] ( identifier[job_listener] , identifier[events] . identifier[EVENT_JOB_EXECUTED] | identifier[events] . identifier[EVENT_JOB_MISSED] | identifier[events] . identifier[EVENT_JOB_ERROR] ) keyword[return] identifier[scheduler]
def init_scheduler(db_uri): """Initialise and configure the scheduler.""" global scheduler scheduler = apscheduler.Scheduler() scheduler.misfire_grace_time = 3600 scheduler.add_jobstore(sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), 'default') scheduler.add_listener(job_listener, events.EVENT_JOB_EXECUTED | events.EVENT_JOB_MISSED | events.EVENT_JOB_ERROR) return scheduler
def set_membership(self, room_id, user_id, membership, reason="", profile=None, timestamp=None): """Perform PUT /rooms/$room_id/state/m.room.member/$user_id Args: room_id (str): The room ID user_id (str): The user ID membership (str): New membership value reason (str): The reason timestamp (int): Set origin_server_ts (For application services only) """ if profile is None: profile = {} body = { "membership": membership, "reason": reason } if 'displayname' in profile: body["displayname"] = profile["displayname"] if 'avatar_url' in profile: body["avatar_url"] = profile["avatar_url"] return self.send_state_event(room_id, "m.room.member", body, state_key=user_id, timestamp=timestamp)
def function[set_membership, parameter[self, room_id, user_id, membership, reason, profile, timestamp]]: constant[Perform PUT /rooms/$room_id/state/m.room.member/$user_id Args: room_id (str): The room ID user_id (str): The user ID membership (str): New membership value reason (str): The reason timestamp (int): Set origin_server_ts (For application services only) ] if compare[name[profile] is constant[None]] begin[:] variable[profile] assign[=] dictionary[[], []] variable[body] assign[=] dictionary[[<ast.Constant object at 0x7da1b16c1450>, <ast.Constant object at 0x7da1b16c1f90>], [<ast.Name object at 0x7da1b16c3a90>, <ast.Name object at 0x7da1b16c23b0>]] if compare[constant[displayname] in name[profile]] begin[:] call[name[body]][constant[displayname]] assign[=] call[name[profile]][constant[displayname]] if compare[constant[avatar_url] in name[profile]] begin[:] call[name[body]][constant[avatar_url]] assign[=] call[name[profile]][constant[avatar_url]] return[call[name[self].send_state_event, parameter[name[room_id], constant[m.room.member], name[body]]]]
keyword[def] identifier[set_membership] ( identifier[self] , identifier[room_id] , identifier[user_id] , identifier[membership] , identifier[reason] = literal[string] , identifier[profile] = keyword[None] , identifier[timestamp] = keyword[None] ): literal[string] keyword[if] identifier[profile] keyword[is] keyword[None] : identifier[profile] ={} identifier[body] ={ literal[string] : identifier[membership] , literal[string] : identifier[reason] } keyword[if] literal[string] keyword[in] identifier[profile] : identifier[body] [ literal[string] ]= identifier[profile] [ literal[string] ] keyword[if] literal[string] keyword[in] identifier[profile] : identifier[body] [ literal[string] ]= identifier[profile] [ literal[string] ] keyword[return] identifier[self] . identifier[send_state_event] ( identifier[room_id] , literal[string] , identifier[body] , identifier[state_key] = identifier[user_id] , identifier[timestamp] = identifier[timestamp] )
def set_membership(self, room_id, user_id, membership, reason='', profile=None, timestamp=None): """Perform PUT /rooms/$room_id/state/m.room.member/$user_id Args: room_id (str): The room ID user_id (str): The user ID membership (str): New membership value reason (str): The reason timestamp (int): Set origin_server_ts (For application services only) """ if profile is None: profile = {} # depends on [control=['if'], data=['profile']] body = {'membership': membership, 'reason': reason} if 'displayname' in profile: body['displayname'] = profile['displayname'] # depends on [control=['if'], data=['profile']] if 'avatar_url' in profile: body['avatar_url'] = profile['avatar_url'] # depends on [control=['if'], data=['profile']] return self.send_state_event(room_id, 'm.room.member', body, state_key=user_id, timestamp=timestamp)
def comments(self, case_id=None, variant_id=None, username=None): """Return comments for a case or variant. Args: case_id (str): id for a related case variant_id (Optional[str]): id for a related variant """ logger.debug("Looking for comments") comment_objs = self.query(Comment) if case_id: comment_objs = comment_objs.filter_by(case_id=case_id) if variant_id: comment_objs = comment_objs.filter_by(variant_id=variant_id) elif case_id: comment_objs = comment_objs.filter_by(variant_id=None) return comment_objs
def function[comments, parameter[self, case_id, variant_id, username]]: constant[Return comments for a case or variant. Args: case_id (str): id for a related case variant_id (Optional[str]): id for a related variant ] call[name[logger].debug, parameter[constant[Looking for comments]]] variable[comment_objs] assign[=] call[name[self].query, parameter[name[Comment]]] if name[case_id] begin[:] variable[comment_objs] assign[=] call[name[comment_objs].filter_by, parameter[]] if name[variant_id] begin[:] variable[comment_objs] assign[=] call[name[comment_objs].filter_by, parameter[]] return[name[comment_objs]]
keyword[def] identifier[comments] ( identifier[self] , identifier[case_id] = keyword[None] , identifier[variant_id] = keyword[None] , identifier[username] = keyword[None] ): literal[string] identifier[logger] . identifier[debug] ( literal[string] ) identifier[comment_objs] = identifier[self] . identifier[query] ( identifier[Comment] ) keyword[if] identifier[case_id] : identifier[comment_objs] = identifier[comment_objs] . identifier[filter_by] ( identifier[case_id] = identifier[case_id] ) keyword[if] identifier[variant_id] : identifier[comment_objs] = identifier[comment_objs] . identifier[filter_by] ( identifier[variant_id] = identifier[variant_id] ) keyword[elif] identifier[case_id] : identifier[comment_objs] = identifier[comment_objs] . identifier[filter_by] ( identifier[variant_id] = keyword[None] ) keyword[return] identifier[comment_objs]
def comments(self, case_id=None, variant_id=None, username=None): """Return comments for a case or variant. Args: case_id (str): id for a related case variant_id (Optional[str]): id for a related variant """ logger.debug('Looking for comments') comment_objs = self.query(Comment) if case_id: comment_objs = comment_objs.filter_by(case_id=case_id) # depends on [control=['if'], data=[]] if variant_id: comment_objs = comment_objs.filter_by(variant_id=variant_id) # depends on [control=['if'], data=[]] elif case_id: comment_objs = comment_objs.filter_by(variant_id=None) # depends on [control=['if'], data=[]] return comment_objs
def get_help(obj, env, subcmds): """Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any. """ doc = txt.dedent(obj.__doc__ or "") env = env.copy() ## get a local copy doc = doc.strip() if not re.search(r"^usage:\s*$", doc, flags=re.IGNORECASE | re.MULTILINE): doc += txt.dedent(""" Usage: %(std_usage)s Options: %(std_options)s""") help_line = (" %%-%ds %%s" % (max([5] + [len(a) for a in subcmds]), )) env["actions"] = "\n".join( help_line % ( name, get_help(subcmd, subcmd_env(env, name), {}).split("\n")[0]) for name, subcmd in subcmds.items()) env["actions_help"] = "" if not env["actions"] else ( "ACTION could be one of:\n\n" "%(actions)s\n\n" "See '%(surcmd)s help ACTION' for more information " "on a specific command." % env) if "%(std_usage)s" in doc: env["std_usage"] = txt.indent( ("%(surcmd)s --help\n" "%(surcmd)s --version" + (("\n%(surcmd)s help [COMMAND]" "\n%(surcmd)s ACTION [ARGS...]") if subcmds else "")) % env, _find_prefix(doc, "%(std_usage)s"), first="") if "%(std_options)s" in doc: env["std_options"] = txt.indent( "--help Show this screen.\n" "--version Show version.", _find_prefix(doc, "%(std_options)s"), first="") if subcmds and "%(actions_help)s" not in doc: doc += "\n\n%(actions_help)s" try: output = doc % env except KeyError as e: msg.err("Doc interpolation of %s needed missing key %r" % (aformat(env["surcmd"], attrs=["bold", ]), e.args[0])) exit(1) except Exception as e: msg.err( "Documentation of %s is not valid. Please check it:\n%s" % (aformat(env["surcmd"], attrs=["bold", ]), doc)) exit(1) return output
def function[get_help, parameter[obj, env, subcmds]]: constant[Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any. ] variable[doc] assign[=] call[name[txt].dedent, parameter[<ast.BoolOp object at 0x7da18ede64a0>]] variable[env] assign[=] call[name[env].copy, parameter[]] variable[doc] assign[=] call[name[doc].strip, parameter[]] if <ast.UnaryOp object at 0x7da18ede65c0> begin[:] <ast.AugAssign object at 0x7da18ede4fa0> variable[help_line] assign[=] binary_operation[constant[ %%-%ds %%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Call object at 0x7da18ede4160>]]] call[name[env]][constant[actions]] assign[=] call[constant[ ].join, parameter[<ast.GeneratorExp object at 0x7da18ede5b10>]] call[name[env]][constant[actions_help]] assign[=] <ast.IfExp object at 0x7da18ede4b50> if compare[constant[%(std_usage)s] in name[doc]] begin[:] call[name[env]][constant[std_usage]] assign[=] call[name[txt].indent, parameter[binary_operation[binary_operation[constant[%(surcmd)s --help %(surcmd)s --version] + <ast.IfExp object at 0x7da18ede7b80>] <ast.Mod object at 0x7da2590d6920> name[env]], call[name[_find_prefix], parameter[name[doc], constant[%(std_usage)s]]]]] if compare[constant[%(std_options)s] in name[doc]] begin[:] call[name[env]][constant[std_options]] assign[=] call[name[txt].indent, parameter[constant[--help Show this screen. --version Show version.], call[name[_find_prefix], parameter[name[doc], constant[%(std_options)s]]]]] if <ast.BoolOp object at 0x7da18ede5360> begin[:] <ast.AugAssign object at 0x7da18ede6b00> <ast.Try object at 0x7da18ede75e0> return[name[output]]
keyword[def] identifier[get_help] ( identifier[obj] , identifier[env] , identifier[subcmds] ): literal[string] identifier[doc] = identifier[txt] . identifier[dedent] ( identifier[obj] . identifier[__doc__] keyword[or] literal[string] ) identifier[env] = identifier[env] . identifier[copy] () identifier[doc] = identifier[doc] . identifier[strip] () keyword[if] keyword[not] identifier[re] . identifier[search] ( literal[string] , identifier[doc] , identifier[flags] = identifier[re] . identifier[IGNORECASE] | identifier[re] . identifier[MULTILINE] ): identifier[doc] += identifier[txt] . identifier[dedent] ( literal[string] ) identifier[help_line] =( literal[string] %( identifier[max] ([ literal[int] ]+[ identifier[len] ( identifier[a] ) keyword[for] identifier[a] keyword[in] identifier[subcmds] ]),)) identifier[env] [ literal[string] ]= literal[string] . identifier[join] ( identifier[help_line] %( identifier[name] , identifier[get_help] ( identifier[subcmd] , identifier[subcmd_env] ( identifier[env] , identifier[name] ),{}). identifier[split] ( literal[string] )[ literal[int] ]) keyword[for] identifier[name] , identifier[subcmd] keyword[in] identifier[subcmds] . identifier[items] ()) identifier[env] [ literal[string] ]= literal[string] keyword[if] keyword[not] identifier[env] [ literal[string] ] keyword[else] ( literal[string] literal[string] literal[string] literal[string] % identifier[env] ) keyword[if] literal[string] keyword[in] identifier[doc] : identifier[env] [ literal[string] ]= identifier[txt] . identifier[indent] ( ( literal[string] literal[string] + (( literal[string] literal[string] ) keyword[if] identifier[subcmds] keyword[else] literal[string] )) % identifier[env] , identifier[_find_prefix] ( identifier[doc] , literal[string] ), identifier[first] = literal[string] ) keyword[if] literal[string] keyword[in] identifier[doc] : identifier[env] [ literal[string] ]= identifier[txt] . identifier[indent] ( literal[string] literal[string] , identifier[_find_prefix] ( identifier[doc] , literal[string] ), identifier[first] = literal[string] ) keyword[if] identifier[subcmds] keyword[and] literal[string] keyword[not] keyword[in] identifier[doc] : identifier[doc] += literal[string] keyword[try] : identifier[output] = identifier[doc] % identifier[env] keyword[except] identifier[KeyError] keyword[as] identifier[e] : identifier[msg] . identifier[err] ( literal[string] %( identifier[aformat] ( identifier[env] [ literal[string] ], identifier[attrs] =[ literal[string] ,]), identifier[e] . identifier[args] [ literal[int] ])) identifier[exit] ( literal[int] ) keyword[except] identifier[Exception] keyword[as] identifier[e] : identifier[msg] . identifier[err] ( literal[string] %( identifier[aformat] ( identifier[env] [ literal[string] ], identifier[attrs] =[ literal[string] ,]), identifier[doc] )) identifier[exit] ( literal[int] ) keyword[return] identifier[output]
def get_help(obj, env, subcmds): """Interpolate complete help doc of given object Assumption that given object as a specific interface: obj.__doc__ is the basic help object. obj.get_actions_titles() returns the subcommand if any. """ doc = txt.dedent(obj.__doc__ or '') env = env.copy() ## get a local copy doc = doc.strip() if not re.search('^usage:\\s*$', doc, flags=re.IGNORECASE | re.MULTILINE): doc += txt.dedent('\n\n Usage:\n %(std_usage)s\n\n Options:\n %(std_options)s') # depends on [control=['if'], data=[]] help_line = ' %%-%ds %%s' % (max([5] + [len(a) for a in subcmds]),) env['actions'] = '\n'.join((help_line % (name, get_help(subcmd, subcmd_env(env, name), {}).split('\n')[0]) for (name, subcmd) in subcmds.items())) env['actions_help'] = '' if not env['actions'] else "ACTION could be one of:\n\n%(actions)s\n\nSee '%(surcmd)s help ACTION' for more information on a specific command." % env if '%(std_usage)s' in doc: env['std_usage'] = txt.indent(('%(surcmd)s --help\n%(surcmd)s --version' + ('\n%(surcmd)s help [COMMAND]\n%(surcmd)s ACTION [ARGS...]' if subcmds else '')) % env, _find_prefix(doc, '%(std_usage)s'), first='') # depends on [control=['if'], data=['doc']] if '%(std_options)s' in doc: env['std_options'] = txt.indent('--help Show this screen.\n--version Show version.', _find_prefix(doc, '%(std_options)s'), first='') # depends on [control=['if'], data=['doc']] if subcmds and '%(actions_help)s' not in doc: doc += '\n\n%(actions_help)s' # depends on [control=['if'], data=[]] try: output = doc % env # depends on [control=['try'], data=[]] except KeyError as e: msg.err('Doc interpolation of %s needed missing key %r' % (aformat(env['surcmd'], attrs=['bold']), e.args[0])) exit(1) # depends on [control=['except'], data=['e']] except Exception as e: msg.err('Documentation of %s is not valid. Please check it:\n%s' % (aformat(env['surcmd'], attrs=['bold']), doc)) exit(1) # depends on [control=['except'], data=[]] return output
def set_parent(self, parent): """ Args: - **parent** ((:class:`~pyFG.forticonfig.FortiConfig`): FortiConfig object you want to set as parent. """ self.parent = parent if self.config_type == 'edit': self.rel_path_fwd = 'edit %s\n' % self.get_name() self.rel_path_bwd = 'next\n' elif self.config_type == 'config': self.rel_path_fwd = 'config %s\n' % self.get_name() self.rel_path_bwd = 'end\n' self.full_path_fwd = '%s%s' % (self.get_parent().full_path_fwd, self.rel_path_fwd) self.full_path_bwd = '%s%s' % (self.rel_path_bwd, self.get_parent().full_path_bwd)
def function[set_parent, parameter[self, parent]]: constant[ Args: - **parent** ((:class:`~pyFG.forticonfig.FortiConfig`): FortiConfig object you want to set as parent. ] name[self].parent assign[=] name[parent] if compare[name[self].config_type equal[==] constant[edit]] begin[:] name[self].rel_path_fwd assign[=] binary_operation[constant[edit %s ] <ast.Mod object at 0x7da2590d6920> call[name[self].get_name, parameter[]]] name[self].rel_path_bwd assign[=] constant[next ] name[self].full_path_fwd assign[=] binary_operation[constant[%s%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da2044c0b50>, <ast.Attribute object at 0x7da2044c1420>]]] name[self].full_path_bwd assign[=] binary_operation[constant[%s%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da2054a5ba0>, <ast.Attribute object at 0x7da2054a6e60>]]]
keyword[def] identifier[set_parent] ( identifier[self] , identifier[parent] ): literal[string] identifier[self] . identifier[parent] = identifier[parent] keyword[if] identifier[self] . identifier[config_type] == literal[string] : identifier[self] . identifier[rel_path_fwd] = literal[string] % identifier[self] . identifier[get_name] () identifier[self] . identifier[rel_path_bwd] = literal[string] keyword[elif] identifier[self] . identifier[config_type] == literal[string] : identifier[self] . identifier[rel_path_fwd] = literal[string] % identifier[self] . identifier[get_name] () identifier[self] . identifier[rel_path_bwd] = literal[string] identifier[self] . identifier[full_path_fwd] = literal[string] %( identifier[self] . identifier[get_parent] (). identifier[full_path_fwd] , identifier[self] . identifier[rel_path_fwd] ) identifier[self] . identifier[full_path_bwd] = literal[string] %( identifier[self] . identifier[rel_path_bwd] , identifier[self] . identifier[get_parent] (). identifier[full_path_bwd] )
def set_parent(self, parent): """ Args: - **parent** ((:class:`~pyFG.forticonfig.FortiConfig`): FortiConfig object you want to set as parent. """ self.parent = parent if self.config_type == 'edit': self.rel_path_fwd = 'edit %s\n' % self.get_name() self.rel_path_bwd = 'next\n' # depends on [control=['if'], data=[]] elif self.config_type == 'config': self.rel_path_fwd = 'config %s\n' % self.get_name() self.rel_path_bwd = 'end\n' # depends on [control=['if'], data=[]] self.full_path_fwd = '%s%s' % (self.get_parent().full_path_fwd, self.rel_path_fwd) self.full_path_bwd = '%s%s' % (self.rel_path_bwd, self.get_parent().full_path_bwd)
def parse_detail(self, response): """Parse individual product's detail""" # Product Information (a start) product_data = { 'url': response.url, 'name': response.css('div.page-title h1::text').extract_first(), } # Inventory Number inventory_number = re.search( r'(?P<inv_num>\d+)$', response.css('span.product-in::text').extract_first(), ).group('inv_num') product_data.update({'in': inventory_number}) # Specifications (arbitrary key:value pairs) specs_table = response.css('#tab-specs dl') for row in specs_table.css('div.spec-row'): keys = row.css('dt::text').extract() values = row.css('dd::text').extract() product_data.update({ key: value for (key, value) in zip(keys, values) }) self.logger.info(product_data['name']) yield product_data
def function[parse_detail, parameter[self, response]]: constant[Parse individual product's detail] variable[product_data] assign[=] dictionary[[<ast.Constant object at 0x7da18f811180>, <ast.Constant object at 0x7da18f8102e0>], [<ast.Attribute object at 0x7da18f811b40>, <ast.Call object at 0x7da18f8101c0>]] variable[inventory_number] assign[=] call[call[name[re].search, parameter[constant[(?P<inv_num>\d+)$], call[call[name[response].css, parameter[constant[span.product-in::text]]].extract_first, parameter[]]]].group, parameter[constant[inv_num]]] call[name[product_data].update, parameter[dictionary[[<ast.Constant object at 0x7da18f8111e0>], [<ast.Name object at 0x7da18f812c50>]]]] variable[specs_table] assign[=] call[name[response].css, parameter[constant[#tab-specs dl]]] for taget[name[row]] in starred[call[name[specs_table].css, parameter[constant[div.spec-row]]]] begin[:] variable[keys] assign[=] call[call[name[row].css, parameter[constant[dt::text]]].extract, parameter[]] variable[values] assign[=] call[call[name[row].css, parameter[constant[dd::text]]].extract, parameter[]] call[name[product_data].update, parameter[<ast.DictComp object at 0x7da18f811c60>]] call[name[self].logger.info, parameter[call[name[product_data]][constant[name]]]] <ast.Yield object at 0x7da18f8133a0>
keyword[def] identifier[parse_detail] ( identifier[self] , identifier[response] ): literal[string] identifier[product_data] ={ literal[string] : identifier[response] . identifier[url] , literal[string] : identifier[response] . identifier[css] ( literal[string] ). identifier[extract_first] (), } identifier[inventory_number] = identifier[re] . identifier[search] ( literal[string] , identifier[response] . identifier[css] ( literal[string] ). identifier[extract_first] (), ). identifier[group] ( literal[string] ) identifier[product_data] . identifier[update] ({ literal[string] : identifier[inventory_number] }) identifier[specs_table] = identifier[response] . identifier[css] ( literal[string] ) keyword[for] identifier[row] keyword[in] identifier[specs_table] . identifier[css] ( literal[string] ): identifier[keys] = identifier[row] . identifier[css] ( literal[string] ). identifier[extract] () identifier[values] = identifier[row] . identifier[css] ( literal[string] ). identifier[extract] () identifier[product_data] . identifier[update] ({ identifier[key] : identifier[value] keyword[for] ( identifier[key] , identifier[value] ) keyword[in] identifier[zip] ( identifier[keys] , identifier[values] ) }) identifier[self] . identifier[logger] . identifier[info] ( identifier[product_data] [ literal[string] ]) keyword[yield] identifier[product_data]
def parse_detail(self, response): """Parse individual product's detail""" # Product Information (a start) product_data = {'url': response.url, 'name': response.css('div.page-title h1::text').extract_first()} # Inventory Number inventory_number = re.search('(?P<inv_num>\\d+)$', response.css('span.product-in::text').extract_first()).group('inv_num') product_data.update({'in': inventory_number}) # Specifications (arbitrary key:value pairs) specs_table = response.css('#tab-specs dl') for row in specs_table.css('div.spec-row'): keys = row.css('dt::text').extract() values = row.css('dd::text').extract() product_data.update({key: value for (key, value) in zip(keys, values)}) # depends on [control=['for'], data=['row']] self.logger.info(product_data['name']) yield product_data
def select_joystick(): '''Allow user to select a joystick from a menu''' list_joysticks() while True: print('Select a joystick (L to list, Q to quit)'), choice = sys.stdin.readline().strip() if choice.lower() == 'l': list_joysticks() elif choice.lower() == 'q': return elif choice.isdigit(): jid = int(choice) if jid not in range(pygame.joystick.get_count()): print('Invalid joystick.') continue break else: print('What?') return jid
def function[select_joystick, parameter[]]: constant[Allow user to select a joystick from a menu] call[name[list_joysticks], parameter[]] while constant[True] begin[:] tuple[[<ast.Call object at 0x7da2046224a0>]] variable[choice] assign[=] call[call[name[sys].stdin.readline, parameter[]].strip, parameter[]] if compare[call[name[choice].lower, parameter[]] equal[==] constant[l]] begin[:] call[name[list_joysticks], parameter[]] return[name[jid]]
keyword[def] identifier[select_joystick] (): literal[string] identifier[list_joysticks] () keyword[while] keyword[True] : identifier[print] ( literal[string] ), identifier[choice] = identifier[sys] . identifier[stdin] . identifier[readline] (). identifier[strip] () keyword[if] identifier[choice] . identifier[lower] ()== literal[string] : identifier[list_joysticks] () keyword[elif] identifier[choice] . identifier[lower] ()== literal[string] : keyword[return] keyword[elif] identifier[choice] . identifier[isdigit] (): identifier[jid] = identifier[int] ( identifier[choice] ) keyword[if] identifier[jid] keyword[not] keyword[in] identifier[range] ( identifier[pygame] . identifier[joystick] . identifier[get_count] ()): identifier[print] ( literal[string] ) keyword[continue] keyword[break] keyword[else] : identifier[print] ( literal[string] ) keyword[return] identifier[jid]
def select_joystick(): """Allow user to select a joystick from a menu""" list_joysticks() while True: (print('Select a joystick (L to list, Q to quit)'),) choice = sys.stdin.readline().strip() if choice.lower() == 'l': list_joysticks() # depends on [control=['if'], data=[]] elif choice.lower() == 'q': return # depends on [control=['if'], data=[]] elif choice.isdigit(): jid = int(choice) if jid not in range(pygame.joystick.get_count()): print('Invalid joystick.') continue # depends on [control=['if'], data=[]] break # depends on [control=['if'], data=[]] else: print('What?') # depends on [control=['while'], data=[]] return jid
def to_dict(self, **kwargs): """ Serialize the search into the dictionary that will be sent over as the request'ubq body. All additional keyword arguments will be included into the dictionary. """ d = {} if self.query: d["query"] = self.query.to_dict() if self._script: d['script'] = self._script d.update(self._extra) d.update(kwargs) return d
def function[to_dict, parameter[self]]: constant[ Serialize the search into the dictionary that will be sent over as the request'ubq body. All additional keyword arguments will be included into the dictionary. ] variable[d] assign[=] dictionary[[], []] if name[self].query begin[:] call[name[d]][constant[query]] assign[=] call[name[self].query.to_dict, parameter[]] if name[self]._script begin[:] call[name[d]][constant[script]] assign[=] name[self]._script call[name[d].update, parameter[name[self]._extra]] call[name[d].update, parameter[name[kwargs]]] return[name[d]]
keyword[def] identifier[to_dict] ( identifier[self] ,** identifier[kwargs] ): literal[string] identifier[d] ={} keyword[if] identifier[self] . identifier[query] : identifier[d] [ literal[string] ]= identifier[self] . identifier[query] . identifier[to_dict] () keyword[if] identifier[self] . identifier[_script] : identifier[d] [ literal[string] ]= identifier[self] . identifier[_script] identifier[d] . identifier[update] ( identifier[self] . identifier[_extra] ) identifier[d] . identifier[update] ( identifier[kwargs] ) keyword[return] identifier[d]
def to_dict(self, **kwargs): """ Serialize the search into the dictionary that will be sent over as the request'ubq body. All additional keyword arguments will be included into the dictionary. """ d = {} if self.query: d['query'] = self.query.to_dict() # depends on [control=['if'], data=[]] if self._script: d['script'] = self._script # depends on [control=['if'], data=[]] d.update(self._extra) d.update(kwargs) return d
def read_binary(self, ba, param_groups=None): """ ba - binaryDataArray XML node """ if ba is None: return [] pgr = ba.find('m:referenceableParamGroupRef', namespaces=self.ns) if pgr is not None and param_groups is not None: q = 'm:referenceableParamGroup[@id="' + pgr.get('ref') + '"]' pg = param_groups.find(q, namespaces=self.ns) else: pg = ba if pg.find('m:cvParam[@accession="MS:1000574"]', namespaces=self.ns) is not None: compress = True elif pg.find('m:cvParam[@accession="MS:1000576"]', namespaces=self.ns) is not None: compress = False else: # TODO: no info? should check the other record? pass if pg.find('m:cvParam[@accession="MS:1000521"]', namespaces=self.ns) is not None: dtype = 'f' elif pg.find('m:cvParam[@accession="MS:1000523"]', namespaces=self.ns) is not None: dtype = 'd' else: # TODO: no info? should check the other record? pass datatext = ba.find('m:binary', namespaces=self.ns).text if compress: rawdata = zlib.decompress(base64.b64decode(datatext)) else: rawdata = base64.b64decode(datatext) return np.fromstring(rawdata, dtype=dtype)
def function[read_binary, parameter[self, ba, param_groups]]: constant[ ba - binaryDataArray XML node ] if compare[name[ba] is constant[None]] begin[:] return[list[[]]] variable[pgr] assign[=] call[name[ba].find, parameter[constant[m:referenceableParamGroupRef]]] if <ast.BoolOp object at 0x7da20c76ce20> begin[:] variable[q] assign[=] binary_operation[binary_operation[constant[m:referenceableParamGroup[@id="] + call[name[pgr].get, parameter[constant[ref]]]] + constant["]]] variable[pg] assign[=] call[name[param_groups].find, parameter[name[q]]] if compare[call[name[pg].find, parameter[constant[m:cvParam[@accession="MS:1000574"]]]] is_not constant[None]] begin[:] variable[compress] assign[=] constant[True] if compare[call[name[pg].find, parameter[constant[m:cvParam[@accession="MS:1000521"]]]] is_not constant[None]] begin[:] variable[dtype] assign[=] constant[f] variable[datatext] assign[=] call[name[ba].find, parameter[constant[m:binary]]].text if name[compress] begin[:] variable[rawdata] assign[=] call[name[zlib].decompress, parameter[call[name[base64].b64decode, parameter[name[datatext]]]]] return[call[name[np].fromstring, parameter[name[rawdata]]]]
keyword[def] identifier[read_binary] ( identifier[self] , identifier[ba] , identifier[param_groups] = keyword[None] ): literal[string] keyword[if] identifier[ba] keyword[is] keyword[None] : keyword[return] [] identifier[pgr] = identifier[ba] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[self] . identifier[ns] ) keyword[if] identifier[pgr] keyword[is] keyword[not] keyword[None] keyword[and] identifier[param_groups] keyword[is] keyword[not] keyword[None] : identifier[q] = literal[string] + identifier[pgr] . identifier[get] ( literal[string] )+ literal[string] identifier[pg] = identifier[param_groups] . identifier[find] ( identifier[q] , identifier[namespaces] = identifier[self] . identifier[ns] ) keyword[else] : identifier[pg] = identifier[ba] keyword[if] identifier[pg] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[self] . identifier[ns] ) keyword[is] keyword[not] keyword[None] : identifier[compress] = keyword[True] keyword[elif] identifier[pg] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[self] . identifier[ns] ) keyword[is] keyword[not] keyword[None] : identifier[compress] = keyword[False] keyword[else] : keyword[pass] keyword[if] identifier[pg] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[self] . identifier[ns] ) keyword[is] keyword[not] keyword[None] : identifier[dtype] = literal[string] keyword[elif] identifier[pg] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[self] . identifier[ns] ) keyword[is] keyword[not] keyword[None] : identifier[dtype] = literal[string] keyword[else] : keyword[pass] identifier[datatext] = identifier[ba] . identifier[find] ( literal[string] , identifier[namespaces] = identifier[self] . identifier[ns] ). identifier[text] keyword[if] identifier[compress] : identifier[rawdata] = identifier[zlib] . identifier[decompress] ( identifier[base64] . identifier[b64decode] ( identifier[datatext] )) keyword[else] : identifier[rawdata] = identifier[base64] . identifier[b64decode] ( identifier[datatext] ) keyword[return] identifier[np] . identifier[fromstring] ( identifier[rawdata] , identifier[dtype] = identifier[dtype] )
def read_binary(self, ba, param_groups=None): """ ba - binaryDataArray XML node """ if ba is None: return [] # depends on [control=['if'], data=[]] pgr = ba.find('m:referenceableParamGroupRef', namespaces=self.ns) if pgr is not None and param_groups is not None: q = 'm:referenceableParamGroup[@id="' + pgr.get('ref') + '"]' pg = param_groups.find(q, namespaces=self.ns) # depends on [control=['if'], data=[]] else: pg = ba if pg.find('m:cvParam[@accession="MS:1000574"]', namespaces=self.ns) is not None: compress = True # depends on [control=['if'], data=[]] elif pg.find('m:cvParam[@accession="MS:1000576"]', namespaces=self.ns) is not None: compress = False # depends on [control=['if'], data=[]] else: # TODO: no info? should check the other record? pass if pg.find('m:cvParam[@accession="MS:1000521"]', namespaces=self.ns) is not None: dtype = 'f' # depends on [control=['if'], data=[]] elif pg.find('m:cvParam[@accession="MS:1000523"]', namespaces=self.ns) is not None: dtype = 'd' # depends on [control=['if'], data=[]] else: # TODO: no info? should check the other record? pass datatext = ba.find('m:binary', namespaces=self.ns).text if compress: rawdata = zlib.decompress(base64.b64decode(datatext)) # depends on [control=['if'], data=[]] else: rawdata = base64.b64decode(datatext) return np.fromstring(rawdata, dtype=dtype)
def get_simulated_epw_path(): """ Returns ------- None if epw can be anywhere """ from oplus import CONF # touchy imports if OS_NAME == "windows": return os.path.join(CONF.eplus_base_dir_path, "WeatherData", "%s.epw" % CONF.default_model_name)
def function[get_simulated_epw_path, parameter[]]: constant[ Returns ------- None if epw can be anywhere ] from relative_module[oplus] import module[CONF] if compare[name[OS_NAME] equal[==] constant[windows]] begin[:] return[call[name[os].path.join, parameter[name[CONF].eplus_base_dir_path, constant[WeatherData], binary_operation[constant[%s.epw] <ast.Mod object at 0x7da2590d6920> name[CONF].default_model_name]]]]
keyword[def] identifier[get_simulated_epw_path] (): literal[string] keyword[from] identifier[oplus] keyword[import] identifier[CONF] keyword[if] identifier[OS_NAME] == literal[string] : keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[CONF] . identifier[eplus_base_dir_path] , literal[string] , literal[string] % identifier[CONF] . identifier[default_model_name] )
def get_simulated_epw_path(): """ Returns ------- None if epw can be anywhere """ from oplus import CONF # touchy imports if OS_NAME == 'windows': return os.path.join(CONF.eplus_base_dir_path, 'WeatherData', '%s.epw' % CONF.default_model_name) # depends on [control=['if'], data=[]]
def _required_constraint_name(table: str, field, key): """Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. Returns: The name for the UNIQUE index. """ return '{table}_{field}_required_{postfix}'.format( table=table, field=field.column, postfix=key )
def function[_required_constraint_name, parameter[table, field, key]]: constant[Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. Returns: The name for the UNIQUE index. ] return[call[constant[{table}_{field}_required_{postfix}].format, parameter[]]]
keyword[def] identifier[_required_constraint_name] ( identifier[table] : identifier[str] , identifier[field] , identifier[key] ): literal[string] keyword[return] literal[string] . identifier[format] ( identifier[table] = identifier[table] , identifier[field] = identifier[field] . identifier[column] , identifier[postfix] = identifier[key] )
def _required_constraint_name(table: str, field, key): """Gets the name for a CONSTRAINT that applies to a single hstore key. Arguments: table: The name of the table the field is a part of. field: The hstore field to create a UNIQUE INDEX for. key: The name of the hstore key to create the name for. Returns: The name for the UNIQUE index. """ return '{table}_{field}_required_{postfix}'.format(table=table, field=field.column, postfix=key)
def _n_rectangles(obj): ''' Calculate the total number of rectangles with respect to the type of the object ''' return sum(_total_rectangles(neu) for neu in obj.neurites) \ if hasattr(obj, 'neurites') else _total_rectangles(obj)
def function[_n_rectangles, parameter[obj]]: constant[ Calculate the total number of rectangles with respect to the type of the object ] return[<ast.IfExp object at 0x7da18fe904c0>]
keyword[def] identifier[_n_rectangles] ( identifier[obj] ): literal[string] keyword[return] identifier[sum] ( identifier[_total_rectangles] ( identifier[neu] ) keyword[for] identifier[neu] keyword[in] identifier[obj] . identifier[neurites] ) keyword[if] identifier[hasattr] ( identifier[obj] , literal[string] ) keyword[else] identifier[_total_rectangles] ( identifier[obj] )
def _n_rectangles(obj): """ Calculate the total number of rectangles with respect to the type of the object """ return sum((_total_rectangles(neu) for neu in obj.neurites)) if hasattr(obj, 'neurites') else _total_rectangles(obj)
def _getDetails(self, uriRef, associations_details): """ Given a uriRef, return a dict of all the details for that Ref use the uriRef as the 'id' of the dict """ associationDetail = {} for detail in associations_details: if detail['subject'] == uriRef: associationDetail[detail['predicate']] = detail['object'] associationDetail['id'] = uriRef return associationDetail
def function[_getDetails, parameter[self, uriRef, associations_details]]: constant[ Given a uriRef, return a dict of all the details for that Ref use the uriRef as the 'id' of the dict ] variable[associationDetail] assign[=] dictionary[[], []] for taget[name[detail]] in starred[name[associations_details]] begin[:] if compare[call[name[detail]][constant[subject]] equal[==] name[uriRef]] begin[:] call[name[associationDetail]][call[name[detail]][constant[predicate]]] assign[=] call[name[detail]][constant[object]] call[name[associationDetail]][constant[id]] assign[=] name[uriRef] return[name[associationDetail]]
keyword[def] identifier[_getDetails] ( identifier[self] , identifier[uriRef] , identifier[associations_details] ): literal[string] identifier[associationDetail] ={} keyword[for] identifier[detail] keyword[in] identifier[associations_details] : keyword[if] identifier[detail] [ literal[string] ]== identifier[uriRef] : identifier[associationDetail] [ identifier[detail] [ literal[string] ]]= identifier[detail] [ literal[string] ] identifier[associationDetail] [ literal[string] ]= identifier[uriRef] keyword[return] identifier[associationDetail]
def _getDetails(self, uriRef, associations_details): """ Given a uriRef, return a dict of all the details for that Ref use the uriRef as the 'id' of the dict """ associationDetail = {} for detail in associations_details: if detail['subject'] == uriRef: associationDetail[detail['predicate']] = detail['object'] # depends on [control=['if'], data=[]] associationDetail['id'] = uriRef # depends on [control=['for'], data=['detail']] return associationDetail
def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """ color = QColor() if not is_string(text): # testing for QString (PyQt API#1) text = str(text) if not is_text_string(text): return color if text.startswith('#') and len(text)==7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color elif text not in list(QColor.colorNames()): return color color.setNamedColor(text) return color
def function[text_to_qcolor, parameter[text]]: constant[ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated ] variable[color] assign[=] call[name[QColor], parameter[]] if <ast.UnaryOp object at 0x7da18ede5150> begin[:] variable[text] assign[=] call[name[str], parameter[name[text]]] if <ast.UnaryOp object at 0x7da1b23462c0> begin[:] return[name[color]] if <ast.BoolOp object at 0x7da1b2346170> begin[:] variable[correct] assign[=] constant[#0123456789abcdef] for taget[name[char]] in starred[name[text]] begin[:] if compare[call[name[char].lower, parameter[]] <ast.NotIn object at 0x7da2590d7190> name[correct]] begin[:] return[name[color]] call[name[color].setNamedColor, parameter[name[text]]] return[name[color]]
keyword[def] identifier[text_to_qcolor] ( identifier[text] ): literal[string] identifier[color] = identifier[QColor] () keyword[if] keyword[not] identifier[is_string] ( identifier[text] ): identifier[text] = identifier[str] ( identifier[text] ) keyword[if] keyword[not] identifier[is_text_string] ( identifier[text] ): keyword[return] identifier[color] keyword[if] identifier[text] . identifier[startswith] ( literal[string] ) keyword[and] identifier[len] ( identifier[text] )== literal[int] : identifier[correct] = literal[string] keyword[for] identifier[char] keyword[in] identifier[text] : keyword[if] identifier[char] . identifier[lower] () keyword[not] keyword[in] identifier[correct] : keyword[return] identifier[color] keyword[elif] identifier[text] keyword[not] keyword[in] identifier[list] ( identifier[QColor] . identifier[colorNames] ()): keyword[return] identifier[color] identifier[color] . identifier[setNamedColor] ( identifier[text] ) keyword[return] identifier[color]
def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """ color = QColor() if not is_string(text): # testing for QString (PyQt API#1) text = str(text) # depends on [control=['if'], data=[]] if not is_text_string(text): return color # depends on [control=['if'], data=[]] if text.startswith('#') and len(text) == 7: correct = '#0123456789abcdef' for char in text: if char.lower() not in correct: return color # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['char']] # depends on [control=['if'], data=[]] elif text not in list(QColor.colorNames()): return color # depends on [control=['if'], data=[]] color.setNamedColor(text) return color
def connect(self, interface, event, object_path, handler): """ Connect to a DBus signal. If ``object_path`` is None, subscribe for all objects and invoke the callback with the object_path as its first argument. """ if object_path: def callback(connection, sender_name, object_path, interface_name, signal_name, parameters): return handler(*unpack_variant(parameters)) else: def callback(connection, sender_name, object_path, interface_name, signal_name, parameters): return handler(object_path, *unpack_variant(parameters)) return self.connection.signal_subscribe( self.bus_name, interface, event, object_path, None, Gio.DBusSignalFlags.NONE, callback, )
def function[connect, parameter[self, interface, event, object_path, handler]]: constant[ Connect to a DBus signal. If ``object_path`` is None, subscribe for all objects and invoke the callback with the object_path as its first argument. ] if name[object_path] begin[:] def function[callback, parameter[connection, sender_name, object_path, interface_name, signal_name, parameters]]: return[call[name[handler], parameter[<ast.Starred object at 0x7da18c4cfdc0>]]] return[call[name[self].connection.signal_subscribe, parameter[name[self].bus_name, name[interface], name[event], name[object_path], constant[None], name[Gio].DBusSignalFlags.NONE, name[callback]]]]
keyword[def] identifier[connect] ( identifier[self] , identifier[interface] , identifier[event] , identifier[object_path] , identifier[handler] ): literal[string] keyword[if] identifier[object_path] : keyword[def] identifier[callback] ( identifier[connection] , identifier[sender_name] , identifier[object_path] , identifier[interface_name] , identifier[signal_name] , identifier[parameters] ): keyword[return] identifier[handler] (* identifier[unpack_variant] ( identifier[parameters] )) keyword[else] : keyword[def] identifier[callback] ( identifier[connection] , identifier[sender_name] , identifier[object_path] , identifier[interface_name] , identifier[signal_name] , identifier[parameters] ): keyword[return] identifier[handler] ( identifier[object_path] ,* identifier[unpack_variant] ( identifier[parameters] )) keyword[return] identifier[self] . identifier[connection] . identifier[signal_subscribe] ( identifier[self] . identifier[bus_name] , identifier[interface] , identifier[event] , identifier[object_path] , keyword[None] , identifier[Gio] . identifier[DBusSignalFlags] . identifier[NONE] , identifier[callback] , )
def connect(self, interface, event, object_path, handler): """ Connect to a DBus signal. If ``object_path`` is None, subscribe for all objects and invoke the callback with the object_path as its first argument. """ if object_path: def callback(connection, sender_name, object_path, interface_name, signal_name, parameters): return handler(*unpack_variant(parameters)) # depends on [control=['if'], data=[]] else: def callback(connection, sender_name, object_path, interface_name, signal_name, parameters): return handler(object_path, *unpack_variant(parameters)) return self.connection.signal_subscribe(self.bus_name, interface, event, object_path, None, Gio.DBusSignalFlags.NONE, callback)
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passed. """ query = parse_qs(query, keep_blank_values=True) # Load yaml of passed values for key, vals in query.items(): # Multiple values of the same name could be passed use first # Also params without strings will be treated as true values query[key] = yaml.load(vals[0] or 'true', Loader=yaml.FullLoader) # If expected, populate with defaults for key, val in cls.default_query.items(): if key not in query: query[key] = val return query
def function[conform_query, parameter[cls, query]]: constant[Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passed. ] variable[query] assign[=] call[name[parse_qs], parameter[name[query]]] for taget[tuple[[<ast.Name object at 0x7da1b1980f10>, <ast.Name object at 0x7da1b1980fa0>]]] in starred[call[name[query].items, parameter[]]] begin[:] call[name[query]][name[key]] assign[=] call[name[yaml].load, parameter[<ast.BoolOp object at 0x7da1b19818a0>]] for taget[tuple[[<ast.Name object at 0x7da1b190a5c0>, <ast.Name object at 0x7da1b1909210>]]] in starred[call[name[cls].default_query.items, parameter[]]] begin[:] if compare[name[key] <ast.NotIn object at 0x7da2590d7190> name[query]] begin[:] call[name[query]][name[key]] assign[=] name[val] return[name[query]]
keyword[def] identifier[conform_query] ( identifier[cls] , identifier[query] ): literal[string] identifier[query] = identifier[parse_qs] ( identifier[query] , identifier[keep_blank_values] = keyword[True] ) keyword[for] identifier[key] , identifier[vals] keyword[in] identifier[query] . identifier[items] (): identifier[query] [ identifier[key] ]= identifier[yaml] . identifier[load] ( identifier[vals] [ literal[int] ] keyword[or] literal[string] , identifier[Loader] = identifier[yaml] . identifier[FullLoader] ) keyword[for] identifier[key] , identifier[val] keyword[in] identifier[cls] . identifier[default_query] . identifier[items] (): keyword[if] identifier[key] keyword[not] keyword[in] identifier[query] : identifier[query] [ identifier[key] ]= identifier[val] keyword[return] identifier[query]
def conform_query(cls, query): """Converts the query string from a target uri, uses cls.default_query to populate default arguments. :param query: Unparsed query string :type query: urllib.parse.unsplit(uri).query :returns: Dictionary of parsed values, everything in cls.default_query will be set if not passed. """ query = parse_qs(query, keep_blank_values=True) # Load yaml of passed values for (key, vals) in query.items(): # Multiple values of the same name could be passed use first # Also params without strings will be treated as true values query[key] = yaml.load(vals[0] or 'true', Loader=yaml.FullLoader) # depends on [control=['for'], data=[]] # If expected, populate with defaults for (key, val) in cls.default_query.items(): if key not in query: query[key] = val # depends on [control=['if'], data=['key', 'query']] # depends on [control=['for'], data=[]] return query
def _gen_success_message(publish_output): """ Generate detailed success message for published applications. Parameters ---------- publish_output : dict Output from serverlessrepo publish_application Returns ------- str Detailed success message """ application_id = publish_output.get('application_id') details = json.dumps(publish_output.get('details'), indent=2) if CREATE_APPLICATION in publish_output.get('actions'): return "Created new application with the following metadata:\n{}".format(details) return 'The following metadata of application "{}" has been updated:\n{}'.format(application_id, details)
def function[_gen_success_message, parameter[publish_output]]: constant[ Generate detailed success message for published applications. Parameters ---------- publish_output : dict Output from serverlessrepo publish_application Returns ------- str Detailed success message ] variable[application_id] assign[=] call[name[publish_output].get, parameter[constant[application_id]]] variable[details] assign[=] call[name[json].dumps, parameter[call[name[publish_output].get, parameter[constant[details]]]]] if compare[name[CREATE_APPLICATION] in call[name[publish_output].get, parameter[constant[actions]]]] begin[:] return[call[constant[Created new application with the following metadata: {}].format, parameter[name[details]]]] return[call[constant[The following metadata of application "{}" has been updated: {}].format, parameter[name[application_id], name[details]]]]
keyword[def] identifier[_gen_success_message] ( identifier[publish_output] ): literal[string] identifier[application_id] = identifier[publish_output] . identifier[get] ( literal[string] ) identifier[details] = identifier[json] . identifier[dumps] ( identifier[publish_output] . identifier[get] ( literal[string] ), identifier[indent] = literal[int] ) keyword[if] identifier[CREATE_APPLICATION] keyword[in] identifier[publish_output] . identifier[get] ( literal[string] ): keyword[return] literal[string] . identifier[format] ( identifier[details] ) keyword[return] literal[string] . identifier[format] ( identifier[application_id] , identifier[details] )
def _gen_success_message(publish_output): """ Generate detailed success message for published applications. Parameters ---------- publish_output : dict Output from serverlessrepo publish_application Returns ------- str Detailed success message """ application_id = publish_output.get('application_id') details = json.dumps(publish_output.get('details'), indent=2) if CREATE_APPLICATION in publish_output.get('actions'): return 'Created new application with the following metadata:\n{}'.format(details) # depends on [control=['if'], data=[]] return 'The following metadata of application "{}" has been updated:\n{}'.format(application_id, details)
def rmdir(self, parents=False): """Removes this directory, provided it is empty. Use :func:`~rpaths.Path.rmtree` if it might still contain files. :param parents: If set to True, it will also destroy every empty directory above it until an error is encountered. """ if parents: os.removedirs(self.path) else: os.rmdir(self.path)
def function[rmdir, parameter[self, parents]]: constant[Removes this directory, provided it is empty. Use :func:`~rpaths.Path.rmtree` if it might still contain files. :param parents: If set to True, it will also destroy every empty directory above it until an error is encountered. ] if name[parents] begin[:] call[name[os].removedirs, parameter[name[self].path]]
keyword[def] identifier[rmdir] ( identifier[self] , identifier[parents] = keyword[False] ): literal[string] keyword[if] identifier[parents] : identifier[os] . identifier[removedirs] ( identifier[self] . identifier[path] ) keyword[else] : identifier[os] . identifier[rmdir] ( identifier[self] . identifier[path] )
def rmdir(self, parents=False): """Removes this directory, provided it is empty. Use :func:`~rpaths.Path.rmtree` if it might still contain files. :param parents: If set to True, it will also destroy every empty directory above it until an error is encountered. """ if parents: os.removedirs(self.path) # depends on [control=['if'], data=[]] else: os.rmdir(self.path)
def build(self, recipe): """ Builds a recipe :param recipe: Name of the recipe to build. """ return self.__app.recipes.build(recipe, self._plugin)
def function[build, parameter[self, recipe]]: constant[ Builds a recipe :param recipe: Name of the recipe to build. ] return[call[name[self].__app.recipes.build, parameter[name[recipe], name[self]._plugin]]]
keyword[def] identifier[build] ( identifier[self] , identifier[recipe] ): literal[string] keyword[return] identifier[self] . identifier[__app] . identifier[recipes] . identifier[build] ( identifier[recipe] , identifier[self] . identifier[_plugin] )
def build(self, recipe): """ Builds a recipe :param recipe: Name of the recipe to build. """ return self.__app.recipes.build(recipe, self._plugin)
def search(self, **kwargs): """ Method to search vrf's based on extends search. :param search: Dict containing QuerySets to find vrf's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing vrf's """ return super(ApiVrf, self).get(self.prepare_url('api/v3/vrf/', kwargs))
def function[search, parameter[self]]: constant[ Method to search vrf's based on extends search. :param search: Dict containing QuerySets to find vrf's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing vrf's ] return[call[call[name[super], parameter[name[ApiVrf], name[self]]].get, parameter[call[name[self].prepare_url, parameter[constant[api/v3/vrf/], name[kwargs]]]]]]
keyword[def] identifier[search] ( identifier[self] ,** identifier[kwargs] ): literal[string] keyword[return] identifier[super] ( identifier[ApiVrf] , identifier[self] ). identifier[get] ( identifier[self] . identifier[prepare_url] ( literal[string] , identifier[kwargs] ))
def search(self, **kwargs): """ Method to search vrf's based on extends search. :param search: Dict containing QuerySets to find vrf's. :param include: Array containing fields to include on response. :param exclude: Array containing fields to exclude on response. :param fields: Array containing fields to override default fields. :param kind: Determine if result will be detailed ('detail') or basic ('basic'). :return: Dict containing vrf's """ return super(ApiVrf, self).get(self.prepare_url('api/v3/vrf/', kwargs))
def interrupt(self): """ Invoked on a write operation into the IR of the RendererDevice. """ if(self.device.read(9) & 0x01): self.handle_request() self.device.clear_IR()
def function[interrupt, parameter[self]]: constant[ Invoked on a write operation into the IR of the RendererDevice. ] if binary_operation[call[name[self].device.read, parameter[constant[9]]] <ast.BitAnd object at 0x7da2590d6b60> constant[1]] begin[:] call[name[self].handle_request, parameter[]] call[name[self].device.clear_IR, parameter[]]
keyword[def] identifier[interrupt] ( identifier[self] ): literal[string] keyword[if] ( identifier[self] . identifier[device] . identifier[read] ( literal[int] )& literal[int] ): identifier[self] . identifier[handle_request] () identifier[self] . identifier[device] . identifier[clear_IR] ()
def interrupt(self): """ Invoked on a write operation into the IR of the RendererDevice. """ if self.device.read(9) & 1: self.handle_request() # depends on [control=['if'], data=[]] self.device.clear_IR()
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current index of the item """ # ensure we have an object and not a brain obj = api.get_object(obj) uid = api.get_uid(obj) url = api.get_url(obj) title = api.get_title(obj) # get the category if self.show_categories_enabled(): category = obj.getCategoryTitle() if category not in self.categories: self.categories.append(category) item["category"] = category item["replace"]["Title"] = get_link(url, value=title) item["selected"] = False item["selected"] = uid in self.selected_services_uids # Add methods methods = obj.getMethods() if methods: links = map( lambda m: get_link( m.absolute_url(), value=m.Title(), css_class="link"), methods) item["replace"]["Methods"] = ", ".join(links) else: item["methods"] = "" calculation = obj.getCalculation() if calculation: title = calculation.Title() url = calculation.absolute_url() item["Calculation"] = title item["replace"]["Calculation"] = get_link(url, value=title) else: item["Calculation"] = "" # Icons after_icons = "" if obj.getAccredited(): after_icons += get_image( "accredited.png", title=_("Accredited")) if obj.getAttachmentOption() == "r": after_icons += get_image( "attach_reqd.png", title=_("Attachment required")) if obj.getAttachmentOption() == "n": after_icons += get_image( "attach_no.png", title=_("Attachment not permitted")) if after_icons: item["after"]["Title"] = after_icons return item
def function[folderitem, parameter[self, obj, item, index]]: constant[Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current index of the item ] variable[obj] assign[=] call[name[api].get_object, parameter[name[obj]]] variable[uid] assign[=] call[name[api].get_uid, parameter[name[obj]]] variable[url] assign[=] call[name[api].get_url, parameter[name[obj]]] variable[title] assign[=] call[name[api].get_title, parameter[name[obj]]] if call[name[self].show_categories_enabled, parameter[]] begin[:] variable[category] assign[=] call[name[obj].getCategoryTitle, parameter[]] if compare[name[category] <ast.NotIn object at 0x7da2590d7190> name[self].categories] begin[:] call[name[self].categories.append, parameter[name[category]]] call[name[item]][constant[category]] assign[=] name[category] call[call[name[item]][constant[replace]]][constant[Title]] assign[=] call[name[get_link], parameter[name[url]]] call[name[item]][constant[selected]] assign[=] constant[False] call[name[item]][constant[selected]] assign[=] compare[name[uid] in name[self].selected_services_uids] variable[methods] assign[=] call[name[obj].getMethods, parameter[]] if name[methods] begin[:] variable[links] assign[=] call[name[map], parameter[<ast.Lambda object at 0x7da1b1d4a530>, name[methods]]] call[call[name[item]][constant[replace]]][constant[Methods]] assign[=] call[constant[, ].join, parameter[name[links]]] variable[calculation] assign[=] call[name[obj].getCalculation, parameter[]] if name[calculation] begin[:] variable[title] assign[=] call[name[calculation].Title, parameter[]] variable[url] assign[=] call[name[calculation].absolute_url, parameter[]] call[name[item]][constant[Calculation]] assign[=] name[title] call[call[name[item]][constant[replace]]][constant[Calculation]] assign[=] call[name[get_link], parameter[name[url]]] variable[after_icons] assign[=] constant[] if call[name[obj].getAccredited, parameter[]] begin[:] <ast.AugAssign object at 0x7da1b1d49960> if compare[call[name[obj].getAttachmentOption, parameter[]] equal[==] constant[r]] begin[:] <ast.AugAssign object at 0x7da1b1d48070> if compare[call[name[obj].getAttachmentOption, parameter[]] equal[==] constant[n]] begin[:] <ast.AugAssign object at 0x7da1b1d487f0> if name[after_icons] begin[:] call[call[name[item]][constant[after]]][constant[Title]] assign[=] name[after_icons] return[name[item]]
keyword[def] identifier[folderitem] ( identifier[self] , identifier[obj] , identifier[item] , identifier[index] ): literal[string] identifier[obj] = identifier[api] . identifier[get_object] ( identifier[obj] ) identifier[uid] = identifier[api] . identifier[get_uid] ( identifier[obj] ) identifier[url] = identifier[api] . identifier[get_url] ( identifier[obj] ) identifier[title] = identifier[api] . identifier[get_title] ( identifier[obj] ) keyword[if] identifier[self] . identifier[show_categories_enabled] (): identifier[category] = identifier[obj] . identifier[getCategoryTitle] () keyword[if] identifier[category] keyword[not] keyword[in] identifier[self] . identifier[categories] : identifier[self] . identifier[categories] . identifier[append] ( identifier[category] ) identifier[item] [ literal[string] ]= identifier[category] identifier[item] [ literal[string] ][ literal[string] ]= identifier[get_link] ( identifier[url] , identifier[value] = identifier[title] ) identifier[item] [ literal[string] ]= keyword[False] identifier[item] [ literal[string] ]= identifier[uid] keyword[in] identifier[self] . identifier[selected_services_uids] identifier[methods] = identifier[obj] . identifier[getMethods] () keyword[if] identifier[methods] : identifier[links] = identifier[map] ( keyword[lambda] identifier[m] : identifier[get_link] ( identifier[m] . identifier[absolute_url] (), identifier[value] = identifier[m] . identifier[Title] (), identifier[css_class] = literal[string] ), identifier[methods] ) identifier[item] [ literal[string] ][ literal[string] ]= literal[string] . identifier[join] ( identifier[links] ) keyword[else] : identifier[item] [ literal[string] ]= literal[string] identifier[calculation] = identifier[obj] . identifier[getCalculation] () keyword[if] identifier[calculation] : identifier[title] = identifier[calculation] . identifier[Title] () identifier[url] = identifier[calculation] . identifier[absolute_url] () identifier[item] [ literal[string] ]= identifier[title] identifier[item] [ literal[string] ][ literal[string] ]= identifier[get_link] ( identifier[url] , identifier[value] = identifier[title] ) keyword[else] : identifier[item] [ literal[string] ]= literal[string] identifier[after_icons] = literal[string] keyword[if] identifier[obj] . identifier[getAccredited] (): identifier[after_icons] += identifier[get_image] ( literal[string] , identifier[title] = identifier[_] ( literal[string] )) keyword[if] identifier[obj] . identifier[getAttachmentOption] ()== literal[string] : identifier[after_icons] += identifier[get_image] ( literal[string] , identifier[title] = identifier[_] ( literal[string] )) keyword[if] identifier[obj] . identifier[getAttachmentOption] ()== literal[string] : identifier[after_icons] += identifier[get_image] ( literal[string] , identifier[title] = identifier[_] ( literal[string] )) keyword[if] identifier[after_icons] : identifier[item] [ literal[string] ][ literal[string] ]= identifier[after_icons] keyword[return] identifier[item]
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by the template :index: current index of the item """ # ensure we have an object and not a brain obj = api.get_object(obj) uid = api.get_uid(obj) url = api.get_url(obj) title = api.get_title(obj) # get the category if self.show_categories_enabled(): category = obj.getCategoryTitle() if category not in self.categories: self.categories.append(category) # depends on [control=['if'], data=['category']] item['category'] = category # depends on [control=['if'], data=[]] item['replace']['Title'] = get_link(url, value=title) item['selected'] = False item['selected'] = uid in self.selected_services_uids # Add methods methods = obj.getMethods() if methods: links = map(lambda m: get_link(m.absolute_url(), value=m.Title(), css_class='link'), methods) item['replace']['Methods'] = ', '.join(links) # depends on [control=['if'], data=[]] else: item['methods'] = '' calculation = obj.getCalculation() if calculation: title = calculation.Title() url = calculation.absolute_url() item['Calculation'] = title item['replace']['Calculation'] = get_link(url, value=title) # depends on [control=['if'], data=[]] else: item['Calculation'] = '' # Icons after_icons = '' if obj.getAccredited(): after_icons += get_image('accredited.png', title=_('Accredited')) # depends on [control=['if'], data=[]] if obj.getAttachmentOption() == 'r': after_icons += get_image('attach_reqd.png', title=_('Attachment required')) # depends on [control=['if'], data=[]] if obj.getAttachmentOption() == 'n': after_icons += get_image('attach_no.png', title=_('Attachment not permitted')) # depends on [control=['if'], data=[]] if after_icons: item['after']['Title'] = after_icons # depends on [control=['if'], data=[]] return item
def _write_config_file(items, global_vars, template, project_name, out_dir, remotes): """Write configuration file, adding required top level attributes. """ config_dir = utils.safe_makedir(os.path.join(out_dir, "config")) out_config_file = os.path.join(config_dir, "%s.yaml" % project_name) out = {"fc_name": project_name, "upload": {"dir": "../final"}, "details": items} if remotes.get("base"): r_base = objectstore.parse_remote(remotes.get("base")) out["upload"]["method"] = r_base.store out["upload"]["bucket"] = r_base.bucket out["upload"]["folder"] = os.path.join(r_base.key, "final") if r_base.key else "final" if r_base.region: out["upload"]["region"] = r_base.region if global_vars: out["globals"] = global_vars for k, v in template.items(): if k not in ["details"]: out[k] = v if os.path.exists(out_config_file): shutil.move(out_config_file, out_config_file + ".bak%s" % datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")) with open(out_config_file, "w") as out_handle: yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False) return out_config_file
def function[_write_config_file, parameter[items, global_vars, template, project_name, out_dir, remotes]]: constant[Write configuration file, adding required top level attributes. ] variable[config_dir] assign[=] call[name[utils].safe_makedir, parameter[call[name[os].path.join, parameter[name[out_dir], constant[config]]]]] variable[out_config_file] assign[=] call[name[os].path.join, parameter[name[config_dir], binary_operation[constant[%s.yaml] <ast.Mod object at 0x7da2590d6920> name[project_name]]]] variable[out] assign[=] dictionary[[<ast.Constant object at 0x7da1b26acdf0>, <ast.Constant object at 0x7da1b26af370>, <ast.Constant object at 0x7da1b26ae7a0>], [<ast.Name object at 0x7da1b26ad120>, <ast.Dict object at 0x7da1b26ac6a0>, <ast.Name object at 0x7da1b26af520>]] if call[name[remotes].get, parameter[constant[base]]] begin[:] variable[r_base] assign[=] call[name[objectstore].parse_remote, parameter[call[name[remotes].get, parameter[constant[base]]]]] call[call[name[out]][constant[upload]]][constant[method]] assign[=] name[r_base].store call[call[name[out]][constant[upload]]][constant[bucket]] assign[=] name[r_base].bucket call[call[name[out]][constant[upload]]][constant[folder]] assign[=] <ast.IfExp object at 0x7da1b26ae650> if name[r_base].region begin[:] call[call[name[out]][constant[upload]]][constant[region]] assign[=] name[r_base].region if name[global_vars] begin[:] call[name[out]][constant[globals]] assign[=] name[global_vars] for taget[tuple[[<ast.Name object at 0x7da1b26ad180>, <ast.Name object at 0x7da1b26ae4a0>]]] in starred[call[name[template].items, parameter[]]] begin[:] if compare[name[k] <ast.NotIn object at 0x7da2590d7190> list[[<ast.Constant object at 0x7da1b26af280>]]] begin[:] call[name[out]][name[k]] assign[=] name[v] if call[name[os].path.exists, parameter[name[out_config_file]]] begin[:] call[name[shutil].move, parameter[name[out_config_file], binary_operation[name[out_config_file] + binary_operation[constant[.bak%s] <ast.Mod object at 0x7da2590d6920> call[call[name[datetime].datetime.now, parameter[]].strftime, parameter[constant[%Y-%m-%d-%H-%M-%S]]]]]]] with call[name[open], parameter[name[out_config_file], constant[w]]] begin[:] call[name[yaml].safe_dump, parameter[name[out], name[out_handle]]] return[name[out_config_file]]
keyword[def] identifier[_write_config_file] ( identifier[items] , identifier[global_vars] , identifier[template] , identifier[project_name] , identifier[out_dir] , identifier[remotes] ): literal[string] identifier[config_dir] = identifier[utils] . identifier[safe_makedir] ( identifier[os] . identifier[path] . identifier[join] ( identifier[out_dir] , literal[string] )) identifier[out_config_file] = identifier[os] . identifier[path] . identifier[join] ( identifier[config_dir] , literal[string] % identifier[project_name] ) identifier[out] ={ literal[string] : identifier[project_name] , literal[string] :{ literal[string] : literal[string] }, literal[string] : identifier[items] } keyword[if] identifier[remotes] . identifier[get] ( literal[string] ): identifier[r_base] = identifier[objectstore] . identifier[parse_remote] ( identifier[remotes] . identifier[get] ( literal[string] )) identifier[out] [ literal[string] ][ literal[string] ]= identifier[r_base] . identifier[store] identifier[out] [ literal[string] ][ literal[string] ]= identifier[r_base] . identifier[bucket] identifier[out] [ literal[string] ][ literal[string] ]= identifier[os] . identifier[path] . identifier[join] ( identifier[r_base] . identifier[key] , literal[string] ) keyword[if] identifier[r_base] . identifier[key] keyword[else] literal[string] keyword[if] identifier[r_base] . identifier[region] : identifier[out] [ literal[string] ][ literal[string] ]= identifier[r_base] . identifier[region] keyword[if] identifier[global_vars] : identifier[out] [ literal[string] ]= identifier[global_vars] keyword[for] identifier[k] , identifier[v] keyword[in] identifier[template] . identifier[items] (): keyword[if] identifier[k] keyword[not] keyword[in] [ literal[string] ]: identifier[out] [ identifier[k] ]= identifier[v] keyword[if] identifier[os] . identifier[path] . identifier[exists] ( identifier[out_config_file] ): identifier[shutil] . identifier[move] ( identifier[out_config_file] , identifier[out_config_file] + literal[string] % identifier[datetime] . identifier[datetime] . identifier[now] (). identifier[strftime] ( literal[string] )) keyword[with] identifier[open] ( identifier[out_config_file] , literal[string] ) keyword[as] identifier[out_handle] : identifier[yaml] . identifier[safe_dump] ( identifier[out] , identifier[out_handle] , identifier[default_flow_style] = keyword[False] , identifier[allow_unicode] = keyword[False] ) keyword[return] identifier[out_config_file]
def _write_config_file(items, global_vars, template, project_name, out_dir, remotes): """Write configuration file, adding required top level attributes. """ config_dir = utils.safe_makedir(os.path.join(out_dir, 'config')) out_config_file = os.path.join(config_dir, '%s.yaml' % project_name) out = {'fc_name': project_name, 'upload': {'dir': '../final'}, 'details': items} if remotes.get('base'): r_base = objectstore.parse_remote(remotes.get('base')) out['upload']['method'] = r_base.store out['upload']['bucket'] = r_base.bucket out['upload']['folder'] = os.path.join(r_base.key, 'final') if r_base.key else 'final' if r_base.region: out['upload']['region'] = r_base.region # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]] if global_vars: out['globals'] = global_vars # depends on [control=['if'], data=[]] for (k, v) in template.items(): if k not in ['details']: out[k] = v # depends on [control=['if'], data=['k']] # depends on [control=['for'], data=[]] if os.path.exists(out_config_file): shutil.move(out_config_file, out_config_file + '.bak%s' % datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')) # depends on [control=['if'], data=[]] with open(out_config_file, 'w') as out_handle: yaml.safe_dump(out, out_handle, default_flow_style=False, allow_unicode=False) # depends on [control=['with'], data=['out_handle']] return out_config_file
def load_token(cls, token, force=False): """Validate a secret link token (non-expiring + expiring).""" for algorithm in SUPPORTED_DIGEST_ALGORITHMS: s = SecretLinkSerializer(algorithm_name=algorithm) st = TimedSecretLinkSerializer(algorithm_name=algorithm) for serializer in (s, st): try: data = serializer.load_token(token, force=force) if data: return data except SignatureExpired: raise # signature was parsed and is expired except BadData: continue
def function[load_token, parameter[cls, token, force]]: constant[Validate a secret link token (non-expiring + expiring).] for taget[name[algorithm]] in starred[name[SUPPORTED_DIGEST_ALGORITHMS]] begin[:] variable[s] assign[=] call[name[SecretLinkSerializer], parameter[]] variable[st] assign[=] call[name[TimedSecretLinkSerializer], parameter[]] for taget[name[serializer]] in starred[tuple[[<ast.Name object at 0x7da20c990850>, <ast.Name object at 0x7da20c993a30>]]] begin[:] <ast.Try object at 0x7da20c992530>
keyword[def] identifier[load_token] ( identifier[cls] , identifier[token] , identifier[force] = keyword[False] ): literal[string] keyword[for] identifier[algorithm] keyword[in] identifier[SUPPORTED_DIGEST_ALGORITHMS] : identifier[s] = identifier[SecretLinkSerializer] ( identifier[algorithm_name] = identifier[algorithm] ) identifier[st] = identifier[TimedSecretLinkSerializer] ( identifier[algorithm_name] = identifier[algorithm] ) keyword[for] identifier[serializer] keyword[in] ( identifier[s] , identifier[st] ): keyword[try] : identifier[data] = identifier[serializer] . identifier[load_token] ( identifier[token] , identifier[force] = identifier[force] ) keyword[if] identifier[data] : keyword[return] identifier[data] keyword[except] identifier[SignatureExpired] : keyword[raise] keyword[except] identifier[BadData] : keyword[continue]
def load_token(cls, token, force=False): """Validate a secret link token (non-expiring + expiring).""" for algorithm in SUPPORTED_DIGEST_ALGORITHMS: s = SecretLinkSerializer(algorithm_name=algorithm) st = TimedSecretLinkSerializer(algorithm_name=algorithm) for serializer in (s, st): try: data = serializer.load_token(token, force=force) if data: return data # depends on [control=['if'], data=[]] # depends on [control=['try'], data=[]] except SignatureExpired: raise # signature was parsed and is expired # depends on [control=['except'], data=[]] except BadData: continue # depends on [control=['except'], data=[]] # depends on [control=['for'], data=['serializer']] # depends on [control=['for'], data=['algorithm']]
def load_case(adapter, case_obj, update=False): """Load a case into the database If the case already exists the function will exit. If the user want to load a case that is already in the database 'update' has to be 'True' Args: adapter (MongoAdapter): connection to the database case_obj (dict): case object to persist to the database update(bool): If existing case should be updated Returns: case_obj(dict): A dictionary with the builded case """ logger.info('Loading case {} into database'.format(case_obj['display_name'])) # Check if case exists in database existing_case = adapter.case(case_obj['_id']) if existing_case: if update: adapter.update_case(case_obj) else: raise IntegrityError("Case {0} already exists in database".format(case_obj['_id'])) else: adapter.add_case(case_obj) return case_obj
def function[load_case, parameter[adapter, case_obj, update]]: constant[Load a case into the database If the case already exists the function will exit. If the user want to load a case that is already in the database 'update' has to be 'True' Args: adapter (MongoAdapter): connection to the database case_obj (dict): case object to persist to the database update(bool): If existing case should be updated Returns: case_obj(dict): A dictionary with the builded case ] call[name[logger].info, parameter[call[constant[Loading case {} into database].format, parameter[call[name[case_obj]][constant[display_name]]]]]] variable[existing_case] assign[=] call[name[adapter].case, parameter[call[name[case_obj]][constant[_id]]]] if name[existing_case] begin[:] if name[update] begin[:] call[name[adapter].update_case, parameter[name[case_obj]]] return[name[case_obj]]
keyword[def] identifier[load_case] ( identifier[adapter] , identifier[case_obj] , identifier[update] = keyword[False] ): literal[string] identifier[logger] . identifier[info] ( literal[string] . identifier[format] ( identifier[case_obj] [ literal[string] ])) identifier[existing_case] = identifier[adapter] . identifier[case] ( identifier[case_obj] [ literal[string] ]) keyword[if] identifier[existing_case] : keyword[if] identifier[update] : identifier[adapter] . identifier[update_case] ( identifier[case_obj] ) keyword[else] : keyword[raise] identifier[IntegrityError] ( literal[string] . identifier[format] ( identifier[case_obj] [ literal[string] ])) keyword[else] : identifier[adapter] . identifier[add_case] ( identifier[case_obj] ) keyword[return] identifier[case_obj]
def load_case(adapter, case_obj, update=False): """Load a case into the database If the case already exists the function will exit. If the user want to load a case that is already in the database 'update' has to be 'True' Args: adapter (MongoAdapter): connection to the database case_obj (dict): case object to persist to the database update(bool): If existing case should be updated Returns: case_obj(dict): A dictionary with the builded case """ logger.info('Loading case {} into database'.format(case_obj['display_name'])) # Check if case exists in database existing_case = adapter.case(case_obj['_id']) if existing_case: if update: adapter.update_case(case_obj) # depends on [control=['if'], data=[]] else: raise IntegrityError('Case {0} already exists in database'.format(case_obj['_id'])) # depends on [control=['if'], data=[]] else: adapter.add_case(case_obj) return case_obj
def is_rate_matrix(K, tol=1e-10): """ True if K is a rate matrix Parameters ---------- K : numpy.ndarray matrix Matrix to check tol : float tolerance to check with Returns ------- Truth value : bool True, if K negated diagonal is positive and row sums up to zero. False, otherwise """ R = K - K.diagonal() off_diagonal_positive = np.allclose(R, abs(R), 0.0, atol=tol) row_sum = K.sum(axis=1) row_sum_eq_0 = np.allclose(row_sum, 0.0, atol=tol) return off_diagonal_positive and row_sum_eq_0
def function[is_rate_matrix, parameter[K, tol]]: constant[ True if K is a rate matrix Parameters ---------- K : numpy.ndarray matrix Matrix to check tol : float tolerance to check with Returns ------- Truth value : bool True, if K negated diagonal is positive and row sums up to zero. False, otherwise ] variable[R] assign[=] binary_operation[name[K] - call[name[K].diagonal, parameter[]]] variable[off_diagonal_positive] assign[=] call[name[np].allclose, parameter[name[R], call[name[abs], parameter[name[R]]], constant[0.0]]] variable[row_sum] assign[=] call[name[K].sum, parameter[]] variable[row_sum_eq_0] assign[=] call[name[np].allclose, parameter[name[row_sum], constant[0.0]]] return[<ast.BoolOp object at 0x7da1b26314e0>]
keyword[def] identifier[is_rate_matrix] ( identifier[K] , identifier[tol] = literal[int] ): literal[string] identifier[R] = identifier[K] - identifier[K] . identifier[diagonal] () identifier[off_diagonal_positive] = identifier[np] . identifier[allclose] ( identifier[R] , identifier[abs] ( identifier[R] ), literal[int] , identifier[atol] = identifier[tol] ) identifier[row_sum] = identifier[K] . identifier[sum] ( identifier[axis] = literal[int] ) identifier[row_sum_eq_0] = identifier[np] . identifier[allclose] ( identifier[row_sum] , literal[int] , identifier[atol] = identifier[tol] ) keyword[return] identifier[off_diagonal_positive] keyword[and] identifier[row_sum_eq_0]
def is_rate_matrix(K, tol=1e-10): """ True if K is a rate matrix Parameters ---------- K : numpy.ndarray matrix Matrix to check tol : float tolerance to check with Returns ------- Truth value : bool True, if K negated diagonal is positive and row sums up to zero. False, otherwise """ R = K - K.diagonal() off_diagonal_positive = np.allclose(R, abs(R), 0.0, atol=tol) row_sum = K.sum(axis=1) row_sum_eq_0 = np.allclose(row_sum, 0.0, atol=tol) return off_diagonal_positive and row_sum_eq_0
def field_metadata(self, well_row=0, well_column=0, field_row=0, field_column=0): """Get OME-XML metadata of given field. Parameters ---------- well_row : int Y well coordinate. Same as --V in files. well_column : int X well coordinate. Same as --U in files. field_row : int Y field coordinate. Same as --Y in files. field_column : int X field coordinate. Same as --X in files. Returns ------- lxml.objectify.ObjectifiedElement lxml object of OME-XML found in slide/chamber/field/metadata. """ def condition(path): attrs = attributes(path) return (attrs.u == well_column and attrs.v == well_row and attrs.x == field_column and attrs.y == field_row) field = [f for f in self.fields if condition(f)] if field: field = field[0] filename = _pattern(field, 'metadata', _image, extension='*.ome.xml') filename = glob(filename)[0] # resolve, assume found return objectify.parse(filename).getroot()
def function[field_metadata, parameter[self, well_row, well_column, field_row, field_column]]: constant[Get OME-XML metadata of given field. Parameters ---------- well_row : int Y well coordinate. Same as --V in files. well_column : int X well coordinate. Same as --U in files. field_row : int Y field coordinate. Same as --Y in files. field_column : int X field coordinate. Same as --X in files. Returns ------- lxml.objectify.ObjectifiedElement lxml object of OME-XML found in slide/chamber/field/metadata. ] def function[condition, parameter[path]]: variable[attrs] assign[=] call[name[attributes], parameter[name[path]]] return[<ast.BoolOp object at 0x7da1b0088ee0>] variable[field] assign[=] <ast.ListComp object at 0x7da1b008bca0> if name[field] begin[:] variable[field] assign[=] call[name[field]][constant[0]] variable[filename] assign[=] call[name[_pattern], parameter[name[field], constant[metadata], name[_image]]] variable[filename] assign[=] call[call[name[glob], parameter[name[filename]]]][constant[0]] return[call[call[name[objectify].parse, parameter[name[filename]]].getroot, parameter[]]]
keyword[def] identifier[field_metadata] ( identifier[self] , identifier[well_row] = literal[int] , identifier[well_column] = literal[int] , identifier[field_row] = literal[int] , identifier[field_column] = literal[int] ): literal[string] keyword[def] identifier[condition] ( identifier[path] ): identifier[attrs] = identifier[attributes] ( identifier[path] ) keyword[return] ( identifier[attrs] . identifier[u] == identifier[well_column] keyword[and] identifier[attrs] . identifier[v] == identifier[well_row] keyword[and] identifier[attrs] . identifier[x] == identifier[field_column] keyword[and] identifier[attrs] . identifier[y] == identifier[field_row] ) identifier[field] =[ identifier[f] keyword[for] identifier[f] keyword[in] identifier[self] . identifier[fields] keyword[if] identifier[condition] ( identifier[f] )] keyword[if] identifier[field] : identifier[field] = identifier[field] [ literal[int] ] identifier[filename] = identifier[_pattern] ( identifier[field] , literal[string] , identifier[_image] , identifier[extension] = literal[string] ) identifier[filename] = identifier[glob] ( identifier[filename] )[ literal[int] ] keyword[return] identifier[objectify] . identifier[parse] ( identifier[filename] ). identifier[getroot] ()
def field_metadata(self, well_row=0, well_column=0, field_row=0, field_column=0): """Get OME-XML metadata of given field. Parameters ---------- well_row : int Y well coordinate. Same as --V in files. well_column : int X well coordinate. Same as --U in files. field_row : int Y field coordinate. Same as --Y in files. field_column : int X field coordinate. Same as --X in files. Returns ------- lxml.objectify.ObjectifiedElement lxml object of OME-XML found in slide/chamber/field/metadata. """ def condition(path): attrs = attributes(path) return attrs.u == well_column and attrs.v == well_row and (attrs.x == field_column) and (attrs.y == field_row) field = [f for f in self.fields if condition(f)] if field: field = field[0] filename = _pattern(field, 'metadata', _image, extension='*.ome.xml') filename = glob(filename)[0] # resolve, assume found return objectify.parse(filename).getroot() # depends on [control=['if'], data=[]]
def feature_scp_generator(path): """ Return a generator over all feature matrices defined in a scp. """ scp_entries = textfile.read_key_value_lines(path, separator=' ') for utterance_id, rx_specifier in scp_entries.items(): yield utterance_id, KaldiWriter.read_float_matrix(rx_specifier)
def function[feature_scp_generator, parameter[path]]: constant[ Return a generator over all feature matrices defined in a scp. ] variable[scp_entries] assign[=] call[name[textfile].read_key_value_lines, parameter[name[path]]] for taget[tuple[[<ast.Name object at 0x7da1b0e27fa0>, <ast.Name object at 0x7da1b0e266b0>]]] in starred[call[name[scp_entries].items, parameter[]]] begin[:] <ast.Yield object at 0x7da1b0e27c40>
keyword[def] identifier[feature_scp_generator] ( identifier[path] ): literal[string] identifier[scp_entries] = identifier[textfile] . identifier[read_key_value_lines] ( identifier[path] , identifier[separator] = literal[string] ) keyword[for] identifier[utterance_id] , identifier[rx_specifier] keyword[in] identifier[scp_entries] . identifier[items] (): keyword[yield] identifier[utterance_id] , identifier[KaldiWriter] . identifier[read_float_matrix] ( identifier[rx_specifier] )
def feature_scp_generator(path): """ Return a generator over all feature matrices defined in a scp. """ scp_entries = textfile.read_key_value_lines(path, separator=' ') for (utterance_id, rx_specifier) in scp_entries.items(): yield (utterance_id, KaldiWriter.read_float_matrix(rx_specifier)) # depends on [control=['for'], data=[]]
def _add_token_to_document(self, token_string, token_attrs=None): """add a token node to this document graph""" token_feat = {self.ns+':token': token_string} if token_attrs: token_attrs.update(token_feat) else: token_attrs = token_feat token_id = 'token_{}'.format(self.token_count) self.add_node(token_id, layers={self.ns, self.ns+':token'}, attr_dict=token_attrs) self.token_count += 1 self.tokens.append(token_id) return token_id
def function[_add_token_to_document, parameter[self, token_string, token_attrs]]: constant[add a token node to this document graph] variable[token_feat] assign[=] dictionary[[<ast.BinOp object at 0x7da18dc9ab00>], [<ast.Name object at 0x7da18dc99e70>]] if name[token_attrs] begin[:] call[name[token_attrs].update, parameter[name[token_feat]]] variable[token_id] assign[=] call[constant[token_{}].format, parameter[name[self].token_count]] call[name[self].add_node, parameter[name[token_id]]] <ast.AugAssign object at 0x7da20c796170> call[name[self].tokens.append, parameter[name[token_id]]] return[name[token_id]]
keyword[def] identifier[_add_token_to_document] ( identifier[self] , identifier[token_string] , identifier[token_attrs] = keyword[None] ): literal[string] identifier[token_feat] ={ identifier[self] . identifier[ns] + literal[string] : identifier[token_string] } keyword[if] identifier[token_attrs] : identifier[token_attrs] . identifier[update] ( identifier[token_feat] ) keyword[else] : identifier[token_attrs] = identifier[token_feat] identifier[token_id] = literal[string] . identifier[format] ( identifier[self] . identifier[token_count] ) identifier[self] . identifier[add_node] ( identifier[token_id] , identifier[layers] ={ identifier[self] . identifier[ns] , identifier[self] . identifier[ns] + literal[string] }, identifier[attr_dict] = identifier[token_attrs] ) identifier[self] . identifier[token_count] += literal[int] identifier[self] . identifier[tokens] . identifier[append] ( identifier[token_id] ) keyword[return] identifier[token_id]
def _add_token_to_document(self, token_string, token_attrs=None): """add a token node to this document graph""" token_feat = {self.ns + ':token': token_string} if token_attrs: token_attrs.update(token_feat) # depends on [control=['if'], data=[]] else: token_attrs = token_feat token_id = 'token_{}'.format(self.token_count) self.add_node(token_id, layers={self.ns, self.ns + ':token'}, attr_dict=token_attrs) self.token_count += 1 self.tokens.append(token_id) return token_id
def to_string(interval, conv=repr, disj=' | ', sep=',', left_open='(', left_closed='[', right_open=')', right_closed=']', pinf='+inf', ninf='-inf'): """ Export given interval (or atomic interval) to string. :param interval: an Interval or AtomicInterval instance. :param conv: function that is used to represent a bound (default is `repr`). :param disj: string representing disjunctive operator (default is ' | '). :param sep: string representing bound separator (default is ','). :param left_open: string representing left open boundary (default is '('). :param left_closed: string representing left closed boundary (default is '['). :param right_open: string representing right open boundary (default is ')'). :param right_closed: string representing right closed boundary (default is ']'). :param pinf: string representing a positive infinity (default is '+inf'). :param ninf: string representing a negative infinity (default is '-inf'). :return: a string representation for given interval. """ interval = Interval(interval) if isinstance(interval, AtomicInterval) else interval if interval.is_empty(): return '{}{}'.format(left_open, right_open) def _convert(bound): if bound == inf: return pinf elif bound == -inf: return ninf else: return conv(bound) exported_intervals = [] for item in interval: left = left_open if item.left == OPEN else left_closed right = right_open if item.right == OPEN else right_closed lower = _convert(item.lower) upper = _convert(item.upper) if item.lower == item.upper: exported_intervals.append('{}{}{}'.format(left, lower, right)) else: exported_intervals.append('{}{}{}{}{}'.format(left, lower, sep, upper, right)) return disj.join(exported_intervals)
def function[to_string, parameter[interval, conv, disj, sep, left_open, left_closed, right_open, right_closed, pinf, ninf]]: constant[ Export given interval (or atomic interval) to string. :param interval: an Interval or AtomicInterval instance. :param conv: function that is used to represent a bound (default is `repr`). :param disj: string representing disjunctive operator (default is ' | '). :param sep: string representing bound separator (default is ','). :param left_open: string representing left open boundary (default is '('). :param left_closed: string representing left closed boundary (default is '['). :param right_open: string representing right open boundary (default is ')'). :param right_closed: string representing right closed boundary (default is ']'). :param pinf: string representing a positive infinity (default is '+inf'). :param ninf: string representing a negative infinity (default is '-inf'). :return: a string representation for given interval. ] variable[interval] assign[=] <ast.IfExp object at 0x7da1b11d7280> if call[name[interval].is_empty, parameter[]] begin[:] return[call[constant[{}{}].format, parameter[name[left_open], name[right_open]]]] def function[_convert, parameter[bound]]: if compare[name[bound] equal[==] name[inf]] begin[:] return[name[pinf]] variable[exported_intervals] assign[=] list[[]] for taget[name[item]] in starred[name[interval]] begin[:] variable[left] assign[=] <ast.IfExp object at 0x7da1b11d5870> variable[right] assign[=] <ast.IfExp object at 0x7da1b11d4790> variable[lower] assign[=] call[name[_convert], parameter[name[item].lower]] variable[upper] assign[=] call[name[_convert], parameter[name[item].upper]] if compare[name[item].lower equal[==] name[item].upper] begin[:] call[name[exported_intervals].append, parameter[call[constant[{}{}{}].format, parameter[name[left], name[lower], name[right]]]]] return[call[name[disj].join, parameter[name[exported_intervals]]]]
keyword[def] identifier[to_string] ( identifier[interval] , identifier[conv] = identifier[repr] , identifier[disj] = literal[string] , identifier[sep] = literal[string] , identifier[left_open] = literal[string] , identifier[left_closed] = literal[string] , identifier[right_open] = literal[string] , identifier[right_closed] = literal[string] , identifier[pinf] = literal[string] , identifier[ninf] = literal[string] ): literal[string] identifier[interval] = identifier[Interval] ( identifier[interval] ) keyword[if] identifier[isinstance] ( identifier[interval] , identifier[AtomicInterval] ) keyword[else] identifier[interval] keyword[if] identifier[interval] . identifier[is_empty] (): keyword[return] literal[string] . identifier[format] ( identifier[left_open] , identifier[right_open] ) keyword[def] identifier[_convert] ( identifier[bound] ): keyword[if] identifier[bound] == identifier[inf] : keyword[return] identifier[pinf] keyword[elif] identifier[bound] ==- identifier[inf] : keyword[return] identifier[ninf] keyword[else] : keyword[return] identifier[conv] ( identifier[bound] ) identifier[exported_intervals] =[] keyword[for] identifier[item] keyword[in] identifier[interval] : identifier[left] = identifier[left_open] keyword[if] identifier[item] . identifier[left] == identifier[OPEN] keyword[else] identifier[left_closed] identifier[right] = identifier[right_open] keyword[if] identifier[item] . identifier[right] == identifier[OPEN] keyword[else] identifier[right_closed] identifier[lower] = identifier[_convert] ( identifier[item] . identifier[lower] ) identifier[upper] = identifier[_convert] ( identifier[item] . identifier[upper] ) keyword[if] identifier[item] . identifier[lower] == identifier[item] . identifier[upper] : identifier[exported_intervals] . identifier[append] ( literal[string] . identifier[format] ( identifier[left] , identifier[lower] , identifier[right] )) keyword[else] : identifier[exported_intervals] . identifier[append] ( literal[string] . identifier[format] ( identifier[left] , identifier[lower] , identifier[sep] , identifier[upper] , identifier[right] )) keyword[return] identifier[disj] . identifier[join] ( identifier[exported_intervals] )
def to_string(interval, conv=repr, disj=' | ', sep=',', left_open='(', left_closed='[', right_open=')', right_closed=']', pinf='+inf', ninf='-inf'): """ Export given interval (or atomic interval) to string. :param interval: an Interval or AtomicInterval instance. :param conv: function that is used to represent a bound (default is `repr`). :param disj: string representing disjunctive operator (default is ' | '). :param sep: string representing bound separator (default is ','). :param left_open: string representing left open boundary (default is '('). :param left_closed: string representing left closed boundary (default is '['). :param right_open: string representing right open boundary (default is ')'). :param right_closed: string representing right closed boundary (default is ']'). :param pinf: string representing a positive infinity (default is '+inf'). :param ninf: string representing a negative infinity (default is '-inf'). :return: a string representation for given interval. """ interval = Interval(interval) if isinstance(interval, AtomicInterval) else interval if interval.is_empty(): return '{}{}'.format(left_open, right_open) # depends on [control=['if'], data=[]] def _convert(bound): if bound == inf: return pinf # depends on [control=['if'], data=[]] elif bound == -inf: return ninf # depends on [control=['if'], data=[]] else: return conv(bound) exported_intervals = [] for item in interval: left = left_open if item.left == OPEN else left_closed right = right_open if item.right == OPEN else right_closed lower = _convert(item.lower) upper = _convert(item.upper) if item.lower == item.upper: exported_intervals.append('{}{}{}'.format(left, lower, right)) # depends on [control=['if'], data=[]] else: exported_intervals.append('{}{}{}{}{}'.format(left, lower, sep, upper, right)) # depends on [control=['for'], data=['item']] return disj.join(exported_intervals)
def _get_flavor_ref(self, flavor): """ Flavors are odd in that the API expects an href link, not an ID, as with nearly every other resource. This method takes either a CloudDatabaseFlavor object, a flavor ID, a RAM size, or a flavor name, and uses that to determine the appropriate href. """ flavor_obj = None if isinstance(flavor, CloudDatabaseFlavor): flavor_obj = flavor elif isinstance(flavor, int): # They passed an ID or a size try: flavor_obj = self.get_flavor(flavor) except exc.NotFound: # Must be either a size or bad ID, which will # be handled below pass if flavor_obj is None: # Try flavor name flavors = self.list_flavors() try: flavor_obj = [flav for flav in flavors if flav.name == flavor][0] except IndexError: # No such name; try matching RAM try: flavor_obj = [flav for flav in flavors if flav.ram == flavor][0] except IndexError: raise exc.FlavorNotFound("Could not determine flavor from " "'%s'." % flavor) # OK, we have a Flavor object. Get the href href = [link["href"] for link in flavor_obj.links if link["rel"] == "self"][0] return href
def function[_get_flavor_ref, parameter[self, flavor]]: constant[ Flavors are odd in that the API expects an href link, not an ID, as with nearly every other resource. This method takes either a CloudDatabaseFlavor object, a flavor ID, a RAM size, or a flavor name, and uses that to determine the appropriate href. ] variable[flavor_obj] assign[=] constant[None] if call[name[isinstance], parameter[name[flavor], name[CloudDatabaseFlavor]]] begin[:] variable[flavor_obj] assign[=] name[flavor] if compare[name[flavor_obj] is constant[None]] begin[:] variable[flavors] assign[=] call[name[self].list_flavors, parameter[]] <ast.Try object at 0x7da1b0558d00> variable[href] assign[=] call[<ast.ListComp object at 0x7da1b0558400>][constant[0]] return[name[href]]
keyword[def] identifier[_get_flavor_ref] ( identifier[self] , identifier[flavor] ): literal[string] identifier[flavor_obj] = keyword[None] keyword[if] identifier[isinstance] ( identifier[flavor] , identifier[CloudDatabaseFlavor] ): identifier[flavor_obj] = identifier[flavor] keyword[elif] identifier[isinstance] ( identifier[flavor] , identifier[int] ): keyword[try] : identifier[flavor_obj] = identifier[self] . identifier[get_flavor] ( identifier[flavor] ) keyword[except] identifier[exc] . identifier[NotFound] : keyword[pass] keyword[if] identifier[flavor_obj] keyword[is] keyword[None] : identifier[flavors] = identifier[self] . identifier[list_flavors] () keyword[try] : identifier[flavor_obj] =[ identifier[flav] keyword[for] identifier[flav] keyword[in] identifier[flavors] keyword[if] identifier[flav] . identifier[name] == identifier[flavor] ][ literal[int] ] keyword[except] identifier[IndexError] : keyword[try] : identifier[flavor_obj] =[ identifier[flav] keyword[for] identifier[flav] keyword[in] identifier[flavors] keyword[if] identifier[flav] . identifier[ram] == identifier[flavor] ][ literal[int] ] keyword[except] identifier[IndexError] : keyword[raise] identifier[exc] . identifier[FlavorNotFound] ( literal[string] literal[string] % identifier[flavor] ) identifier[href] =[ identifier[link] [ literal[string] ] keyword[for] identifier[link] keyword[in] identifier[flavor_obj] . identifier[links] keyword[if] identifier[link] [ literal[string] ]== literal[string] ][ literal[int] ] keyword[return] identifier[href]
def _get_flavor_ref(self, flavor): """ Flavors are odd in that the API expects an href link, not an ID, as with nearly every other resource. This method takes either a CloudDatabaseFlavor object, a flavor ID, a RAM size, or a flavor name, and uses that to determine the appropriate href. """ flavor_obj = None if isinstance(flavor, CloudDatabaseFlavor): flavor_obj = flavor # depends on [control=['if'], data=[]] elif isinstance(flavor, int): # They passed an ID or a size try: flavor_obj = self.get_flavor(flavor) # depends on [control=['try'], data=[]] except exc.NotFound: # Must be either a size or bad ID, which will # be handled below pass # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] if flavor_obj is None: # Try flavor name flavors = self.list_flavors() try: flavor_obj = [flav for flav in flavors if flav.name == flavor][0] # depends on [control=['try'], data=[]] except IndexError: # No such name; try matching RAM try: flavor_obj = [flav for flav in flavors if flav.ram == flavor][0] # depends on [control=['try'], data=[]] except IndexError: raise exc.FlavorNotFound("Could not determine flavor from '%s'." % flavor) # depends on [control=['except'], data=[]] # depends on [control=['except'], data=[]] # depends on [control=['if'], data=['flavor_obj']] # OK, we have a Flavor object. Get the href href = [link['href'] for link in flavor_obj.links if link['rel'] == 'self'][0] return href
def booleanise(b): """Normalise a 'stringified' Boolean to a proper Python Boolean. ElasticSearch has a habit of returning "true" and "false" in its JSON responses when it should be returning `true` and `false`. If `b` looks like a stringified Boolean true, return True. If `b` looks like a stringified Boolean false, return False. If we don't know what `b` is supposed to represent, return it back to the caller. """ s = str(b) if s.lower() == "true": return True if s.lower() == "false": return False return b
def function[booleanise, parameter[b]]: constant[Normalise a 'stringified' Boolean to a proper Python Boolean. ElasticSearch has a habit of returning "true" and "false" in its JSON responses when it should be returning `true` and `false`. If `b` looks like a stringified Boolean true, return True. If `b` looks like a stringified Boolean false, return False. If we don't know what `b` is supposed to represent, return it back to the caller. ] variable[s] assign[=] call[name[str], parameter[name[b]]] if compare[call[name[s].lower, parameter[]] equal[==] constant[true]] begin[:] return[constant[True]] if compare[call[name[s].lower, parameter[]] equal[==] constant[false]] begin[:] return[constant[False]] return[name[b]]
keyword[def] identifier[booleanise] ( identifier[b] ): literal[string] identifier[s] = identifier[str] ( identifier[b] ) keyword[if] identifier[s] . identifier[lower] ()== literal[string] : keyword[return] keyword[True] keyword[if] identifier[s] . identifier[lower] ()== literal[string] : keyword[return] keyword[False] keyword[return] identifier[b]
def booleanise(b): """Normalise a 'stringified' Boolean to a proper Python Boolean. ElasticSearch has a habit of returning "true" and "false" in its JSON responses when it should be returning `true` and `false`. If `b` looks like a stringified Boolean true, return True. If `b` looks like a stringified Boolean false, return False. If we don't know what `b` is supposed to represent, return it back to the caller. """ s = str(b) if s.lower() == 'true': return True # depends on [control=['if'], data=[]] if s.lower() == 'false': return False # depends on [control=['if'], data=[]] return b
def get_component_id_list(self, system_id): '''get list of component IDs with parameters for a given system ID''' ret = [] for (s,c) in self.mpstate.mav_param_by_sysid.keys(): if s == system_id: ret.append(c) return ret
def function[get_component_id_list, parameter[self, system_id]]: constant[get list of component IDs with parameters for a given system ID] variable[ret] assign[=] list[[]] for taget[tuple[[<ast.Name object at 0x7da1b16a6bf0>, <ast.Name object at 0x7da1b16a6bc0>]]] in starred[call[name[self].mpstate.mav_param_by_sysid.keys, parameter[]]] begin[:] if compare[name[s] equal[==] name[system_id]] begin[:] call[name[ret].append, parameter[name[c]]] return[name[ret]]
keyword[def] identifier[get_component_id_list] ( identifier[self] , identifier[system_id] ): literal[string] identifier[ret] =[] keyword[for] ( identifier[s] , identifier[c] ) keyword[in] identifier[self] . identifier[mpstate] . identifier[mav_param_by_sysid] . identifier[keys] (): keyword[if] identifier[s] == identifier[system_id] : identifier[ret] . identifier[append] ( identifier[c] ) keyword[return] identifier[ret]
def get_component_id_list(self, system_id): """get list of component IDs with parameters for a given system ID""" ret = [] for (s, c) in self.mpstate.mav_param_by_sysid.keys(): if s == system_id: ret.append(c) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=[]] return ret
def get_tags(ctx, archive_name): ''' Print tags assigned to an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(' '.join(var.get_tags()), nl=False) print('')
def function[get_tags, parameter[ctx, archive_name]]: constant[ Print tags assigned to an archive ] call[name[_generate_api], parameter[name[ctx]]] variable[var] assign[=] call[name[ctx].obj.api.get_archive, parameter[name[archive_name]]] call[name[click].echo, parameter[call[constant[ ].join, parameter[call[name[var].get_tags, parameter[]]]]]] call[name[print], parameter[constant[]]]
keyword[def] identifier[get_tags] ( identifier[ctx] , identifier[archive_name] ): literal[string] identifier[_generate_api] ( identifier[ctx] ) identifier[var] = identifier[ctx] . identifier[obj] . identifier[api] . identifier[get_archive] ( identifier[archive_name] ) identifier[click] . identifier[echo] ( literal[string] . identifier[join] ( identifier[var] . identifier[get_tags] ()), identifier[nl] = keyword[False] ) identifier[print] ( literal[string] )
def get_tags(ctx, archive_name): """ Print tags assigned to an archive """ _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) click.echo(' '.join(var.get_tags()), nl=False) print('')
def identity(self): """Get the daemon identity This will return an object containing some properties: - alignak: the Alignak instance name - version: the Alignak version - type: the daemon type - name: the daemon name :return: daemon identity :rtype: dict """ res = self.app.get_id() res.update({"start_time": self.start_time}) res.update({"running_id": self.running_id}) return res
def function[identity, parameter[self]]: constant[Get the daemon identity This will return an object containing some properties: - alignak: the Alignak instance name - version: the Alignak version - type: the daemon type - name: the daemon name :return: daemon identity :rtype: dict ] variable[res] assign[=] call[name[self].app.get_id, parameter[]] call[name[res].update, parameter[dictionary[[<ast.Constant object at 0x7da18f58cfd0>], [<ast.Attribute object at 0x7da18f58eec0>]]]] call[name[res].update, parameter[dictionary[[<ast.Constant object at 0x7da18f58c310>], [<ast.Attribute object at 0x7da18f58f3d0>]]]] return[name[res]]
keyword[def] identifier[identity] ( identifier[self] ): literal[string] identifier[res] = identifier[self] . identifier[app] . identifier[get_id] () identifier[res] . identifier[update] ({ literal[string] : identifier[self] . identifier[start_time] }) identifier[res] . identifier[update] ({ literal[string] : identifier[self] . identifier[running_id] }) keyword[return] identifier[res]
def identity(self): """Get the daemon identity This will return an object containing some properties: - alignak: the Alignak instance name - version: the Alignak version - type: the daemon type - name: the daemon name :return: daemon identity :rtype: dict """ res = self.app.get_id() res.update({'start_time': self.start_time}) res.update({'running_id': self.running_id}) return res
def rename_pool(service, old_name, new_name): """ Rename a Ceph pool from old_name to new_name :param service: six.string_types. The Ceph user name to run the command under :param old_name: six.string_types :param new_name: six.string_types :return: None """ validator(value=old_name, valid_type=six.string_types) validator(value=new_name, valid_type=six.string_types) cmd = ['ceph', '--id', service, 'osd', 'pool', 'rename', old_name, new_name] check_call(cmd)
def function[rename_pool, parameter[service, old_name, new_name]]: constant[ Rename a Ceph pool from old_name to new_name :param service: six.string_types. The Ceph user name to run the command under :param old_name: six.string_types :param new_name: six.string_types :return: None ] call[name[validator], parameter[]] call[name[validator], parameter[]] variable[cmd] assign[=] list[[<ast.Constant object at 0x7da18fe91b10>, <ast.Constant object at 0x7da18fe913c0>, <ast.Name object at 0x7da18fe90df0>, <ast.Constant object at 0x7da18fe92a40>, <ast.Constant object at 0x7da18fe91720>, <ast.Constant object at 0x7da18fe918d0>, <ast.Name object at 0x7da18fe92860>, <ast.Name object at 0x7da18fe917e0>]] call[name[check_call], parameter[name[cmd]]]
keyword[def] identifier[rename_pool] ( identifier[service] , identifier[old_name] , identifier[new_name] ): literal[string] identifier[validator] ( identifier[value] = identifier[old_name] , identifier[valid_type] = identifier[six] . identifier[string_types] ) identifier[validator] ( identifier[value] = identifier[new_name] , identifier[valid_type] = identifier[six] . identifier[string_types] ) identifier[cmd] =[ literal[string] , literal[string] , identifier[service] , literal[string] , literal[string] , literal[string] , identifier[old_name] , identifier[new_name] ] identifier[check_call] ( identifier[cmd] )
def rename_pool(service, old_name, new_name): """ Rename a Ceph pool from old_name to new_name :param service: six.string_types. The Ceph user name to run the command under :param old_name: six.string_types :param new_name: six.string_types :return: None """ validator(value=old_name, valid_type=six.string_types) validator(value=new_name, valid_type=six.string_types) cmd = ['ceph', '--id', service, 'osd', 'pool', 'rename', old_name, new_name] check_call(cmd)
def setup_fields(attrs): """ Collect all fields declared on the class and remove them from attrs """ fields = {} iterator = list(attrs.items()) for key, value in iterator: if not isinstance(value, Field): continue fields[key] = value del attrs[key] return fields
def function[setup_fields, parameter[attrs]]: constant[ Collect all fields declared on the class and remove them from attrs ] variable[fields] assign[=] dictionary[[], []] variable[iterator] assign[=] call[name[list], parameter[call[name[attrs].items, parameter[]]]] for taget[tuple[[<ast.Name object at 0x7da1b1a8ebf0>, <ast.Name object at 0x7da1b1a8e110>]]] in starred[name[iterator]] begin[:] if <ast.UnaryOp object at 0x7da1b1a8ca00> begin[:] continue call[name[fields]][name[key]] assign[=] name[value] <ast.Delete object at 0x7da1b1a8dba0> return[name[fields]]
keyword[def] identifier[setup_fields] ( identifier[attrs] ): literal[string] identifier[fields] ={} identifier[iterator] = identifier[list] ( identifier[attrs] . identifier[items] ()) keyword[for] identifier[key] , identifier[value] keyword[in] identifier[iterator] : keyword[if] keyword[not] identifier[isinstance] ( identifier[value] , identifier[Field] ): keyword[continue] identifier[fields] [ identifier[key] ]= identifier[value] keyword[del] identifier[attrs] [ identifier[key] ] keyword[return] identifier[fields]
def setup_fields(attrs): """ Collect all fields declared on the class and remove them from attrs """ fields = {} iterator = list(attrs.items()) for (key, value) in iterator: if not isinstance(value, Field): continue # depends on [control=['if'], data=[]] fields[key] = value del attrs[key] # depends on [control=['for'], data=[]] return fields
def parse_property_array(self, tup_tree): """ :: <!ELEMENT PROPERTY.ARRAY (QUALIFIER*, VALUE.ARRAY?)> <!ATTLIST PROPERTY.ARRAY %CIMName; %CIMType; #REQUIRED %ArraySize; %ClassOrigin; %Propagated; %EmbeddedObject; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'PROPERTY.ARRAY', ('NAME', 'TYPE'), ('CLASSORIGIN', 'PROPAGATED', 'ARRAYSIZE', 'EmbeddedObject', 'EMBEDDEDOBJECT', 'xml:lang'), ('QUALIFIER', 'VALUE.ARRAY')) # The 'xml:lang' attribute is tolerated but ignored. values = self.unpack_value(tup_tree) attrl = attrs(tup_tree) qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) array_size = attrl.get('ARRAYSIZE', None) if array_size is not None: # Issue #1044: Clarify if hex support is needed. array_size = int(array_size) embedded_object = False if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: try: embedded_object = attrl['EmbeddedObject'] except KeyError: embedded_object = attrl['EMBEDDEDOBJECT'] if embedded_object: values = self.parse_embeddedObject(values) obj = CIMProperty(attrl['NAME'], values, type=attrl['TYPE'], is_array=True, array_size=array_size, class_origin=attrl.get('CLASSORIGIN', None), propagated=self.unpack_boolean( attrl.get('PROPAGATED', 'false')), qualifiers=qualifiers, embedded_object=embedded_object) return obj
def function[parse_property_array, parameter[self, tup_tree]]: constant[ :: <!ELEMENT PROPERTY.ARRAY (QUALIFIER*, VALUE.ARRAY?)> <!ATTLIST PROPERTY.ARRAY %CIMName; %CIMType; #REQUIRED %ArraySize; %ClassOrigin; %Propagated; %EmbeddedObject; xml:lang NMTOKEN #IMPLIED> ] call[name[self].check_node, parameter[name[tup_tree], constant[PROPERTY.ARRAY], tuple[[<ast.Constant object at 0x7da18bccbaf0>, <ast.Constant object at 0x7da18bccacb0>]], tuple[[<ast.Constant object at 0x7da18bccbe80>, <ast.Constant object at 0x7da18bccb970>, <ast.Constant object at 0x7da18bccb160>, <ast.Constant object at 0x7da18bcc8f10>, <ast.Constant object at 0x7da18bccb730>, <ast.Constant object at 0x7da18bccaa40>]], tuple[[<ast.Constant object at 0x7da18bcc8070>, <ast.Constant object at 0x7da18bccb6d0>]]]] variable[values] assign[=] call[name[self].unpack_value, parameter[name[tup_tree]]] variable[attrl] assign[=] call[name[attrs], parameter[name[tup_tree]]] variable[qualifiers] assign[=] call[name[self].list_of_matching, parameter[name[tup_tree], tuple[[<ast.Constant object at 0x7da18bcc99c0>]]]] variable[array_size] assign[=] call[name[attrl].get, parameter[constant[ARRAYSIZE], constant[None]]] if compare[name[array_size] is_not constant[None]] begin[:] variable[array_size] assign[=] call[name[int], parameter[name[array_size]]] variable[embedded_object] assign[=] constant[False] if <ast.BoolOp object at 0x7da18bccbdf0> begin[:] <ast.Try object at 0x7da18bcc8a00> if name[embedded_object] begin[:] variable[values] assign[=] call[name[self].parse_embeddedObject, parameter[name[values]]] variable[obj] assign[=] call[name[CIMProperty], parameter[call[name[attrl]][constant[NAME]], name[values]]] return[name[obj]]
keyword[def] identifier[parse_property_array] ( identifier[self] , identifier[tup_tree] ): literal[string] identifier[self] . identifier[check_node] ( identifier[tup_tree] , literal[string] ,( literal[string] , literal[string] ), ( literal[string] , literal[string] , literal[string] , literal[string] , literal[string] , literal[string] ), ( literal[string] , literal[string] )) identifier[values] = identifier[self] . identifier[unpack_value] ( identifier[tup_tree] ) identifier[attrl] = identifier[attrs] ( identifier[tup_tree] ) identifier[qualifiers] = identifier[self] . identifier[list_of_matching] ( identifier[tup_tree] ,( literal[string] ,)) identifier[array_size] = identifier[attrl] . identifier[get] ( literal[string] , keyword[None] ) keyword[if] identifier[array_size] keyword[is] keyword[not] keyword[None] : identifier[array_size] = identifier[int] ( identifier[array_size] ) identifier[embedded_object] = keyword[False] keyword[if] literal[string] keyword[in] identifier[attrl] keyword[or] literal[string] keyword[in] identifier[attrl] : keyword[try] : identifier[embedded_object] = identifier[attrl] [ literal[string] ] keyword[except] identifier[KeyError] : identifier[embedded_object] = identifier[attrl] [ literal[string] ] keyword[if] identifier[embedded_object] : identifier[values] = identifier[self] . identifier[parse_embeddedObject] ( identifier[values] ) identifier[obj] = identifier[CIMProperty] ( identifier[attrl] [ literal[string] ], identifier[values] , identifier[type] = identifier[attrl] [ literal[string] ], identifier[is_array] = keyword[True] , identifier[array_size] = identifier[array_size] , identifier[class_origin] = identifier[attrl] . identifier[get] ( literal[string] , keyword[None] ), identifier[propagated] = identifier[self] . identifier[unpack_boolean] ( identifier[attrl] . identifier[get] ( literal[string] , literal[string] )), identifier[qualifiers] = identifier[qualifiers] , identifier[embedded_object] = identifier[embedded_object] ) keyword[return] identifier[obj]
def parse_property_array(self, tup_tree): """ :: <!ELEMENT PROPERTY.ARRAY (QUALIFIER*, VALUE.ARRAY?)> <!ATTLIST PROPERTY.ARRAY %CIMName; %CIMType; #REQUIRED %ArraySize; %ClassOrigin; %Propagated; %EmbeddedObject; xml:lang NMTOKEN #IMPLIED> """ self.check_node(tup_tree, 'PROPERTY.ARRAY', ('NAME', 'TYPE'), ('CLASSORIGIN', 'PROPAGATED', 'ARRAYSIZE', 'EmbeddedObject', 'EMBEDDEDOBJECT', 'xml:lang'), ('QUALIFIER', 'VALUE.ARRAY')) # The 'xml:lang' attribute is tolerated but ignored. values = self.unpack_value(tup_tree) attrl = attrs(tup_tree) qualifiers = self.list_of_matching(tup_tree, ('QUALIFIER',)) array_size = attrl.get('ARRAYSIZE', None) if array_size is not None: # Issue #1044: Clarify if hex support is needed. array_size = int(array_size) # depends on [control=['if'], data=['array_size']] embedded_object = False if 'EmbeddedObject' in attrl or 'EMBEDDEDOBJECT' in attrl: try: embedded_object = attrl['EmbeddedObject'] # depends on [control=['try'], data=[]] except KeyError: embedded_object = attrl['EMBEDDEDOBJECT'] # depends on [control=['except'], data=[]] # depends on [control=['if'], data=[]] if embedded_object: values = self.parse_embeddedObject(values) # depends on [control=['if'], data=[]] obj = CIMProperty(attrl['NAME'], values, type=attrl['TYPE'], is_array=True, array_size=array_size, class_origin=attrl.get('CLASSORIGIN', None), propagated=self.unpack_boolean(attrl.get('PROPAGATED', 'false')), qualifiers=qualifiers, embedded_object=embedded_object) return obj
def compare_basis_files(file_path_1, file_path_2, file_type_1=None, file_type_2=None, uncontract_general=False): '''Compare two files containing formatted basis sets''' bs1 = read_formatted_basis(file_path_1, file_type_1) bs2 = read_formatted_basis(file_path_2, file_type_2) return basis_comparison_report(bs1, bs2, uncontract_general)
def function[compare_basis_files, parameter[file_path_1, file_path_2, file_type_1, file_type_2, uncontract_general]]: constant[Compare two files containing formatted basis sets] variable[bs1] assign[=] call[name[read_formatted_basis], parameter[name[file_path_1], name[file_type_1]]] variable[bs2] assign[=] call[name[read_formatted_basis], parameter[name[file_path_2], name[file_type_2]]] return[call[name[basis_comparison_report], parameter[name[bs1], name[bs2], name[uncontract_general]]]]
keyword[def] identifier[compare_basis_files] ( identifier[file_path_1] , identifier[file_path_2] , identifier[file_type_1] = keyword[None] , identifier[file_type_2] = keyword[None] , identifier[uncontract_general] = keyword[False] ): literal[string] identifier[bs1] = identifier[read_formatted_basis] ( identifier[file_path_1] , identifier[file_type_1] ) identifier[bs2] = identifier[read_formatted_basis] ( identifier[file_path_2] , identifier[file_type_2] ) keyword[return] identifier[basis_comparison_report] ( identifier[bs1] , identifier[bs2] , identifier[uncontract_general] )
def compare_basis_files(file_path_1, file_path_2, file_type_1=None, file_type_2=None, uncontract_general=False): """Compare two files containing formatted basis sets""" bs1 = read_formatted_basis(file_path_1, file_type_1) bs2 = read_formatted_basis(file_path_2, file_type_2) return basis_comparison_report(bs1, bs2, uncontract_general)
def insert(self, index, value): """ Insert object before index. :param int index: index to insert in :param string value: path to insert """ self._list.insert(index, value) self._sync()
def function[insert, parameter[self, index, value]]: constant[ Insert object before index. :param int index: index to insert in :param string value: path to insert ] call[name[self]._list.insert, parameter[name[index], name[value]]] call[name[self]._sync, parameter[]]
keyword[def] identifier[insert] ( identifier[self] , identifier[index] , identifier[value] ): literal[string] identifier[self] . identifier[_list] . identifier[insert] ( identifier[index] , identifier[value] ) identifier[self] . identifier[_sync] ()
def insert(self, index, value): """ Insert object before index. :param int index: index to insert in :param string value: path to insert """ self._list.insert(index, value) self._sync()
def mail_sent_contains_html(self): """ Test that an email contains the HTML (assert HTML in) in the multiline as one of its MIME alternatives. The HTML is normalised by passing through Django's :func:`django.test.html.parse_html`. Example: .. code-block:: gherkin And I have sent an email with the following HTML alternative: \"\"\" <p><strong>Name:</strong> Sir Panda</p> <p><strong>Phone:</strong> 0400000000</p> <p><strong>Email:</strong> sir.panda@pand.as</p> \"\"\" """ for email in mail.outbox: try: html = next(content for content, mime in email.alternatives if mime == 'text/html') dom1 = parse_html(html) dom2 = parse_html(self.multiline) assert_in(dom1, dom2) except AssertionError as exc: print("Email did not match", exc) # we intentionally eat the exception continue return True raise AssertionError("No email contained the HTML")
def function[mail_sent_contains_html, parameter[self]]: constant[ Test that an email contains the HTML (assert HTML in) in the multiline as one of its MIME alternatives. The HTML is normalised by passing through Django's :func:`django.test.html.parse_html`. Example: .. code-block:: gherkin And I have sent an email with the following HTML alternative: """ <p><strong>Name:</strong> Sir Panda</p> <p><strong>Phone:</strong> 0400000000</p> <p><strong>Email:</strong> sir.panda@pand.as</p> """ ] for taget[name[email]] in starred[name[mail].outbox] begin[:] <ast.Try object at 0x7da1b1ada980> return[constant[True]] <ast.Raise object at 0x7da1b1ada380>
keyword[def] identifier[mail_sent_contains_html] ( identifier[self] ): literal[string] keyword[for] identifier[email] keyword[in] identifier[mail] . identifier[outbox] : keyword[try] : identifier[html] = identifier[next] ( identifier[content] keyword[for] identifier[content] , identifier[mime] keyword[in] identifier[email] . identifier[alternatives] keyword[if] identifier[mime] == literal[string] ) identifier[dom1] = identifier[parse_html] ( identifier[html] ) identifier[dom2] = identifier[parse_html] ( identifier[self] . identifier[multiline] ) identifier[assert_in] ( identifier[dom1] , identifier[dom2] ) keyword[except] identifier[AssertionError] keyword[as] identifier[exc] : identifier[print] ( literal[string] , identifier[exc] ) keyword[continue] keyword[return] keyword[True] keyword[raise] identifier[AssertionError] ( literal[string] )
def mail_sent_contains_html(self): ''' Test that an email contains the HTML (assert HTML in) in the multiline as one of its MIME alternatives. The HTML is normalised by passing through Django's :func:`django.test.html.parse_html`. Example: .. code-block:: gherkin And I have sent an email with the following HTML alternative: """ <p><strong>Name:</strong> Sir Panda</p> <p><strong>Phone:</strong> 0400000000</p> <p><strong>Email:</strong> sir.panda@pand.as</p> """ ''' for email in mail.outbox: try: html = next((content for (content, mime) in email.alternatives if mime == 'text/html')) dom1 = parse_html(html) dom2 = parse_html(self.multiline) assert_in(dom1, dom2) # depends on [control=['try'], data=[]] except AssertionError as exc: print('Email did not match', exc) # we intentionally eat the exception continue # depends on [control=['except'], data=['exc']] return True # depends on [control=['for'], data=['email']] raise AssertionError('No email contained the HTML')
def dr( self, cell_lengths ): """ Particle displacement vector for this jump Args: cell_lengths (np.array(x,y,z)): Cell lengths for the orthogonal simulation cell. Returns (np.array(x,y,z)): dr """ half_cell_lengths = cell_lengths / 2.0 this_dr = self.final_site.r - self.initial_site.r for i in range( 3 ): if this_dr[ i ] > half_cell_lengths[ i ]: this_dr[ i ] -= cell_lengths[ i ] if this_dr[ i ] < -half_cell_lengths[ i ]: this_dr[ i ] += cell_lengths[ i ] return this_dr
def function[dr, parameter[self, cell_lengths]]: constant[ Particle displacement vector for this jump Args: cell_lengths (np.array(x,y,z)): Cell lengths for the orthogonal simulation cell. Returns (np.array(x,y,z)): dr ] variable[half_cell_lengths] assign[=] binary_operation[name[cell_lengths] / constant[2.0]] variable[this_dr] assign[=] binary_operation[name[self].final_site.r - name[self].initial_site.r] for taget[name[i]] in starred[call[name[range], parameter[constant[3]]]] begin[:] if compare[call[name[this_dr]][name[i]] greater[>] call[name[half_cell_lengths]][name[i]]] begin[:] <ast.AugAssign object at 0x7da20c6a80a0> if compare[call[name[this_dr]][name[i]] less[<] <ast.UnaryOp object at 0x7da20c6a9810>] begin[:] <ast.AugAssign object at 0x7da20c6a88b0> return[name[this_dr]]
keyword[def] identifier[dr] ( identifier[self] , identifier[cell_lengths] ): literal[string] identifier[half_cell_lengths] = identifier[cell_lengths] / literal[int] identifier[this_dr] = identifier[self] . identifier[final_site] . identifier[r] - identifier[self] . identifier[initial_site] . identifier[r] keyword[for] identifier[i] keyword[in] identifier[range] ( literal[int] ): keyword[if] identifier[this_dr] [ identifier[i] ]> identifier[half_cell_lengths] [ identifier[i] ]: identifier[this_dr] [ identifier[i] ]-= identifier[cell_lengths] [ identifier[i] ] keyword[if] identifier[this_dr] [ identifier[i] ]<- identifier[half_cell_lengths] [ identifier[i] ]: identifier[this_dr] [ identifier[i] ]+= identifier[cell_lengths] [ identifier[i] ] keyword[return] identifier[this_dr]
def dr(self, cell_lengths): """ Particle displacement vector for this jump Args: cell_lengths (np.array(x,y,z)): Cell lengths for the orthogonal simulation cell. Returns (np.array(x,y,z)): dr """ half_cell_lengths = cell_lengths / 2.0 this_dr = self.final_site.r - self.initial_site.r for i in range(3): if this_dr[i] > half_cell_lengths[i]: this_dr[i] -= cell_lengths[i] # depends on [control=['if'], data=[]] if this_dr[i] < -half_cell_lengths[i]: this_dr[i] += cell_lengths[i] # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['i']] return this_dr
def _compare_acl(current, desired, region, key, keyid, profile): ''' ACLs can be specified using macro-style names that get expanded to something more complex. There's no predictable way to reverse it. So expand all syntactic sugar in our input, and compare against that rather than the input itself. ''' ocid = _get_canonical_id(region, key, keyid, profile) return __utils__['boto3.json_objs_equal'](current, _acl_to_grant(desired, ocid))
def function[_compare_acl, parameter[current, desired, region, key, keyid, profile]]: constant[ ACLs can be specified using macro-style names that get expanded to something more complex. There's no predictable way to reverse it. So expand all syntactic sugar in our input, and compare against that rather than the input itself. ] variable[ocid] assign[=] call[name[_get_canonical_id], parameter[name[region], name[key], name[keyid], name[profile]]] return[call[call[name[__utils__]][constant[boto3.json_objs_equal]], parameter[name[current], call[name[_acl_to_grant], parameter[name[desired], name[ocid]]]]]]
keyword[def] identifier[_compare_acl] ( identifier[current] , identifier[desired] , identifier[region] , identifier[key] , identifier[keyid] , identifier[profile] ): literal[string] identifier[ocid] = identifier[_get_canonical_id] ( identifier[region] , identifier[key] , identifier[keyid] , identifier[profile] ) keyword[return] identifier[__utils__] [ literal[string] ]( identifier[current] , identifier[_acl_to_grant] ( identifier[desired] , identifier[ocid] ))
def _compare_acl(current, desired, region, key, keyid, profile): """ ACLs can be specified using macro-style names that get expanded to something more complex. There's no predictable way to reverse it. So expand all syntactic sugar in our input, and compare against that rather than the input itself. """ ocid = _get_canonical_id(region, key, keyid, profile) return __utils__['boto3.json_objs_equal'](current, _acl_to_grant(desired, ocid))
def retryable_http_error( e ): """ Determine if an error encountered during an HTTP download is likely to go away if we try again. """ if isinstance( e, urllib.error.HTTPError ) and e.code in ('503', '408', '500'): # The server returned one of: # 503 Service Unavailable # 408 Request Timeout # 500 Internal Server Error return True if isinstance( e, BadStatusLine ): # The server didn't return a valid response at all return True return False
def function[retryable_http_error, parameter[e]]: constant[ Determine if an error encountered during an HTTP download is likely to go away if we try again. ] if <ast.BoolOp object at 0x7da1b2344490> begin[:] return[constant[True]] if call[name[isinstance], parameter[name[e], name[BadStatusLine]]] begin[:] return[constant[True]] return[constant[False]]
keyword[def] identifier[retryable_http_error] ( identifier[e] ): literal[string] keyword[if] identifier[isinstance] ( identifier[e] , identifier[urllib] . identifier[error] . identifier[HTTPError] ) keyword[and] identifier[e] . identifier[code] keyword[in] ( literal[string] , literal[string] , literal[string] ): keyword[return] keyword[True] keyword[if] identifier[isinstance] ( identifier[e] , identifier[BadStatusLine] ): keyword[return] keyword[True] keyword[return] keyword[False]
def retryable_http_error(e): """ Determine if an error encountered during an HTTP download is likely to go away if we try again. """ if isinstance(e, urllib.error.HTTPError) and e.code in ('503', '408', '500'): # The server returned one of: # 503 Service Unavailable # 408 Request Timeout # 500 Internal Server Error return True # depends on [control=['if'], data=[]] if isinstance(e, BadStatusLine): # The server didn't return a valid response at all return True # depends on [control=['if'], data=[]] return False
def gelman_rubin(chains, return_cdf=False): """ Compute the Gelman-Rubin R-statistic from an ensemble of chains. `chains` is expected to have shape `(nsteps, nchains)` if samples are one dimensional, or `(nsteps, nchains, ndim)` if multidimensional. For multidimensional samples R-statistics will be computed for each dimension. :param chains: An `(nsteps, nchains)` or `(nsteps, nchains, ndim)`-shaped array. :param return_cdf: (optional) If ``True``, the CDF of the R-statistic(s), assuming an F-distribution, are returned in addition to the R-statistic(s). """ if len(chains.shape) > 2: results = [gelman_rubin(chains[..., param], return_cdf=return_cdf) for param in range(chains.shape[-1])] if return_cdf: return zip(*results) else: return results nchains, nsteps = chains.shape[1], chains.shape[0] chain_means = np.mean(chains, axis=0) chain_vars = np.var(chains, axis=0) # between-chain variance interchain_var = np.sum((chain_means - np.mean(chains)) ** 2) / (nchains - 1) # within-chain variances intrachain_vars = (chains - chain_means)**2 / (nsteps - 1) intrachain_var = np.sum(intrachain_vars)/nchains var = intrachain_var * (nsteps - 1) / nsteps + interchain_var post_var = var + interchain_var / nchains # The Statistic R = np.sqrt(post_var / intrachain_var) if return_cdf: # R should be F-distributed dof1 = nchains - 1 dof2 = 2*intrachain_var**2*nchains/np.var(intrachain_vars) return R, f.cdf(R, dof1, dof2) else: return R
def function[gelman_rubin, parameter[chains, return_cdf]]: constant[ Compute the Gelman-Rubin R-statistic from an ensemble of chains. `chains` is expected to have shape `(nsteps, nchains)` if samples are one dimensional, or `(nsteps, nchains, ndim)` if multidimensional. For multidimensional samples R-statistics will be computed for each dimension. :param chains: An `(nsteps, nchains)` or `(nsteps, nchains, ndim)`-shaped array. :param return_cdf: (optional) If ``True``, the CDF of the R-statistic(s), assuming an F-distribution, are returned in addition to the R-statistic(s). ] if compare[call[name[len], parameter[name[chains].shape]] greater[>] constant[2]] begin[:] variable[results] assign[=] <ast.ListComp object at 0x7da1b2594820> if name[return_cdf] begin[:] return[call[name[zip], parameter[<ast.Starred object at 0x7da1b2596380>]]] <ast.Tuple object at 0x7da1b25974f0> assign[=] tuple[[<ast.Subscript object at 0x7da1b2596bc0>, <ast.Subscript object at 0x7da1b2594dc0>]] variable[chain_means] assign[=] call[name[np].mean, parameter[name[chains]]] variable[chain_vars] assign[=] call[name[np].var, parameter[name[chains]]] variable[interchain_var] assign[=] binary_operation[call[name[np].sum, parameter[binary_operation[binary_operation[name[chain_means] - call[name[np].mean, parameter[name[chains]]]] ** constant[2]]]] / binary_operation[name[nchains] - constant[1]]] variable[intrachain_vars] assign[=] binary_operation[binary_operation[binary_operation[name[chains] - name[chain_means]] ** constant[2]] / binary_operation[name[nsteps] - constant[1]]] variable[intrachain_var] assign[=] binary_operation[call[name[np].sum, parameter[name[intrachain_vars]]] / name[nchains]] variable[var] assign[=] binary_operation[binary_operation[binary_operation[name[intrachain_var] * binary_operation[name[nsteps] - constant[1]]] / name[nsteps]] + name[interchain_var]] variable[post_var] assign[=] binary_operation[name[var] + binary_operation[name[interchain_var] / name[nchains]]] variable[R] assign[=] call[name[np].sqrt, parameter[binary_operation[name[post_var] / name[intrachain_var]]]] if name[return_cdf] begin[:] variable[dof1] assign[=] binary_operation[name[nchains] - constant[1]] variable[dof2] assign[=] binary_operation[binary_operation[binary_operation[constant[2] * binary_operation[name[intrachain_var] ** constant[2]]] * name[nchains]] / call[name[np].var, parameter[name[intrachain_vars]]]] return[tuple[[<ast.Name object at 0x7da1b25960b0>, <ast.Call object at 0x7da1b25976a0>]]]
keyword[def] identifier[gelman_rubin] ( identifier[chains] , identifier[return_cdf] = keyword[False] ): literal[string] keyword[if] identifier[len] ( identifier[chains] . identifier[shape] )> literal[int] : identifier[results] =[ identifier[gelman_rubin] ( identifier[chains] [..., identifier[param] ], identifier[return_cdf] = identifier[return_cdf] ) keyword[for] identifier[param] keyword[in] identifier[range] ( identifier[chains] . identifier[shape] [- literal[int] ])] keyword[if] identifier[return_cdf] : keyword[return] identifier[zip] (* identifier[results] ) keyword[else] : keyword[return] identifier[results] identifier[nchains] , identifier[nsteps] = identifier[chains] . identifier[shape] [ literal[int] ], identifier[chains] . identifier[shape] [ literal[int] ] identifier[chain_means] = identifier[np] . identifier[mean] ( identifier[chains] , identifier[axis] = literal[int] ) identifier[chain_vars] = identifier[np] . identifier[var] ( identifier[chains] , identifier[axis] = literal[int] ) identifier[interchain_var] = identifier[np] . identifier[sum] (( identifier[chain_means] - identifier[np] . identifier[mean] ( identifier[chains] ))** literal[int] )/( identifier[nchains] - literal[int] ) identifier[intrachain_vars] =( identifier[chains] - identifier[chain_means] )** literal[int] /( identifier[nsteps] - literal[int] ) identifier[intrachain_var] = identifier[np] . identifier[sum] ( identifier[intrachain_vars] )/ identifier[nchains] identifier[var] = identifier[intrachain_var] *( identifier[nsteps] - literal[int] )/ identifier[nsteps] + identifier[interchain_var] identifier[post_var] = identifier[var] + identifier[interchain_var] / identifier[nchains] identifier[R] = identifier[np] . identifier[sqrt] ( identifier[post_var] / identifier[intrachain_var] ) keyword[if] identifier[return_cdf] : identifier[dof1] = identifier[nchains] - literal[int] identifier[dof2] = literal[int] * identifier[intrachain_var] ** literal[int] * identifier[nchains] / identifier[np] . identifier[var] ( identifier[intrachain_vars] ) keyword[return] identifier[R] , identifier[f] . identifier[cdf] ( identifier[R] , identifier[dof1] , identifier[dof2] ) keyword[else] : keyword[return] identifier[R]
def gelman_rubin(chains, return_cdf=False): """ Compute the Gelman-Rubin R-statistic from an ensemble of chains. `chains` is expected to have shape `(nsteps, nchains)` if samples are one dimensional, or `(nsteps, nchains, ndim)` if multidimensional. For multidimensional samples R-statistics will be computed for each dimension. :param chains: An `(nsteps, nchains)` or `(nsteps, nchains, ndim)`-shaped array. :param return_cdf: (optional) If ``True``, the CDF of the R-statistic(s), assuming an F-distribution, are returned in addition to the R-statistic(s). """ if len(chains.shape) > 2: results = [gelman_rubin(chains[..., param], return_cdf=return_cdf) for param in range(chains.shape[-1])] if return_cdf: return zip(*results) # depends on [control=['if'], data=[]] else: return results # depends on [control=['if'], data=[]] (nchains, nsteps) = (chains.shape[1], chains.shape[0]) chain_means = np.mean(chains, axis=0) chain_vars = np.var(chains, axis=0) # between-chain variance interchain_var = np.sum((chain_means - np.mean(chains)) ** 2) / (nchains - 1) # within-chain variances intrachain_vars = (chains - chain_means) ** 2 / (nsteps - 1) intrachain_var = np.sum(intrachain_vars) / nchains var = intrachain_var * (nsteps - 1) / nsteps + interchain_var post_var = var + interchain_var / nchains # The Statistic R = np.sqrt(post_var / intrachain_var) if return_cdf: # R should be F-distributed dof1 = nchains - 1 dof2 = 2 * intrachain_var ** 2 * nchains / np.var(intrachain_vars) return (R, f.cdf(R, dof1, dof2)) # depends on [control=['if'], data=[]] else: return R
def _process_pathways(self, limit=None): """ This method adds the KEGG pathway IDs. These are the canonical pathways as defined in KEGG. We also encode the graphical depiction which maps 1:1 with the identifier. Triples created: <pathway_id> is a GO:signal_transduction <pathway_id> rdfs:label <pathway_name> <gene_id> RO:involved_in <pathway_id> :param limit: :return: """ LOG.info("Processing pathways") if self.test_mode: graph = self.testgraph else: graph = self.graph model = Model(graph) line_counter = 0 path = Pathway(graph) raw = '/'.join((self.rawdir, self.files['pathway']['file'])) with open(raw, 'r', encoding="iso-8859-1") as csvfile: filereader = csv.reader(csvfile, delimiter='\t', quotechar='\"') for row in filereader: line_counter += 1 (pathway_id, pathway_name) = row if self.test_mode and pathway_id not in self.test_ids['pathway']: continue pathway_id = 'KEGG-'+pathway_id.strip() path.addPathway(pathway_id, pathway_name) # we know that the pathway images from kegg map 1:1 here. # so add those image_filename = re.sub(r'KEGG-path:', '', pathway_id) + '.png' image_url = 'http://www.genome.jp/kegg/pathway/map/'+image_filename model.addDepiction(pathway_id, image_url) if not self.test_mode and limit is not None and line_counter > limit: break LOG.info("Done with pathways") return
def function[_process_pathways, parameter[self, limit]]: constant[ This method adds the KEGG pathway IDs. These are the canonical pathways as defined in KEGG. We also encode the graphical depiction which maps 1:1 with the identifier. Triples created: <pathway_id> is a GO:signal_transduction <pathway_id> rdfs:label <pathway_name> <gene_id> RO:involved_in <pathway_id> :param limit: :return: ] call[name[LOG].info, parameter[constant[Processing pathways]]] if name[self].test_mode begin[:] variable[graph] assign[=] name[self].testgraph variable[model] assign[=] call[name[Model], parameter[name[graph]]] variable[line_counter] assign[=] constant[0] variable[path] assign[=] call[name[Pathway], parameter[name[graph]]] variable[raw] assign[=] call[constant[/].join, parameter[tuple[[<ast.Attribute object at 0x7da1b26ae2c0>, <ast.Subscript object at 0x7da1b26ad390>]]]] with call[name[open], parameter[name[raw], constant[r]]] begin[:] variable[filereader] assign[=] call[name[csv].reader, parameter[name[csvfile]]] for taget[name[row]] in starred[name[filereader]] begin[:] <ast.AugAssign object at 0x7da1b26acb50> <ast.Tuple object at 0x7da1b26acb20> assign[=] name[row] if <ast.BoolOp object at 0x7da1b26adb70> begin[:] continue variable[pathway_id] assign[=] binary_operation[constant[KEGG-] + call[name[pathway_id].strip, parameter[]]] call[name[path].addPathway, parameter[name[pathway_id], name[pathway_name]]] variable[image_filename] assign[=] binary_operation[call[name[re].sub, parameter[constant[KEGG-path:], constant[], name[pathway_id]]] + constant[.png]] variable[image_url] assign[=] binary_operation[constant[http://www.genome.jp/kegg/pathway/map/] + name[image_filename]] call[name[model].addDepiction, parameter[name[pathway_id], name[image_url]]] if <ast.BoolOp object at 0x7da1b26af010> begin[:] break call[name[LOG].info, parameter[constant[Done with pathways]]] return[None]
keyword[def] identifier[_process_pathways] ( identifier[self] , identifier[limit] = keyword[None] ): literal[string] identifier[LOG] . identifier[info] ( literal[string] ) keyword[if] identifier[self] . identifier[test_mode] : identifier[graph] = identifier[self] . identifier[testgraph] keyword[else] : identifier[graph] = identifier[self] . identifier[graph] identifier[model] = identifier[Model] ( identifier[graph] ) identifier[line_counter] = literal[int] identifier[path] = identifier[Pathway] ( identifier[graph] ) identifier[raw] = literal[string] . identifier[join] (( identifier[self] . identifier[rawdir] , identifier[self] . identifier[files] [ literal[string] ][ literal[string] ])) keyword[with] identifier[open] ( identifier[raw] , literal[string] , identifier[encoding] = literal[string] ) keyword[as] identifier[csvfile] : identifier[filereader] = identifier[csv] . identifier[reader] ( identifier[csvfile] , identifier[delimiter] = literal[string] , identifier[quotechar] = literal[string] ) keyword[for] identifier[row] keyword[in] identifier[filereader] : identifier[line_counter] += literal[int] ( identifier[pathway_id] , identifier[pathway_name] )= identifier[row] keyword[if] identifier[self] . identifier[test_mode] keyword[and] identifier[pathway_id] keyword[not] keyword[in] identifier[self] . identifier[test_ids] [ literal[string] ]: keyword[continue] identifier[pathway_id] = literal[string] + identifier[pathway_id] . identifier[strip] () identifier[path] . identifier[addPathway] ( identifier[pathway_id] , identifier[pathway_name] ) identifier[image_filename] = identifier[re] . identifier[sub] ( literal[string] , literal[string] , identifier[pathway_id] )+ literal[string] identifier[image_url] = literal[string] + identifier[image_filename] identifier[model] . identifier[addDepiction] ( identifier[pathway_id] , identifier[image_url] ) keyword[if] keyword[not] identifier[self] . identifier[test_mode] keyword[and] identifier[limit] keyword[is] keyword[not] keyword[None] keyword[and] identifier[line_counter] > identifier[limit] : keyword[break] identifier[LOG] . identifier[info] ( literal[string] ) keyword[return]
def _process_pathways(self, limit=None): """ This method adds the KEGG pathway IDs. These are the canonical pathways as defined in KEGG. We also encode the graphical depiction which maps 1:1 with the identifier. Triples created: <pathway_id> is a GO:signal_transduction <pathway_id> rdfs:label <pathway_name> <gene_id> RO:involved_in <pathway_id> :param limit: :return: """ LOG.info('Processing pathways') if self.test_mode: graph = self.testgraph # depends on [control=['if'], data=[]] else: graph = self.graph model = Model(graph) line_counter = 0 path = Pathway(graph) raw = '/'.join((self.rawdir, self.files['pathway']['file'])) with open(raw, 'r', encoding='iso-8859-1') as csvfile: filereader = csv.reader(csvfile, delimiter='\t', quotechar='"') for row in filereader: line_counter += 1 (pathway_id, pathway_name) = row if self.test_mode and pathway_id not in self.test_ids['pathway']: continue # depends on [control=['if'], data=[]] pathway_id = 'KEGG-' + pathway_id.strip() path.addPathway(pathway_id, pathway_name) # we know that the pathway images from kegg map 1:1 here. # so add those image_filename = re.sub('KEGG-path:', '', pathway_id) + '.png' image_url = 'http://www.genome.jp/kegg/pathway/map/' + image_filename model.addDepiction(pathway_id, image_url) if not self.test_mode and limit is not None and (line_counter > limit): break # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['row']] # depends on [control=['with'], data=['csvfile']] LOG.info('Done with pathways') return
def clean_path_from_deprecated_naming(base_path): """ Checks if the base path includes deprecated characters/format and returns corrected version The state machine folder name should be according the universal RAFCON path format. In case the state machine path is inside a mounted library_root_path also the library_path has to have this format. The library path is a partial path of the state machine path. This rules are followed to always provide secure paths for RAFCON and all operating systems. :param base_path: :return: cleaned base_path :rtype: str """ def warning_logger_message(insert_string): not_allowed_characters = "'" + "', '".join(REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION.keys()) + "'" logger.warning("Deprecated {2} in {0}. Please avoid to use the following characters {1}." "".format(base_path, not_allowed_characters, insert_string)) from rafcon.core.singleton import library_manager if library_manager.is_os_path_within_library_root_paths(base_path): library_path, library_name = library_manager.get_library_path_and_name_for_os_path(base_path) clean_library_path = clean_path(library_path) clean_library_name = clean_path(library_name) if library_name != clean_library_name or library_path != clean_library_path: warning_logger_message("library path") library_root_key = library_manager._get_library_root_key_for_os_path(base_path) library_root_path = library_manager._library_root_paths[library_root_key] clean_base_path = os.path.join(library_root_path, clean_library_path, clean_library_name) else: path_elements = base_path.split(os.path.sep) state_machine_folder_name = base_path.split(os.path.sep)[-1] path_elements[-1] = clean_path(state_machine_folder_name) if not state_machine_folder_name == path_elements[-1]: warning_logger_message("state machine folder name") clean_base_path = os.path.sep.join(path_elements) return clean_base_path
def function[clean_path_from_deprecated_naming, parameter[base_path]]: constant[ Checks if the base path includes deprecated characters/format and returns corrected version The state machine folder name should be according the universal RAFCON path format. In case the state machine path is inside a mounted library_root_path also the library_path has to have this format. The library path is a partial path of the state machine path. This rules are followed to always provide secure paths for RAFCON and all operating systems. :param base_path: :return: cleaned base_path :rtype: str ] def function[warning_logger_message, parameter[insert_string]]: variable[not_allowed_characters] assign[=] binary_operation[binary_operation[constant['] + call[constant[', '].join, parameter[call[name[REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION].keys, parameter[]]]]] + constant[']] call[name[logger].warning, parameter[call[constant[Deprecated {2} in {0}. Please avoid to use the following characters {1}.].format, parameter[name[base_path], name[not_allowed_characters], name[insert_string]]]]] from relative_module[rafcon.core.singleton] import module[library_manager] if call[name[library_manager].is_os_path_within_library_root_paths, parameter[name[base_path]]] begin[:] <ast.Tuple object at 0x7da1b1b85810> assign[=] call[name[library_manager].get_library_path_and_name_for_os_path, parameter[name[base_path]]] variable[clean_library_path] assign[=] call[name[clean_path], parameter[name[library_path]]] variable[clean_library_name] assign[=] call[name[clean_path], parameter[name[library_name]]] if <ast.BoolOp object at 0x7da1b1b84be0> begin[:] call[name[warning_logger_message], parameter[constant[library path]]] variable[library_root_key] assign[=] call[name[library_manager]._get_library_root_key_for_os_path, parameter[name[base_path]]] variable[library_root_path] assign[=] call[name[library_manager]._library_root_paths][name[library_root_key]] variable[clean_base_path] assign[=] call[name[os].path.join, parameter[name[library_root_path], name[clean_library_path], name[clean_library_name]]] return[name[clean_base_path]]
keyword[def] identifier[clean_path_from_deprecated_naming] ( identifier[base_path] ): literal[string] keyword[def] identifier[warning_logger_message] ( identifier[insert_string] ): identifier[not_allowed_characters] = literal[string] + literal[string] . identifier[join] ( identifier[REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION] . identifier[keys] ())+ literal[string] identifier[logger] . identifier[warning] ( literal[string] literal[string] . identifier[format] ( identifier[base_path] , identifier[not_allowed_characters] , identifier[insert_string] )) keyword[from] identifier[rafcon] . identifier[core] . identifier[singleton] keyword[import] identifier[library_manager] keyword[if] identifier[library_manager] . identifier[is_os_path_within_library_root_paths] ( identifier[base_path] ): identifier[library_path] , identifier[library_name] = identifier[library_manager] . identifier[get_library_path_and_name_for_os_path] ( identifier[base_path] ) identifier[clean_library_path] = identifier[clean_path] ( identifier[library_path] ) identifier[clean_library_name] = identifier[clean_path] ( identifier[library_name] ) keyword[if] identifier[library_name] != identifier[clean_library_name] keyword[or] identifier[library_path] != identifier[clean_library_path] : identifier[warning_logger_message] ( literal[string] ) identifier[library_root_key] = identifier[library_manager] . identifier[_get_library_root_key_for_os_path] ( identifier[base_path] ) identifier[library_root_path] = identifier[library_manager] . identifier[_library_root_paths] [ identifier[library_root_key] ] identifier[clean_base_path] = identifier[os] . identifier[path] . identifier[join] ( identifier[library_root_path] , identifier[clean_library_path] , identifier[clean_library_name] ) keyword[else] : identifier[path_elements] = identifier[base_path] . identifier[split] ( identifier[os] . identifier[path] . identifier[sep] ) identifier[state_machine_folder_name] = identifier[base_path] . identifier[split] ( identifier[os] . identifier[path] . identifier[sep] )[- literal[int] ] identifier[path_elements] [- literal[int] ]= identifier[clean_path] ( identifier[state_machine_folder_name] ) keyword[if] keyword[not] identifier[state_machine_folder_name] == identifier[path_elements] [- literal[int] ]: identifier[warning_logger_message] ( literal[string] ) identifier[clean_base_path] = identifier[os] . identifier[path] . identifier[sep] . identifier[join] ( identifier[path_elements] ) keyword[return] identifier[clean_base_path]
def clean_path_from_deprecated_naming(base_path): """ Checks if the base path includes deprecated characters/format and returns corrected version The state machine folder name should be according the universal RAFCON path format. In case the state machine path is inside a mounted library_root_path also the library_path has to have this format. The library path is a partial path of the state machine path. This rules are followed to always provide secure paths for RAFCON and all operating systems. :param base_path: :return: cleaned base_path :rtype: str """ def warning_logger_message(insert_string): not_allowed_characters = "'" + "', '".join(REPLACED_CHARACTERS_FOR_NO_OS_LIMITATION.keys()) + "'" logger.warning('Deprecated {2} in {0}. Please avoid to use the following characters {1}.'.format(base_path, not_allowed_characters, insert_string)) from rafcon.core.singleton import library_manager if library_manager.is_os_path_within_library_root_paths(base_path): (library_path, library_name) = library_manager.get_library_path_and_name_for_os_path(base_path) clean_library_path = clean_path(library_path) clean_library_name = clean_path(library_name) if library_name != clean_library_name or library_path != clean_library_path: warning_logger_message('library path') # depends on [control=['if'], data=[]] library_root_key = library_manager._get_library_root_key_for_os_path(base_path) library_root_path = library_manager._library_root_paths[library_root_key] clean_base_path = os.path.join(library_root_path, clean_library_path, clean_library_name) # depends on [control=['if'], data=[]] else: path_elements = base_path.split(os.path.sep) state_machine_folder_name = base_path.split(os.path.sep)[-1] path_elements[-1] = clean_path(state_machine_folder_name) if not state_machine_folder_name == path_elements[-1]: warning_logger_message('state machine folder name') # depends on [control=['if'], data=[]] clean_base_path = os.path.sep.join(path_elements) return clean_base_path
def _contains_egg_info( s, _egg_info_re=re.compile(r'([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
def function[_contains_egg_info, parameter[s, _egg_info_re]]: constant[Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 ] return[call[name[bool], parameter[call[name[_egg_info_re].search, parameter[name[s]]]]]]
keyword[def] identifier[_contains_egg_info] ( identifier[s] , identifier[_egg_info_re] = identifier[re] . identifier[compile] ( literal[string] , identifier[re] . identifier[I] )): literal[string] keyword[return] identifier[bool] ( identifier[_egg_info_re] . identifier[search] ( identifier[s] ))
def _contains_egg_info(s, _egg_info_re=re.compile('([a-z0-9_.]+)-([a-z0-9_.!+-]+)', re.I)): """Determine whether the string looks like an egg_info. :param s: The string to parse. E.g. foo-2.1 """ return bool(_egg_info_re.search(s))
def new_stats_exporter(options=None, interval=None): """Get a stats exporter and running transport thread. Create a new `StackdriverStatsExporter` with the given options and start periodically exporting stats to stackdriver in the background. Fall back to default auth if `options` is null. This will raise `google.auth.exceptions.DefaultCredentialsError` if default credentials aren't configured. See `opencensus.metrics.transport.get_exporter_thread` for details on the transport thread. :type options: :class:`Options` :param exporter: Options to pass to the exporter :type interval: int or float :param interval: Seconds between export calls. :rtype: :class:`StackdriverStatsExporter` :return: The newly-created exporter. """ if options is None: _, project_id = google.auth.default() options = Options(project_id=project_id) if str(options.project_id).strip() == "": raise ValueError(ERROR_BLANK_PROJECT_ID) ci = client_info.ClientInfo(client_library_version=get_user_agent_slug()) client = monitoring_v3.MetricServiceClient(client_info=ci) exporter = StackdriverStatsExporter(client=client, options=options) transport.get_exporter_thread(stats.stats, exporter, interval=interval) return exporter
def function[new_stats_exporter, parameter[options, interval]]: constant[Get a stats exporter and running transport thread. Create a new `StackdriverStatsExporter` with the given options and start periodically exporting stats to stackdriver in the background. Fall back to default auth if `options` is null. This will raise `google.auth.exceptions.DefaultCredentialsError` if default credentials aren't configured. See `opencensus.metrics.transport.get_exporter_thread` for details on the transport thread. :type options: :class:`Options` :param exporter: Options to pass to the exporter :type interval: int or float :param interval: Seconds between export calls. :rtype: :class:`StackdriverStatsExporter` :return: The newly-created exporter. ] if compare[name[options] is constant[None]] begin[:] <ast.Tuple object at 0x7da2054a5c00> assign[=] call[name[google].auth.default, parameter[]] variable[options] assign[=] call[name[Options], parameter[]] if compare[call[call[name[str], parameter[name[options].project_id]].strip, parameter[]] equal[==] constant[]] begin[:] <ast.Raise object at 0x7da2054a63b0> variable[ci] assign[=] call[name[client_info].ClientInfo, parameter[]] variable[client] assign[=] call[name[monitoring_v3].MetricServiceClient, parameter[]] variable[exporter] assign[=] call[name[StackdriverStatsExporter], parameter[]] call[name[transport].get_exporter_thread, parameter[name[stats].stats, name[exporter]]] return[name[exporter]]
keyword[def] identifier[new_stats_exporter] ( identifier[options] = keyword[None] , identifier[interval] = keyword[None] ): literal[string] keyword[if] identifier[options] keyword[is] keyword[None] : identifier[_] , identifier[project_id] = identifier[google] . identifier[auth] . identifier[default] () identifier[options] = identifier[Options] ( identifier[project_id] = identifier[project_id] ) keyword[if] identifier[str] ( identifier[options] . identifier[project_id] ). identifier[strip] ()== literal[string] : keyword[raise] identifier[ValueError] ( identifier[ERROR_BLANK_PROJECT_ID] ) identifier[ci] = identifier[client_info] . identifier[ClientInfo] ( identifier[client_library_version] = identifier[get_user_agent_slug] ()) identifier[client] = identifier[monitoring_v3] . identifier[MetricServiceClient] ( identifier[client_info] = identifier[ci] ) identifier[exporter] = identifier[StackdriverStatsExporter] ( identifier[client] = identifier[client] , identifier[options] = identifier[options] ) identifier[transport] . identifier[get_exporter_thread] ( identifier[stats] . identifier[stats] , identifier[exporter] , identifier[interval] = identifier[interval] ) keyword[return] identifier[exporter]
def new_stats_exporter(options=None, interval=None): """Get a stats exporter and running transport thread. Create a new `StackdriverStatsExporter` with the given options and start periodically exporting stats to stackdriver in the background. Fall back to default auth if `options` is null. This will raise `google.auth.exceptions.DefaultCredentialsError` if default credentials aren't configured. See `opencensus.metrics.transport.get_exporter_thread` for details on the transport thread. :type options: :class:`Options` :param exporter: Options to pass to the exporter :type interval: int or float :param interval: Seconds between export calls. :rtype: :class:`StackdriverStatsExporter` :return: The newly-created exporter. """ if options is None: (_, project_id) = google.auth.default() options = Options(project_id=project_id) # depends on [control=['if'], data=['options']] if str(options.project_id).strip() == '': raise ValueError(ERROR_BLANK_PROJECT_ID) # depends on [control=['if'], data=[]] ci = client_info.ClientInfo(client_library_version=get_user_agent_slug()) client = monitoring_v3.MetricServiceClient(client_info=ci) exporter = StackdriverStatsExporter(client=client, options=options) transport.get_exporter_thread(stats.stats, exporter, interval=interval) return exporter
def log(self, logfile=None): """Log the ASCII traceback into a file object.""" if logfile is None: logfile = sys.stderr tb = self.plaintext.encode('utf-8', 'replace').rstrip() + '\n' logfile.write(tb)
def function[log, parameter[self, logfile]]: constant[Log the ASCII traceback into a file object.] if compare[name[logfile] is constant[None]] begin[:] variable[logfile] assign[=] name[sys].stderr variable[tb] assign[=] binary_operation[call[call[name[self].plaintext.encode, parameter[constant[utf-8], constant[replace]]].rstrip, parameter[]] + constant[ ]] call[name[logfile].write, parameter[name[tb]]]
keyword[def] identifier[log] ( identifier[self] , identifier[logfile] = keyword[None] ): literal[string] keyword[if] identifier[logfile] keyword[is] keyword[None] : identifier[logfile] = identifier[sys] . identifier[stderr] identifier[tb] = identifier[self] . identifier[plaintext] . identifier[encode] ( literal[string] , literal[string] ). identifier[rstrip] ()+ literal[string] identifier[logfile] . identifier[write] ( identifier[tb] )
def log(self, logfile=None): """Log the ASCII traceback into a file object.""" if logfile is None: logfile = sys.stderr # depends on [control=['if'], data=['logfile']] tb = self.plaintext.encode('utf-8', 'replace').rstrip() + '\n' logfile.write(tb)
def simxGetUIButtonProperty(clientID, uiHandle, uiButtonID, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' prop = ct.c_int() return c_GetUIButtonProperty(clientID, uiHandle, uiButtonID, ct.byref(prop), operationMode), prop.value
def function[simxGetUIButtonProperty, parameter[clientID, uiHandle, uiButtonID, operationMode]]: constant[ Please have a look at the function description/documentation in the V-REP user manual ] variable[prop] assign[=] call[name[ct].c_int, parameter[]] return[tuple[[<ast.Call object at 0x7da207f01de0>, <ast.Attribute object at 0x7da207f022c0>]]]
keyword[def] identifier[simxGetUIButtonProperty] ( identifier[clientID] , identifier[uiHandle] , identifier[uiButtonID] , identifier[operationMode] ): literal[string] identifier[prop] = identifier[ct] . identifier[c_int] () keyword[return] identifier[c_GetUIButtonProperty] ( identifier[clientID] , identifier[uiHandle] , identifier[uiButtonID] , identifier[ct] . identifier[byref] ( identifier[prop] ), identifier[operationMode] ), identifier[prop] . identifier[value]
def simxGetUIButtonProperty(clientID, uiHandle, uiButtonID, operationMode): """ Please have a look at the function description/documentation in the V-REP user manual """ prop = ct.c_int() return (c_GetUIButtonProperty(clientID, uiHandle, uiButtonID, ct.byref(prop), operationMode), prop.value)
def _get_locations(self, calc): """Locate locations within the profile.""" return (self._location_in(calc.profile), self._location_out(calc.profile))
def function[_get_locations, parameter[self, calc]]: constant[Locate locations within the profile.] return[tuple[[<ast.Call object at 0x7da1b25ef6d0>, <ast.Call object at 0x7da1b25efeb0>]]]
keyword[def] identifier[_get_locations] ( identifier[self] , identifier[calc] ): literal[string] keyword[return] ( identifier[self] . identifier[_location_in] ( identifier[calc] . identifier[profile] ), identifier[self] . identifier[_location_out] ( identifier[calc] . identifier[profile] ))
def _get_locations(self, calc): """Locate locations within the profile.""" return (self._location_in(calc.profile), self._location_out(calc.profile))
def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())]
def function[pathNames, parameter[self]]: constant[ Path Names @return: A list of path + name of each file, relative to the root directory. ] return[<ast.ListComp object at 0x7da20c76d000>]
keyword[def] identifier[pathNames] ( identifier[self] )->[ identifier[str] ]: literal[string] keyword[return] [ identifier[f] . identifier[pathName] keyword[for] identifier[f] keyword[in] identifier[list] ( identifier[self] . identifier[_files] . identifier[values] ())]
def pathNames(self) -> [str]: """ Path Names @return: A list of path + name of each file, relative to the root directory. """ return [f.pathName for f in list(self._files.values())]
def tenant_path(cls, project, tenant): """Return a fully-qualified tenant string.""" return google.api_core.path_template.expand( "projects/{project}/tenants/{tenant}", project=project, tenant=tenant )
def function[tenant_path, parameter[cls, project, tenant]]: constant[Return a fully-qualified tenant string.] return[call[name[google].api_core.path_template.expand, parameter[constant[projects/{project}/tenants/{tenant}]]]]
keyword[def] identifier[tenant_path] ( identifier[cls] , identifier[project] , identifier[tenant] ): literal[string] keyword[return] identifier[google] . identifier[api_core] . identifier[path_template] . identifier[expand] ( literal[string] , identifier[project] = identifier[project] , identifier[tenant] = identifier[tenant] )
def tenant_path(cls, project, tenant): """Return a fully-qualified tenant string.""" return google.api_core.path_template.expand('projects/{project}/tenants/{tenant}', project=project, tenant=tenant)
def _exclude_files_parser(cls, key): """Returns a parser function to make sure field inputs are not files. Parses a value after getting the key so error messages are more informative. :param key: :rtype: callable """ def parser(value): exclude_directive = 'file:' if value.startswith(exclude_directive): raise ValueError( 'Only strings are accepted for the {0} field, ' 'files are not accepted'.format(key)) return value return parser
def function[_exclude_files_parser, parameter[cls, key]]: constant[Returns a parser function to make sure field inputs are not files. Parses a value after getting the key so error messages are more informative. :param key: :rtype: callable ] def function[parser, parameter[value]]: variable[exclude_directive] assign[=] constant[file:] if call[name[value].startswith, parameter[name[exclude_directive]]] begin[:] <ast.Raise object at 0x7da1b1b12fb0> return[name[value]] return[name[parser]]
keyword[def] identifier[_exclude_files_parser] ( identifier[cls] , identifier[key] ): literal[string] keyword[def] identifier[parser] ( identifier[value] ): identifier[exclude_directive] = literal[string] keyword[if] identifier[value] . identifier[startswith] ( identifier[exclude_directive] ): keyword[raise] identifier[ValueError] ( literal[string] literal[string] . identifier[format] ( identifier[key] )) keyword[return] identifier[value] keyword[return] identifier[parser]
def _exclude_files_parser(cls, key): """Returns a parser function to make sure field inputs are not files. Parses a value after getting the key so error messages are more informative. :param key: :rtype: callable """ def parser(value): exclude_directive = 'file:' if value.startswith(exclude_directive): raise ValueError('Only strings are accepted for the {0} field, files are not accepted'.format(key)) # depends on [control=['if'], data=[]] return value return parser
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() if self.id is not None: return "%s/%s/%s" % (url, name, self.id) return "%s/%s" % (url, name)
def function[get_resource_url, parameter[self]]: constant[ Get resource complete url ] variable[name] assign[=] name[self].__class__.resource_name variable[url] assign[=] call[name[self].__class__.rest_base_url, parameter[]] if compare[name[self].id is_not constant[None]] begin[:] return[binary_operation[constant[%s/%s/%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b0f386a0>, <ast.Name object at 0x7da1b0f3bc10>, <ast.Attribute object at 0x7da1b0f38850>]]]] return[binary_operation[constant[%s/%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Name object at 0x7da1b0f3a080>, <ast.Name object at 0x7da1b0f38190>]]]]
keyword[def] identifier[get_resource_url] ( identifier[self] ): literal[string] identifier[name] = identifier[self] . identifier[__class__] . identifier[resource_name] identifier[url] = identifier[self] . identifier[__class__] . identifier[rest_base_url] () keyword[if] identifier[self] . identifier[id] keyword[is] keyword[not] keyword[None] : keyword[return] literal[string] %( identifier[url] , identifier[name] , identifier[self] . identifier[id] ) keyword[return] literal[string] %( identifier[url] , identifier[name] )
def get_resource_url(self): """ Get resource complete url """ name = self.__class__.resource_name url = self.__class__.rest_base_url() if self.id is not None: return '%s/%s/%s' % (url, name, self.id) # depends on [control=['if'], data=[]] return '%s/%s' % (url, name)
def minutes_played(self): """ Returns a ``float`` of the number of game minutes the player was on the court for. """ if self._minutes_played[self._index]: minutes, seconds = self._minutes_played[self._index].split(':') minutes = float(minutes) + float(seconds) / 60 return float(minutes) return None
def function[minutes_played, parameter[self]]: constant[ Returns a ``float`` of the number of game minutes the player was on the court for. ] if call[name[self]._minutes_played][name[self]._index] begin[:] <ast.Tuple object at 0x7da1b0be2080> assign[=] call[call[name[self]._minutes_played][name[self]._index].split, parameter[constant[:]]] variable[minutes] assign[=] binary_operation[call[name[float], parameter[name[minutes]]] + binary_operation[call[name[float], parameter[name[seconds]]] / constant[60]]] return[call[name[float], parameter[name[minutes]]]] return[constant[None]]
keyword[def] identifier[minutes_played] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[_minutes_played] [ identifier[self] . identifier[_index] ]: identifier[minutes] , identifier[seconds] = identifier[self] . identifier[_minutes_played] [ identifier[self] . identifier[_index] ]. identifier[split] ( literal[string] ) identifier[minutes] = identifier[float] ( identifier[minutes] )+ identifier[float] ( identifier[seconds] )/ literal[int] keyword[return] identifier[float] ( identifier[minutes] ) keyword[return] keyword[None]
def minutes_played(self): """ Returns a ``float`` of the number of game minutes the player was on the court for. """ if self._minutes_played[self._index]: (minutes, seconds) = self._minutes_played[self._index].split(':') minutes = float(minutes) + float(seconds) / 60 return float(minutes) # depends on [control=['if'], data=[]] return None
def lerp(a, b, t): """ Returns the linear interpolation between a and b for time t between 0.0-1.0. For example: lerp(100, 200, 0.5) => 150. """ if t < 0.0: return a if t > 1.0: return b return a + (b - a) * t
def function[lerp, parameter[a, b, t]]: constant[ Returns the linear interpolation between a and b for time t between 0.0-1.0. For example: lerp(100, 200, 0.5) => 150. ] if compare[name[t] less[<] constant[0.0]] begin[:] return[name[a]] if compare[name[t] greater[>] constant[1.0]] begin[:] return[name[b]] return[binary_operation[name[a] + binary_operation[binary_operation[name[b] - name[a]] * name[t]]]]
keyword[def] identifier[lerp] ( identifier[a] , identifier[b] , identifier[t] ): literal[string] keyword[if] identifier[t] < literal[int] : keyword[return] identifier[a] keyword[if] identifier[t] > literal[int] : keyword[return] identifier[b] keyword[return] identifier[a] +( identifier[b] - identifier[a] )* identifier[t]
def lerp(a, b, t): """ Returns the linear interpolation between a and b for time t between 0.0-1.0. For example: lerp(100, 200, 0.5) => 150. """ if t < 0.0: return a # depends on [control=['if'], data=[]] if t > 1.0: return b # depends on [control=['if'], data=[]] return a + (b - a) * t
def op(token, func, left=False, right=False): """op provides a more verbose syntax for declaring operators. :param token: The string token of the operator. Usually a single character. :param func: A callable used to evaluate its arguments. Where the operator is both-sided the callable should accept two arguments. Where it is one-sided it should accept one argument. :param left: A boolean indicating whether the operator applies to the expression to the left of it. :param right: A boolean indicating whether the operator applies to the expression to the right of it. :returns: a tuple (token, func, side) where side is OP_BOTH if left and right (or neither) and OP_LEFT if left, otherwise OP_RIGHT. """ both = (left == right) return (token, func, OP_BOTH if both else OP_LEFT if left else OP_RIGHT)
def function[op, parameter[token, func, left, right]]: constant[op provides a more verbose syntax for declaring operators. :param token: The string token of the operator. Usually a single character. :param func: A callable used to evaluate its arguments. Where the operator is both-sided the callable should accept two arguments. Where it is one-sided it should accept one argument. :param left: A boolean indicating whether the operator applies to the expression to the left of it. :param right: A boolean indicating whether the operator applies to the expression to the right of it. :returns: a tuple (token, func, side) where side is OP_BOTH if left and right (or neither) and OP_LEFT if left, otherwise OP_RIGHT. ] variable[both] assign[=] compare[name[left] equal[==] name[right]] return[tuple[[<ast.Name object at 0x7da18f7201c0>, <ast.Name object at 0x7da18f720160>, <ast.IfExp object at 0x7da18f7235e0>]]]
keyword[def] identifier[op] ( identifier[token] , identifier[func] , identifier[left] = keyword[False] , identifier[right] = keyword[False] ): literal[string] identifier[both] =( identifier[left] == identifier[right] ) keyword[return] ( identifier[token] , identifier[func] , identifier[OP_BOTH] keyword[if] identifier[both] keyword[else] identifier[OP_LEFT] keyword[if] identifier[left] keyword[else] identifier[OP_RIGHT] )
def op(token, func, left=False, right=False): """op provides a more verbose syntax for declaring operators. :param token: The string token of the operator. Usually a single character. :param func: A callable used to evaluate its arguments. Where the operator is both-sided the callable should accept two arguments. Where it is one-sided it should accept one argument. :param left: A boolean indicating whether the operator applies to the expression to the left of it. :param right: A boolean indicating whether the operator applies to the expression to the right of it. :returns: a tuple (token, func, side) where side is OP_BOTH if left and right (or neither) and OP_LEFT if left, otherwise OP_RIGHT. """ both = left == right return (token, func, OP_BOTH if both else OP_LEFT if left else OP_RIGHT)
def read(self, input_file): """ Reads an InputHeader from `input_file`. The input header is read as a sequence of *<key>***:***<value>* pairs separated by a newline. The end of the input header is signalled by an empty line or an end-of-file. :param input_file: File-like object that supports iteration over lines """ key, value = None, None import sys for line in input_file: if line == '\n': break if line[-1:] == '\n': line = line[:-1] item = line.split(':', 1) if len(item) == 2: # start of a new item self._update(key, value) key, value = item[0], urllib.unquote(item[1]) elif key is not None: # continuation of the current item value = '\n'.join([value, urllib.unquote(line)]) self._update(key, value) return
def function[read, parameter[self, input_file]]: constant[ Reads an InputHeader from `input_file`. The input header is read as a sequence of *<key>***:***<value>* pairs separated by a newline. The end of the input header is signalled by an empty line or an end-of-file. :param input_file: File-like object that supports iteration over lines ] <ast.Tuple object at 0x7da1b170e7d0> assign[=] tuple[[<ast.Constant object at 0x7da1b170d660>, <ast.Constant object at 0x7da1b170e770>]] import module[sys] for taget[name[line]] in starred[name[input_file]] begin[:] if compare[name[line] equal[==] constant[ ]] begin[:] break if compare[call[name[line]][<ast.Slice object at 0x7da18f00e5c0>] equal[==] constant[ ]] begin[:] variable[line] assign[=] call[name[line]][<ast.Slice object at 0x7da18f00c4f0>] variable[item] assign[=] call[name[line].split, parameter[constant[:], constant[1]]] if compare[call[name[len], parameter[name[item]]] equal[==] constant[2]] begin[:] call[name[self]._update, parameter[name[key], name[value]]] <ast.Tuple object at 0x7da18f00d120> assign[=] tuple[[<ast.Subscript object at 0x7da18f00d6f0>, <ast.Call object at 0x7da18f00ffd0>]] call[name[self]._update, parameter[name[key], name[value]]] return[None]
keyword[def] identifier[read] ( identifier[self] , identifier[input_file] ): literal[string] identifier[key] , identifier[value] = keyword[None] , keyword[None] keyword[import] identifier[sys] keyword[for] identifier[line] keyword[in] identifier[input_file] : keyword[if] identifier[line] == literal[string] : keyword[break] keyword[if] identifier[line] [- literal[int] :]== literal[string] : identifier[line] = identifier[line] [:- literal[int] ] identifier[item] = identifier[line] . identifier[split] ( literal[string] , literal[int] ) keyword[if] identifier[len] ( identifier[item] )== literal[int] : identifier[self] . identifier[_update] ( identifier[key] , identifier[value] ) identifier[key] , identifier[value] = identifier[item] [ literal[int] ], identifier[urllib] . identifier[unquote] ( identifier[item] [ literal[int] ]) keyword[elif] identifier[key] keyword[is] keyword[not] keyword[None] : identifier[value] = literal[string] . identifier[join] ([ identifier[value] , identifier[urllib] . identifier[unquote] ( identifier[line] )]) identifier[self] . identifier[_update] ( identifier[key] , identifier[value] ) keyword[return]
def read(self, input_file): """ Reads an InputHeader from `input_file`. The input header is read as a sequence of *<key>***:***<value>* pairs separated by a newline. The end of the input header is signalled by an empty line or an end-of-file. :param input_file: File-like object that supports iteration over lines """ (key, value) = (None, None) import sys for line in input_file: if line == '\n': break # depends on [control=['if'], data=[]] if line[-1:] == '\n': line = line[:-1] # depends on [control=['if'], data=[]] item = line.split(':', 1) if len(item) == 2: # start of a new item self._update(key, value) (key, value) = (item[0], urllib.unquote(item[1])) # depends on [control=['if'], data=[]] elif key is not None: # continuation of the current item value = '\n'.join([value, urllib.unquote(line)]) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['line']] self._update(key, value) return
def setItemStyle(self, itemStyle): """ Sets the item style that will be used for this widget. If you are trying to set a style on an item that has children, make sure to turn off the useGroupStyleWithChildren option, or it will always display as a group. :param itemStyle | <XGanttWidgetItem.ItemStyle> """ self._itemStyle = itemStyle # initialize the group icon for group style if itemStyle == XGanttWidgetItem.ItemStyle.Group and \ self.icon(0).isNull(): ico = projexui.resources.find('img/folder_close.png') expand_ico = projexui.resources.find('img/folder_open.png') self.setIcon(0, QIcon(ico)) self.setExpandedIcon(0, QIcon(expand_ico))
def function[setItemStyle, parameter[self, itemStyle]]: constant[ Sets the item style that will be used for this widget. If you are trying to set a style on an item that has children, make sure to turn off the useGroupStyleWithChildren option, or it will always display as a group. :param itemStyle | <XGanttWidgetItem.ItemStyle> ] name[self]._itemStyle assign[=] name[itemStyle] if <ast.BoolOp object at 0x7da20cabe650> begin[:] variable[ico] assign[=] call[name[projexui].resources.find, parameter[constant[img/folder_close.png]]] variable[expand_ico] assign[=] call[name[projexui].resources.find, parameter[constant[img/folder_open.png]]] call[name[self].setIcon, parameter[constant[0], call[name[QIcon], parameter[name[ico]]]]] call[name[self].setExpandedIcon, parameter[constant[0], call[name[QIcon], parameter[name[expand_ico]]]]]
keyword[def] identifier[setItemStyle] ( identifier[self] , identifier[itemStyle] ): literal[string] identifier[self] . identifier[_itemStyle] = identifier[itemStyle] keyword[if] identifier[itemStyle] == identifier[XGanttWidgetItem] . identifier[ItemStyle] . identifier[Group] keyword[and] identifier[self] . identifier[icon] ( literal[int] ). identifier[isNull] (): identifier[ico] = identifier[projexui] . identifier[resources] . identifier[find] ( literal[string] ) identifier[expand_ico] = identifier[projexui] . identifier[resources] . identifier[find] ( literal[string] ) identifier[self] . identifier[setIcon] ( literal[int] , identifier[QIcon] ( identifier[ico] )) identifier[self] . identifier[setExpandedIcon] ( literal[int] , identifier[QIcon] ( identifier[expand_ico] ))
def setItemStyle(self, itemStyle): """ Sets the item style that will be used for this widget. If you are trying to set a style on an item that has children, make sure to turn off the useGroupStyleWithChildren option, or it will always display as a group. :param itemStyle | <XGanttWidgetItem.ItemStyle> """ self._itemStyle = itemStyle # initialize the group icon for group style if itemStyle == XGanttWidgetItem.ItemStyle.Group and self.icon(0).isNull(): ico = projexui.resources.find('img/folder_close.png') expand_ico = projexui.resources.find('img/folder_open.png') self.setIcon(0, QIcon(ico)) self.setExpandedIcon(0, QIcon(expand_ico)) # depends on [control=['if'], data=[]]
def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS): """Return an expiration `days` in the future""" now = delorean.Delorean() return now + datetime.timedelta(days=days)
def function[new_expiry, parameter[days]]: constant[Return an expiration `days` in the future] variable[now] assign[=] call[name[delorean].Delorean, parameter[]] return[binary_operation[name[now] + call[name[datetime].timedelta, parameter[]]]]
keyword[def] identifier[new_expiry] ( identifier[days] = identifier[DEFAULT_PASTE_LIFETIME_DAYS] ): literal[string] identifier[now] = identifier[delorean] . identifier[Delorean] () keyword[return] identifier[now] + identifier[datetime] . identifier[timedelta] ( identifier[days] = identifier[days] )
def new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS): """Return an expiration `days` in the future""" now = delorean.Delorean() return now + datetime.timedelta(days=days)
def connect(self): """ Connect to an AWS API via boto3 low-level client and set ``self.conn`` to the `boto3.client <https://boto3.readthed ocs.org/en/latest/reference/core/boto3.html#boto3.client>`_ object (a ``botocore.client.*`` instance). If ``self.conn`` is not None, do nothing. This connects to the API name given by ``self.api_name``. :returns: None """ if self.conn is not None: return kwargs = self._boto3_connection_kwargs self.conn = boto3.client(self.api_name, **kwargs) logger.info("Connected to %s in region %s", self.api_name, self.conn._client_config.region_name)
def function[connect, parameter[self]]: constant[ Connect to an AWS API via boto3 low-level client and set ``self.conn`` to the `boto3.client <https://boto3.readthed ocs.org/en/latest/reference/core/boto3.html#boto3.client>`_ object (a ``botocore.client.*`` instance). If ``self.conn`` is not None, do nothing. This connects to the API name given by ``self.api_name``. :returns: None ] if compare[name[self].conn is_not constant[None]] begin[:] return[None] variable[kwargs] assign[=] name[self]._boto3_connection_kwargs name[self].conn assign[=] call[name[boto3].client, parameter[name[self].api_name]] call[name[logger].info, parameter[constant[Connected to %s in region %s], name[self].api_name, name[self].conn._client_config.region_name]]
keyword[def] identifier[connect] ( identifier[self] ): literal[string] keyword[if] identifier[self] . identifier[conn] keyword[is] keyword[not] keyword[None] : keyword[return] identifier[kwargs] = identifier[self] . identifier[_boto3_connection_kwargs] identifier[self] . identifier[conn] = identifier[boto3] . identifier[client] ( identifier[self] . identifier[api_name] ,** identifier[kwargs] ) identifier[logger] . identifier[info] ( literal[string] , identifier[self] . identifier[api_name] , identifier[self] . identifier[conn] . identifier[_client_config] . identifier[region_name] )
def connect(self): """ Connect to an AWS API via boto3 low-level client and set ``self.conn`` to the `boto3.client <https://boto3.readthed ocs.org/en/latest/reference/core/boto3.html#boto3.client>`_ object (a ``botocore.client.*`` instance). If ``self.conn`` is not None, do nothing. This connects to the API name given by ``self.api_name``. :returns: None """ if self.conn is not None: return # depends on [control=['if'], data=[]] kwargs = self._boto3_connection_kwargs self.conn = boto3.client(self.api_name, **kwargs) logger.info('Connected to %s in region %s', self.api_name, self.conn._client_config.region_name)