_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q8200
nside_to_pixel_area
train
def nside_to_pixel_area(nside): """ Find the area of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- pixel_ar...
python
{ "resource": "" }
q8201
nside_to_pixel_resolution
train
def nside_to_pixel_resolution(nside): """ Find the resolution of HEALPix pixels given the pixel dimensions of one of the 12 'top-level' HEALPix tiles. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- ...
python
{ "resource": "" }
q8202
pixel_resolution_to_nside
train
def pixel_resolution_to_nside(resolution, round='nearest'): """Find closest HEALPix nside for a given angular resolution. This function is the inverse of `nside_to_pixel_resolution`, for the default rounding scheme of ``round='nearest'``. If you choose ``round='up'``, you'll get HEALPix pixels that ...
python
{ "resource": "" }
q8203
nside_to_npix
train
def nside_to_npix(nside): """ Find the number of pixels corresponding to a HEALPix resolution. Parameters ---------- nside : int The number of pixels on the side of one of the 12 'top-level' HEALPix tiles. Returns ------- npix : int The number of pixels in the HEALPix m...
python
{ "resource": "" }
q8204
npix_to_nside
train
def npix_to_nside(npix): """ Find the number of pixels on the side of one of the 12 'top-level' HEALPix tiles given a total number of pixels. Parameters ---------- npix : int The number of pixels in the HEALPix map. Returns ------- nside : int The number of pixels o...
python
{ "resource": "" }
q8205
nested_to_ring
train
def nested_to_ring(nested_index, nside): """ Convert a HEALPix 'nested' index to a HEALPix 'ring' index Parameters ---------- nested_index : int or `~numpy.ndarray` Healpix index using the 'nested' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each ...
python
{ "resource": "" }
q8206
ring_to_nested
train
def ring_to_nested(ring_index, nside): """ Convert a HEALPix 'ring' index to a HEALPix 'nested' index Parameters ---------- ring_index : int or `~numpy.ndarray` Healpix index using the 'ring' ordering nside : int or `~numpy.ndarray` Number of pixels along the side of each of the...
python
{ "resource": "" }
q8207
nside2resol
train
def nside2resol(nside, arcmin=False): """Drop-in replacement for healpy `~healpy.pixelfunc.nside2resol`.""" resolution = nside_to_pixel_resolution(nside) if arcmin: return resolution.to(u.arcmin).value else: return resolution.to(u.rad).value
python
{ "resource": "" }
q8208
nside2pixarea
train
def nside2pixarea(nside, degrees=False): """Drop-in replacement for healpy `~healpy.pixelfunc.nside2pixarea`.""" area = nside_to_pixel_area(nside) if degrees: return area.to(u.deg ** 2).value else: return area.to(u.sr).value
python
{ "resource": "" }
q8209
pix2ang
train
def pix2ang(nside, ipix, nest=False, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.pix2ang`.""" lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return _lonlat_to_healpy(lon, lat, lonlat=lonlat)
python
{ "resource": "" }
q8210
ang2pix
train
def ang2pix(nside, theta, phi, nest=False, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.ang2pix`.""" lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return lonlat_to_healpix(lon, lat, nside, order='nested' if nest else 'ring')
python
{ "resource": "" }
q8211
pix2vec
train
def pix2vec(nside, ipix, nest=False): """Drop-in replacement for healpy `~healpy.pixelfunc.pix2vec`.""" lon, lat = healpix_to_lonlat(ipix, nside, order='nested' if nest else 'ring') return ang2vec(*_lonlat_to_healpy(lon, lat))
python
{ "resource": "" }
q8212
vec2pix
train
def vec2pix(nside, x, y, z, nest=False): """Drop-in replacement for healpy `~healpy.pixelfunc.vec2pix`.""" theta, phi = vec2ang(np.transpose([x, y, z])) # hp.vec2ang() returns raveled arrays, which are 1D. if np.isscalar(x): theta = theta.item() phi = phi.item() else: shape =...
python
{ "resource": "" }
q8213
nest2ring
train
def nest2ring(nside, ipix): """Drop-in replacement for healpy `~healpy.pixelfunc.nest2ring`.""" ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return nested_to_ring(ipix, nside)
python
{ "resource": "" }
q8214
ring2nest
train
def ring2nest(nside, ipix): """Drop-in replacement for healpy `~healpy.pixelfunc.ring2nest`.""" ipix = np.atleast_1d(ipix).astype(np.int64, copy=False) return ring_to_nested(ipix, nside)
python
{ "resource": "" }
q8215
boundaries
train
def boundaries(nside, pix, step=1, nest=False): """Drop-in replacement for healpy `~healpy.boundaries`.""" pix = np.asarray(pix) if pix.ndim > 1: # For consistency with healpy we only support scalars or 1D arrays raise ValueError("Array has to be one dimensional") lon, lat = boundaries_l...
python
{ "resource": "" }
q8216
vec2ang
train
def vec2ang(vectors, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.vec2ang`.""" x, y, z = vectors.transpose() rep_car = CartesianRepresentation(x, y, z) rep_sph = rep_car.represent_as(UnitSphericalRepresentation) return _lonlat_to_healpy(rep_sph.lon.ravel(), rep_sph.lat.ravel()...
python
{ "resource": "" }
q8217
ang2vec
train
def ang2vec(theta, phi, lonlat=False): """Drop-in replacement for healpy `~healpy.pixelfunc.ang2vec`.""" lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) rep_sph = UnitSphericalRepresentation(lon, lat) rep_car = rep_sph.represent_as(CartesianRepresentation) return rep_car.xyz.value
python
{ "resource": "" }
q8218
get_interp_weights
train
def get_interp_weights(nside, theta, phi=None, nest=False, lonlat=False): """ Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_weights`. Although note that the order of the weights and pixels may differ. """ # if phi is not given, theta is interpreted as pixel number if phi is None:...
python
{ "resource": "" }
q8219
get_interp_val
train
def get_interp_val(m, theta, phi, nest=False, lonlat=False): """ Drop-in replacement for healpy `~healpy.pixelfunc.get_interp_val`. """ lon, lat = _healpy_to_lonlat(theta, phi, lonlat=lonlat) return interpolate_bilinear_lonlat(lon, lat, m, order='nested' if nest else 'ring')
python
{ "resource": "" }
q8220
bench_run
train
def bench_run(fast=False): """Run all benchmarks. Return results as a dict.""" results = [] if fast: SIZES = [10, 1e3, 1e5] else: SIZES = [10, 1e3, 1e6] for nest in [True, False]: for size in SIZES: for nside in [1, 128]: results.append(run_singl...
python
{ "resource": "" }
q8221
bench_report
train
def bench_report(results): """Print a report for given benchmark results to the console.""" table = Table(names=['function', 'nest', 'nside', 'size', 'time_healpy', 'time_self', 'ratio'], dtype=['S20', bool, int, int, float, float, float], masked=True) for row in ...
python
{ "resource": "" }
q8222
main
train
def main(fast=False): """Run all benchmarks and print report to the console.""" print('Running benchmarks...\n') results = bench_run(fast=fast) bench_report(results)
python
{ "resource": "" }
q8223
flask_scoped_session.init_app
train
def init_app(self, app): """Setup scoped sesssion creation and teardown for the passed ``app``. :param app: a :class:`~flask.Flask` application """ app.scoped_session = self @app.teardown_appcontext def remove_scoped_session(*args, **kwargs): # pylint: disab...
python
{ "resource": "" }
q8224
validate
train
def validate(request_schema=None, response_schema=None): """ Decorate request handler to make it automagically validate it's request and response. """ def wrapper(func): # Validating the schemas itself. # Die with exception if they aren't valid if request_schema is not None: ...
python
{ "resource": "" }
q8225
cli
train
def cli(yamlfile, inline, format): """ Generate JSON Schema representation of a biolink model """ print(JsonSchemaGenerator(yamlfile, format).serialize(inline=inline))
python
{ "resource": "" }
q8226
cli
train
def cli(yamlfile, format, dir, classes, img, noimages): """ Generate markdown documentation of a biolink model """ MarkdownGenerator(yamlfile, format).serialize(classes=classes, directory=dir, image_dir=img, noimages=noimages)
python
{ "resource": "" }
q8227
MarkdownGenerator.is_secondary_ref
train
def is_secondary_ref(self, en: str) -> bool: """ Determine whether 'en' is the name of something in the neighborhood of the requested classes @param en: element name @return: True if 'en' is the name of a slot, class or type in the immediate neighborhood of of what we are building ...
python
{ "resource": "" }
q8228
MarkdownGenerator.bbin
train
def bbin(obj: Union[str, Element]) -> str: """ Boldify built in types @param obj: object name or id @return: """ return obj.name if isinstance(obj, Element ) else f'**{obj}**' if obj in builtin_names else obj
python
{ "resource": "" }
q8229
MarkdownGenerator.link
train
def link(self, ref: Optional[Union[str, Element]], *, after_link: str = None, use_desc: bool=False, add_subset: bool=True) -> str: """ Create a link to ref if appropriate. @param ref: the name or value of a class, slot, type or the name of a built in type. @param after_link: Text t...
python
{ "resource": "" }
q8230
cli
train
def cli(yamlfile, format, output): """ Generate an OWL representation of a biolink model """ print(OwlSchemaGenerator(yamlfile, format).serialize(output=output))
python
{ "resource": "" }
q8231
OwlSchemaGenerator.visit_slot
train
def visit_slot(self, slot_name: str, slot: SlotDefinition) -> None: """ Add a slot definition per slot @param slot_name: @param slot: @return: """ # Note: We use the raw name in OWL and add a subProperty arc slot_uri = self.prop_uri(slot.name) # Parent s...
python
{ "resource": "" }
q8232
load_raw_schema
train
def load_raw_schema(data: Union[str, TextIO], source_file: str=None, source_file_date: str=None, source_file_size: int=None, base_dir: Optional[str]=None) -> SchemaDefinition: """ Load and flatten SchemaDefinition from a file name, a UR...
python
{ "resource": "" }
q8233
DupCheckYamlLoader.map_constructor
train
def map_constructor(self, loader, node, deep=False): """ Walk the mapping, recording any duplicate keys. """ mapping = {} for key_node, value_node in node.value: key = loader.construct_object(key_node, deep=deep) value = loader.construct_object(value_node, deep=...
python
{ "resource": "" }
q8234
cli
train
def cli(file1, file2, comments) -> int: """ Compare file1 to file2 using a filter """ sys.exit(compare_files(file1, file2, comments))
python
{ "resource": "" }
q8235
cli
train
def cli(file, dir, format): """ Generate GOLR representation of a biolink model """ print(GolrSchemaGenerator(file, format).serialize(dirname=dir))
python
{ "resource": "" }
q8236
cli
train
def cli(yamlfile, directory, out, classname, format): """ Generate graphviz representations of the biolink model """ DotGenerator(yamlfile, format).serialize(classname=classname, dirname=directory, filename=out)
python
{ "resource": "" }
q8237
cli
train
def cli(yamlfile, format, context): """ Generate JSONLD file from biolink schema """ print(JSONLDGenerator(yamlfile, format).serialize(context=context))
python
{ "resource": "" }
q8238
cli
train
def cli(yamlfile, format, output, context): """ Generate an RDF representation of a biolink model """ print(RDFGenerator(yamlfile, format).serialize(output=output, context=context))
python
{ "resource": "" }
q8239
Generator.all_slots
train
def all_slots(self, cls: CLASS_OR_CLASSNAME, *, cls_slots_first: bool = False) \ -> List[SlotDefinition]: """ Return all slots that are part of the class definition. This includes all is_a, mixin and apply_to slots but does NOT include slot_usage targets. If class B has a slot_usage entry ...
python
{ "resource": "" }
q8240
Generator.ancestors
train
def ancestors(self, definition: Union[SLOT_OR_SLOTNAME, CLASS_OR_CLASSNAME]) \ -> List[Union[SlotDefinitionName, ClassDefinitionName]]: """ Return an ordered list of ancestor names for the supplied slot or class @param definition: Slot or class name...
python
{ "resource": "" }
q8241
Generator.neighborhood
train
def neighborhood(self, elements: List[ELEMENT_NAME]) \ -> References: """ Return a list of all slots, classes and types that touch any element in elements, including the element itself @param elements: Elements to do proximity with @return: All slots and classes that touch e...
python
{ "resource": "" }
q8242
Generator.grounded_slot_range
train
def grounded_slot_range(self, slot: Optional[Union[SlotDefinition, Optional[str]]]) -> str: """ Chase the slot range to its final form @param slot: slot to check @return: name of resolved range """ if slot is not None and not isinstance(slot, str): slot = slot.range ...
python
{ "resource": "" }
q8243
Generator.aliased_slot_names
train
def aliased_slot_names(self, slot_names: List[SlotDefinitionName]) -> Set[str]: """ Return the aliased slot names for all members of the list @param slot_names: actual slot names @return: aliases w/ duplicates removed """ return {self.aliased_slot_name(sn) for sn in slot_names}
python
{ "resource": "" }
q8244
Generator.obj_for
train
def obj_for(self, obj_or_name: Union[str, Element]) -> Optional[Union[str, Element]]: """ Return the class, slot or type that represents name or name itself if it is a builtin @param obj_or_name: Object or name @return: Corresponding element or None if not found (most likely cause is that it is...
python
{ "resource": "" }
q8245
Generator.obj_name
train
def obj_name(self, obj: Union[str, Element]) -> str: """ Return the formatted name used for the supplied definition """ if isinstance(obj, str): obj = self.obj_for(obj) if isinstance(obj, SlotDefinition): return underscore(self.aliased_slot_name(obj)) else: ...
python
{ "resource": "" }
q8246
PythonGenerator.gen_inherited
train
def gen_inherited(self) -> str: """ Generate the list of slot properties that are inherited across slot_usage or is_a paths """ inherited_head = 'inherited_slots: List[str] = [' inherited_slots = ', '.join([f'"{underscore(slot.name)}"' for slot in self.schema.slots.values() ...
python
{ "resource": "" }
q8247
PythonGenerator.gen_typedefs
train
def gen_typedefs(self) -> str: """ Generate python type declarations for all defined types """ rval = [] for typ in self.schema.types.values(): typname = self.python_name_for(typ.name) parent = self.python_name_for(typ.typeof) rval.append(f'class {typname}({pa...
python
{ "resource": "" }
q8248
PythonGenerator.gen_classdefs
train
def gen_classdefs(self) -> str: """ Create class definitions for all non-mixin classes in the model Note that apply_to classes are transformed to mixins """ return '\n'.join([self.gen_classdef(k, v) for k, v in self.schema.classes.items() if not v.mixin])
python
{ "resource": "" }
q8249
PythonGenerator.gen_classdef
train
def gen_classdef(self, clsname: str, cls: ClassDefinition) -> str: """ Generate python definition for class clsname """ parentref = f'({self.python_name_for(cls.is_a) if cls.is_a else "YAMLRoot"})' slotdefs = self.gen_slot_variables(cls) postinits = self.gen_postinits(cls) if no...
python
{ "resource": "" }
q8250
PythonGenerator.gen_slot_variables
train
def gen_slot_variables(self, cls: ClassDefinition) -> str: """ Generate python definition for class cls, generating primary keys first followed by the rest of the slots """ return '\n\t'.join([self.gen_slot_variable(cls, pk) for pk in self.primary_keys_for(cls)] + [sel...
python
{ "resource": "" }
q8251
PythonGenerator.gen_slot_variable
train
def gen_slot_variable(self, cls: ClassDefinition, slotname: str) -> str: """ Generate a slot variable for slotname as defined in class """ slot = self.schema.slots[slotname] # Alias allows re-use of slot names in different contexts if slot.alias: slotname = slot.alia...
python
{ "resource": "" }
q8252
PythonGenerator.gen_postinits
train
def gen_postinits(self, cls: ClassDefinition) -> str: """ Generate all the typing and existence checks post initialize """ post_inits = [] if not cls.abstract: pkeys = self.primary_keys_for(cls) for pkey in pkeys: post_inits.append(self.gen_postini...
python
{ "resource": "" }
q8253
PythonGenerator.gen_postinit
train
def gen_postinit(self, cls: ClassDefinition, slotname: str) -> Optional[str]: """ Generate python post init rules for slot in class """ rlines: List[str] = [] slot = self.schema.slots[slotname] if slot.alias: slotname = slot.alias slotname = self.python_name_f...
python
{ "resource": "" }
q8254
PythonGenerator.all_slots_for
train
def all_slots_for(self, cls: ClassDefinition) -> List[SlotDefinitionName]: """ Return all slots for class cls """ if not cls.is_a: return cls.slots else: return [sn for sn in self.all_slots_for(self.schema.classes[cls.is_a]) if sn not in cls.slot_usage] \ ...
python
{ "resource": "" }
q8255
PythonGenerator.range_type_name
train
def range_type_name(self, slot: SlotDefinition, containing_class_name: ClassDefinitionName) -> str: """ Generate the type name for the slot """ if slot.primary_key or slot.identifier: return self.python_name_for(containing_class_name) + camelcase(slot.name) if slot.range in self.sch...
python
{ "resource": "" }
q8256
PythonGenerator.forward_reference
train
def forward_reference(self, slot_range: str, owning_class: str) -> bool: """ Determine whether slot_range is a forward reference """ for cname in self.schema.classes: if cname == owning_class: return True # Occurs on or after elif cname == slot_range: ...
python
{ "resource": "" }
q8257
SchemaLoader.slot_definition_for
train
def slot_definition_for(self, slotname: SlotDefinitionName, cls: ClassDefinition) -> Optional[SlotDefinition]: """ Find the most proximal definition for slotname in the context of cls""" if cls.is_a: for sn in self.schema.classes[cls.is_a].slots: slot = self.schema.slots[sn] ...
python
{ "resource": "" }
q8258
cli
train
def cli(yamlfile, format, classes, directory): """ Generate a UML representation of a biolink model """ print(YumlGenerator(yamlfile, format).serialize(classes=classes, directory=directory), end="")
python
{ "resource": "" }
q8259
YumlGenerator.class_associations
train
def class_associations(self, cn: ClassDefinitionName, must_render: bool=False) -> str: """ Emit all associations for a focus class. If none are specified, all classes are generated @param cn: Name of class to be emitted @param must_render: True means render even if this is a target (class is s...
python
{ "resource": "" }
q8260
YumlGenerator.filtered_cls_slots
train
def filtered_cls_slots(self, cn: ClassDefinitionName, all_slots: bool=True) \ -> List[SlotDefinitionName]: """ Return the set of slots associated with the class that meet the filter criteria. Slots will be returned in defining order, with class slots returned last @param cn: name o...
python
{ "resource": "" }
q8261
cli
train
def cli(yamlfile, format, output, collections): """ Generate a ShEx Schema for a biolink model """ print(ShExGenerator(yamlfile, format).serialize(output=output, collections=collections))
python
{ "resource": "" }
q8262
ShExGenerator.gen_multivalued_slot
train
def gen_multivalued_slot(self, target_name_base: str, target_type: IRIREF) -> IRIREF: """ Generate a shape that represents an RDF list of target_type @param target_name_base: @param target_type: @return: """ list_shape_id = IRIREF(target_name_base + "__List") if ...
python
{ "resource": "" }
q8263
ContextGenerator.add_prefix
train
def add_prefix(self, ncname: str) -> None: """ Look up ncname and add it to the prefix map if necessary @param ncname: name to add """ if ncname not in self.prefixmap: uri = cu.expand_uri(ncname + ':', self.curi_maps) if uri and '://' in uri: self...
python
{ "resource": "" }
q8264
ContextGenerator.get_uri
train
def get_uri(self, ncname: str) -> Optional[str]: """ Get the URI associated with ncname @param ncname: """ uri = cu.expand_uri(ncname + ':', self.curi_maps) return uri if uri and uri.startswith('http') else None
python
{ "resource": "" }
q8265
ContextGenerator.add_mappings
train
def add_mappings(self, defn: Definition, target: Dict) -> None: """ Process any mappings in defn, adding all of the mappings prefixes to the namespace map and add a link to the first mapping to the target @param defn: Class or Slot definition @param target: context target """ ...
python
{ "resource": "" }
q8266
parse
train
def parse(text): """Parse the given text into metadata and strip it for a Markdown parser. :param text: text to be parsed """ rv = {} m = META.match(text) while m: key = m.group(1) value = m.group(2) value = INDENTATION.sub('\n', value.strip()) rv[key] = value ...
python
{ "resource": "" }
q8267
get_dir_walker
train
def get_dir_walker(recursive, topdown=True, followlinks=False): """ Returns a recursive or a non-recursive directory walker. :param recursive: ``True`` produces a recursive walker; ``False`` produces a non-recursive walker. :returns: A walker function. """ if recursive: ...
python
{ "resource": "" }
q8268
listdir
train
def listdir(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all items using their absolute paths in a directory, optionally recursively. :param dir_pathname: The directory to traverse. :param recursive: ``True`` for wal...
python
{ "resource": "" }
q8269
list_directories
train
def list_directories(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all the directories using their absolute paths within the specified directory, optionally recursively. :param dir_pathname: The directo...
python
{ "resource": "" }
q8270
list_files
train
def list_files(dir_pathname, recursive=True, topdown=True, followlinks=False): """ Enlists all the files using their absolute paths within the specified directory, optionally recursively. :param dir_pathname: The directory to traverse. :param rec...
python
{ "resource": "" }
q8271
match_path_against
train
def match_path_against(pathname, patterns, case_sensitive=True): """ Determines whether the pathname matches any of the given wildcard patterns, optionally ignoring the case of the pathname and patterns. :param pathname: A path name that will be matched against a wildcard pattern. :param pa...
python
{ "resource": "" }
q8272
match_path
train
def match_path(pathname, included_patterns=None, excluded_patterns=None, case_sensitive=True): """ Matches a pathname against a set of acceptable and ignored patterns. :param pathname: A pathname which will be matched against a pattern. :param includ...
python
{ "resource": "" }
q8273
match_any_paths
train
def match_any_paths(pathnames, included_patterns=None, excluded_patterns=None, case_sensitive=True): """ Matches from a set of paths based on acceptable patterns and ignorable patterns. :param pathnames: A list of path names that will ...
python
{ "resource": "" }
q8274
match_patterns
train
def match_patterns(pathname, patterns): """Returns ``True`` if the pathname matches any of the given patterns.""" for pattern in patterns: if fnmatch(pathname, pattern): return True return False
python
{ "resource": "" }
q8275
_get_team_info_raw
train
def _get_team_info_raw(soup, base_url, team_pattern, team, sport): """ Parses through html page to gather raw data about team :param soup: BeautifulSoup object containing html to be parsed :param base_url: Pre-formatted url that is formatted depending on sport :param team_pattern: Compiled regex pa...
python
{ "resource": "" }
q8276
_parse_match_info
train
def _parse_match_info(match, soccer=False): """ Parse string containing info of a specific match :param match: Match data :type match: string :param soccer: Set to true if match contains soccer data, defaults to False :type soccer: bool, optional :return: Dictionary containing match informa...
python
{ "resource": "" }
q8277
get_sport
train
def get_sport(sport): """ Get live scores for all matches in a particular sport :param sport: the sport being played :type sport: string :return: List containing Match objects :rtype: list """ sport = sport.lower() data = _request_xml(sport) matches = [] for match in data: ...
python
{ "resource": "" }
q8278
get_match
train
def get_match(sport, team1, team2): """ Get live scores for a single match :param sport: the sport being played :type sport: string :param team1: first team participating in the match :ttype team1: string :param team2: second team participating in the match :type team2: string :retu...
python
{ "resource": "" }
q8279
user_post_delete_handler
train
def user_post_delete_handler(sender, **kwargs): """Sends a metric to InfluxDB when a User object is deleted.""" total = get_user_model().objects.all().count() data = [{ 'measurement': 'django_auth_user_delete', 'tags': {'host': settings.INFLUXDB_TAGS_HOST, }, 'fields': {'value': 1, }...
python
{ "resource": "" }
q8280
user_post_save_handler
train
def user_post_save_handler(**kwargs): """Sends a metric to InfluxDB when a new User object is created.""" if kwargs.get('created'): total = get_user_model().objects.all().count() data = [{ 'measurement': 'django_auth_user_create', 'tags': {'host': settings.INFLUXDB_TAGS_H...
python
{ "resource": "" }
q8281
write_points
train
def write_points(data, force_disable_threading=False): """ Writes a series to influxdb. :param data: Array of dicts, as required by https://github.com/influxdb/influxdb-python :param force_disable_threading: When being called from the Celery task, we set this to `True` so that the user does...
python
{ "resource": "" }
q8282
_create_complete_graph
train
def _create_complete_graph(node_ids): """Create a complete graph from the list of node ids. Args: node_ids: a list of node ids Returns: An undirected graph (as a networkx.Graph) """ g = nx.Graph() g.add_nodes_from(node_ids) for (i, j) in combinations(node_ids, 2): g...
python
{ "resource": "" }
q8283
estimate_skeleton
train
def estimate_skeleton(indep_test_func, data_matrix, alpha, **kwargs): """Estimate a skeleton graph from the statistis information. Args: indep_test_func: the function name for a conditional independency test. data_matrix: data (as a numpy array). alpha: the significance leve...
python
{ "resource": "" }
q8284
set_high_water_mark
train
def set_high_water_mark(socket, config): """ Set a high water mark on the zmq socket. Do so in a way that is cross-compatible with zeromq2 and zeromq3. """ if config['high_water_mark']: if hasattr(zmq, 'HWM'): # zeromq2 socket.setsockopt(zmq.HWM, config['high_water_mark...
python
{ "resource": "" }
q8285
set_tcp_keepalive
train
def set_tcp_keepalive(socket, config): """ Set a series of TCP keepalive options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support We ran into a problem in FedoraInfrastructure where long-standing connectio...
python
{ "resource": "" }
q8286
set_tcp_reconnect
train
def set_tcp_reconnect(socket, config): """ Set a series of TCP reconnect options on the socket if and only if 1) they are specified explicitly in the config and 2) the version of pyzmq has been compiled with support Once our fedmsg bus grew to include many hundreds of endpoints, we started ...
python
{ "resource": "" }
q8287
dict_query
train
def dict_query(dic, query): """ Query a dict with 'dotted notation'. Returns an OrderedDict. A query of "foo.bar.baz" would retrieve 'wat' from this:: dic = { 'foo': { 'bar': { 'baz': 'wat', } } } Multiple querie...
python
{ "resource": "" }
q8288
cowsay_output
train
def cowsay_output(message): """ Invoke a shell command to print cowsay output. Primary replacement for os.system calls. """ command = 'cowsay "%s"' % message ret = subprocess.Popen( command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=...
python
{ "resource": "" }
q8289
expand
train
def expand(obj, relation, seen): """ Return the to_json or id of a sqlalchemy relationship. """ if hasattr(relation, 'all'): relation = relation.all() if hasattr(relation, '__iter__'): return [expand(obj, item, seen) for item in relation] if type(relation) not in seen: return ...
python
{ "resource": "" }
q8290
SigningRelayConsumer.consume
train
def consume(self, msg): """ Sign the message prior to sending the message. Args: msg (dict): The message to sign and relay. """ msg['body'] = crypto.sign(msg['body'], **self.hub.config) super(SigningRelayConsumer, self).consume(msg)
python
{ "resource": "" }
q8291
FedmsgConsumer._backlog
train
def _backlog(self, data): """Find all the datagrepper messages between 'then' and 'now'. Put those on our work queue. Should be called in a thread so as not to block the hub at startup. """ try: data = json.loads(data) except ValueError as e: se...
python
{ "resource": "" }
q8292
FedmsgConsumer.validate
train
def validate(self, message): """ Validate the message before the consumer processes it. This needs to raise an exception, caught by moksha. Args: message (dict): The message as a dictionary. This must, at a minimum, contain the 'topic' key with a unicode str...
python
{ "resource": "" }
q8293
FedmsgConsumer._consume
train
def _consume(self, message): """ Called when a message is consumed. This private method handles some administrative setup and teardown before calling the public interface `consume` typically implemented by a subclass. When `moksha.blocking_mode` is set to `False` in the config,...
python
{ "resource": "" }
q8294
ArgsList.files
train
def files(self, absolute=False): """Returns an expanded list of all valid paths that were passed in.""" _paths = [] for arg in self.all: for path in _expand_path(arg): if os.path.exists(path): if absolute: _paths.append(os...
python
{ "resource": "" }
q8295
ArgsList.assignments
train
def assignments(self): """Extracts assignment values from assignments.""" collection = OrderedDict() for arg in self.all: if '=' in arg: collection.setdefault( arg.split('=', 1)[0], ArgsList(no_argv=True)) collection[arg.split('='...
python
{ "resource": "" }
q8296
sign
train
def sign(message, gpg_home=None, gpg_signing_key=None, **config): """ Insert a new field into the message dict and return it. The new field is: - 'signature' - the computed GPG message digest of the JSON repr of the `msg` field. """ if gpg_home is None or gpg_signing_key is None: ...
python
{ "resource": "" }
q8297
FedMsgContext.destroy
train
def destroy(self): """ Destroy a fedmsg context """ if getattr(self, 'publisher', None): self.log.debug("closing fedmsg publisher") self.log.debug("sent %i messages" % self._i) self.publisher.close() self.publisher = None if getattr(self, 'contex...
python
{ "resource": "" }
q8298
FedMsgContext.publish
train
def publish(self, topic=None, msg=None, modname=None, pre_fire_hook=None, **kw): """ Send a message over the publishing zeromq socket. >>> import fedmsg >>> fedmsg.publish(topic='testing', modname='test', msg={ ... 'test': "Hello World", ...
python
{ "resource": "" }
q8299
_prep_crypto_msg
train
def _prep_crypto_msg(message): """Split the signature and certificate in the same way M2Crypto does. M2Crypto is dropping newlines into its signature and certificate. This exists purely to maintain backwards compatibility. Args: message (dict): A message with the ``signature`` and ``certificat...
python
{ "resource": "" }