repo
stringlengths
7
54
path
stringlengths
4
192
url
stringlengths
87
284
code
stringlengths
78
104k
code_tokens
list
docstring
stringlengths
1
46.9k
docstring_tokens
list
language
stringclasses
1 value
partition
stringclasses
3 values
ellmetha/django-machina
machina/apps/forum/abstract_models.py
https://github.com/ellmetha/django-machina/blob/89ac083c1eaf1cfdeae6686ee094cc86362e8c69/machina/apps/forum/abstract_models.py#L175-L195
def update_trackers(self): """ Updates the denormalized trackers associated with the forum instance. """ direct_approved_topics = self.topics.filter(approved=True).order_by('-last_post_on') # Compute the direct topics count and the direct posts count. self.direct_topics_count = direct_approved_topics.count() self.direct_posts_count = direct_approved_topics.aggregate( total_posts_count=Sum('posts_count'))['total_posts_count'] or 0 # Forces the forum's 'last_post' ID and 'last_post_on' date to the corresponding values # associated with the topic with the latest post. if direct_approved_topics.exists(): self.last_post_id = direct_approved_topics[0].last_post_id self.last_post_on = direct_approved_topics[0].last_post_on else: self.last_post_id = None self.last_post_on = None # Any save of a forum triggered from the update_tracker process will not result in checking # for a change of the forum's parent. self._simple_save()
[ "def", "update_trackers", "(", "self", ")", ":", "direct_approved_topics", "=", "self", ".", "topics", ".", "filter", "(", "approved", "=", "True", ")", ".", "order_by", "(", "'-last_post_on'", ")", "# Compute the direct topics count and the direct posts count.", "sel...
Updates the denormalized trackers associated with the forum instance.
[ "Updates", "the", "denormalized", "trackers", "associated", "with", "the", "forum", "instance", "." ]
python
train
AndrewAnnex/SpiceyPy
spiceypy/spiceypy.py
https://github.com/AndrewAnnex/SpiceyPy/blob/fc20a9b9de68b58eed5b332f0c051fb343a6e335/spiceypy/spiceypy.py#L13604-L13632
def surfpt(positn, u, a, b, c): """ Determine the intersection of a line-of-sight vector with the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfpt_c.html :param positn: Position of the observer in body-fixed frame. :type positn: 3-Element Array of floats :param u: Vector from the observer in some direction. :type u: 3-Element Array of floats :param a: Length of the ellisoid semi-axis along the x-axis. :type a: float :param b: Length of the ellisoid semi-axis along the y-axis. :type b: float :param c: Length of the ellisoid semi-axis along the z-axis. :type c: float :return: Point on the ellipsoid pointed to by u. :rtype: 3-Element Array of floats """ a = ctypes.c_double(a) b = ctypes.c_double(b) c = ctypes.c_double(c) positn = stypes.toDoubleVector(positn) u = stypes.toDoubleVector(u) point = stypes.emptyDoubleVector(3) found = ctypes.c_int() libspice.surfpt_c(positn, u, a, b, c, point, ctypes.byref(found)) return stypes.cVectorToPython(point), bool(found.value)
[ "def", "surfpt", "(", "positn", ",", "u", ",", "a", ",", "b", ",", "c", ")", ":", "a", "=", "ctypes", ".", "c_double", "(", "a", ")", "b", "=", "ctypes", ".", "c_double", "(", "b", ")", "c", "=", "ctypes", ".", "c_double", "(", "c", ")", "p...
Determine the intersection of a line-of-sight vector with the surface of an ellipsoid. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/surfpt_c.html :param positn: Position of the observer in body-fixed frame. :type positn: 3-Element Array of floats :param u: Vector from the observer in some direction. :type u: 3-Element Array of floats :param a: Length of the ellisoid semi-axis along the x-axis. :type a: float :param b: Length of the ellisoid semi-axis along the y-axis. :type b: float :param c: Length of the ellisoid semi-axis along the z-axis. :type c: float :return: Point on the ellipsoid pointed to by u. :rtype: 3-Element Array of floats
[ "Determine", "the", "intersection", "of", "a", "line", "-", "of", "-", "sight", "vector", "with", "the", "surface", "of", "an", "ellipsoid", "." ]
python
train
iotile/coretools
iotilebuild/iotile/build/build/build.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilebuild/iotile/build/build/build.py#L311-L320
def validate_target(self, target): """Make sure that the specified target only contains architectures that we know about.""" archs = target.split('/') for arch in archs: if not arch in self.archs: return False return True
[ "def", "validate_target", "(", "self", ",", "target", ")", ":", "archs", "=", "target", ".", "split", "(", "'/'", ")", "for", "arch", "in", "archs", ":", "if", "not", "arch", "in", "self", ".", "archs", ":", "return", "False", "return", "True" ]
Make sure that the specified target only contains architectures that we know about.
[ "Make", "sure", "that", "the", "specified", "target", "only", "contains", "architectures", "that", "we", "know", "about", "." ]
python
train
googledatalab/pydatalab
datalab/utils/commands/_utils.py
https://github.com/googledatalab/pydatalab/blob/d9031901d5bca22fe0d5925d204e6698df9852e1/datalab/utils/commands/_utils.py#L284-L310
def replace_vars(config, env): """ Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env. """ if isinstance(config, dict): for k, v in list(config.items()): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env) elif isinstance(v, basestring): config[k] = expand_var(v, env) elif isinstance(config, list): for i, v in enumerate(config): if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env) elif isinstance(v, basestring): config[i] = expand_var(v, env) elif isinstance(config, tuple): # TODO(gram): figure out how to handle these if the tuple elements are scalar for v in config: if isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple): replace_vars(v, env)
[ "def", "replace_vars", "(", "config", ",", "env", ")", ":", "if", "isinstance", "(", "config", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "list", "(", "config", ".", "items", "(", ")", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ...
Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env.
[ "Replace", "variable", "references", "in", "config", "using", "the", "supplied", "env", "dictionary", "." ]
python
train
openego/eDisGo
edisgo/grid/tools.py
https://github.com/openego/eDisGo/blob/e6245bdaf236f9c49dbda5a18c1c458290f41e2b/edisgo/grid/tools.py#L362-L452
def get_gen_info(network, level='mvlv', fluctuating=False): """ Gets all the installed generators with some additional information. Parameters ---------- network : :class:`~.grid.network.Network` Network object holding the grid data. level : :obj:`str` Defines which generators are returned. Possible options are: * 'mv' Only generators connected to the MV grid are returned. * 'lv' Only generators connected to the LV grids are returned. * 'mvlv' All generators connected to the MV grid and LV grids are returned. Default: 'mvlv'. fluctuating : :obj:`bool` If True only returns fluctuating generators. Default: False. Returns -------- :pandas:`pandas.DataFrame<dataframe>` Dataframe with all generators connected to the specified voltage level. Index of the dataframe are the generator objects of type :class:`~.grid.components.Generator`. Columns of the dataframe are: * 'gen_repr' The representative of the generator as :obj:`str`. * 'type' The generator type, e.g. 'solar' or 'wind' as :obj:`str`. * 'voltage_level' The voltage level the generator is connected to as :obj:`str`. Can either be 'mv' or 'lv'. * 'nominal_capacity' The nominal capacity of the generator as as :obj:`float`. * 'weather_cell_id' The id of the weather cell the generator is located in as :obj:`int` (only applies to fluctuating generators). """ gens_w_id = [] if 'mv' in level: gens = network.mv_grid.generators gens_voltage_level = ['mv']*len(gens) gens_type = [gen.type for gen in gens] gens_rating = [gen.nominal_capacity for gen in gens] for gen in gens: try: gens_w_id.append(gen.weather_cell_id) except AttributeError: gens_w_id.append(np.nan) gens_grid = [network.mv_grid]*len(gens) else: gens = [] gens_voltage_level = [] gens_type = [] gens_rating = [] gens_grid = [] if 'lv' in level: for lv_grid in network.mv_grid.lv_grids: gens_lv = lv_grid.generators gens.extend(gens_lv) gens_voltage_level.extend(['lv']*len(gens_lv)) gens_type.extend([gen.type for gen in gens_lv]) gens_rating.extend([gen.nominal_capacity for gen in gens_lv]) for gen in gens_lv: try: gens_w_id.append(gen.weather_cell_id) except AttributeError: gens_w_id.append(np.nan) gens_grid.extend([lv_grid] * len(gens_lv)) gen_df = pd.DataFrame({'gen_repr': list(map(lambda x: repr(x), gens)), 'generator': gens, 'type': gens_type, 'voltage_level': gens_voltage_level, 'nominal_capacity': gens_rating, 'weather_cell_id': gens_w_id, 'grid': gens_grid}) gen_df.set_index('generator', inplace=True, drop=True) # filter fluctuating generators if fluctuating: gen_df = gen_df.loc[(gen_df.type == 'solar') | (gen_df.type == 'wind')] return gen_df
[ "def", "get_gen_info", "(", "network", ",", "level", "=", "'mvlv'", ",", "fluctuating", "=", "False", ")", ":", "gens_w_id", "=", "[", "]", "if", "'mv'", "in", "level", ":", "gens", "=", "network", ".", "mv_grid", ".", "generators", "gens_voltage_level", ...
Gets all the installed generators with some additional information. Parameters ---------- network : :class:`~.grid.network.Network` Network object holding the grid data. level : :obj:`str` Defines which generators are returned. Possible options are: * 'mv' Only generators connected to the MV grid are returned. * 'lv' Only generators connected to the LV grids are returned. * 'mvlv' All generators connected to the MV grid and LV grids are returned. Default: 'mvlv'. fluctuating : :obj:`bool` If True only returns fluctuating generators. Default: False. Returns -------- :pandas:`pandas.DataFrame<dataframe>` Dataframe with all generators connected to the specified voltage level. Index of the dataframe are the generator objects of type :class:`~.grid.components.Generator`. Columns of the dataframe are: * 'gen_repr' The representative of the generator as :obj:`str`. * 'type' The generator type, e.g. 'solar' or 'wind' as :obj:`str`. * 'voltage_level' The voltage level the generator is connected to as :obj:`str`. Can either be 'mv' or 'lv'. * 'nominal_capacity' The nominal capacity of the generator as as :obj:`float`. * 'weather_cell_id' The id of the weather cell the generator is located in as :obj:`int` (only applies to fluctuating generators).
[ "Gets", "all", "the", "installed", "generators", "with", "some", "additional", "information", "." ]
python
train
cloud9ers/pylxc
lxc/__init__.py
https://github.com/cloud9ers/pylxc/blob/588961dd37ce6e14fd7c1cc76d1970e48fccba34/lxc/__init__.py#L265-L272
def freeze(name): ''' freezes the container ''' if not exists(name): raise ContainerNotExists("The container (%s) does not exist!" % name) cmd = ['lxc-freeze', '-n', name] subprocess.check_call(cmd)
[ "def", "freeze", "(", "name", ")", ":", "if", "not", "exists", "(", "name", ")", ":", "raise", "ContainerNotExists", "(", "\"The container (%s) does not exist!\"", "%", "name", ")", "cmd", "=", "[", "'lxc-freeze'", ",", "'-n'", ",", "name", "]", "subprocess"...
freezes the container
[ "freezes", "the", "container" ]
python
train
common-workflow-language/cwltool
cwltool/utils.py
https://github.com/common-workflow-language/cwltool/blob/cb81b22abc52838823da9945f04d06739ab32fda/cwltool/utils.py#L112-L127
def docker_windows_reverse_fileuri_adjust(fileuri): # type: (Text) -> (Text) r""" On docker in windows fileuri do not contain : in path To convert this file uri to windows compatible add : after drive letter, so file:///E/var becomes file:///E:/var """ if fileuri is not None and onWindows(): if urllib.parse.urlsplit(fileuri).scheme == "file": filesplit = fileuri.split("/") if filesplit[3][-1] != ':': filesplit[3] = filesplit[3]+':' return '/'.join(filesplit) return fileuri raise ValueError("not a file URI") return fileuri
[ "def", "docker_windows_reverse_fileuri_adjust", "(", "fileuri", ")", ":", "# type: (Text) -> (Text)", "if", "fileuri", "is", "not", "None", "and", "onWindows", "(", ")", ":", "if", "urllib", ".", "parse", ".", "urlsplit", "(", "fileuri", ")", ".", "scheme", "=...
r""" On docker in windows fileuri do not contain : in path To convert this file uri to windows compatible add : after drive letter, so file:///E/var becomes file:///E:/var
[ "r", "On", "docker", "in", "windows", "fileuri", "do", "not", "contain", ":", "in", "path", "To", "convert", "this", "file", "uri", "to", "windows", "compatible", "add", ":", "after", "drive", "letter", "so", "file", ":", "///", "E", "/", "var", "becom...
python
train
mosdef-hub/mbuild
mbuild/compound.py
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1825-L1877
def from_trajectory(self, traj, frame=-1, coords_only=False): """Extract atoms and bonds from a md.Trajectory. Will create sub-compounds for every chain if there is more than one and sub-sub-compounds for every residue. Parameters ---------- traj : mdtraj.Trajectory The trajectory to load. frame : int, optional, default=-1 (last) The frame to take coordinates from. coords_only : bool, optional, default=False Only read coordinate information """ if coords_only: if traj.n_atoms != self.n_particles: raise ValueError('Number of atoms in {traj} does not match' ' {self}'.format(**locals())) atoms_particles = zip(traj.topology.atoms, self.particles(include_ports=False)) if None in self._particles(include_ports=False): raise ValueError('Some particles are None') for mdtraj_atom, particle in atoms_particles: particle.pos = traj.xyz[frame, mdtraj_atom.index] return atom_mapping = dict() for chain in traj.topology.chains: if traj.topology.n_chains > 1: chain_compound = Compound() self.add(chain_compound, 'chain[$]') else: chain_compound = self for res in chain.residues: for atom in res.atoms: new_atom = Particle(name=str(atom.name), pos=traj.xyz[frame, atom.index]) chain_compound.add( new_atom, label='{0}[$]'.format( atom.name)) atom_mapping[atom] = new_atom for mdtraj_atom1, mdtraj_atom2 in traj.topology.bonds: atom1 = atom_mapping[mdtraj_atom1] atom2 = atom_mapping[mdtraj_atom2] self.add_bond((atom1, atom2)) if np.any(traj.unitcell_lengths) and np.any(traj.unitcell_lengths[0]): self.periodicity = traj.unitcell_lengths[0] else: self.periodicity = np.array([0., 0., 0.])
[ "def", "from_trajectory", "(", "self", ",", "traj", ",", "frame", "=", "-", "1", ",", "coords_only", "=", "False", ")", ":", "if", "coords_only", ":", "if", "traj", ".", "n_atoms", "!=", "self", ".", "n_particles", ":", "raise", "ValueError", "(", "'Nu...
Extract atoms and bonds from a md.Trajectory. Will create sub-compounds for every chain if there is more than one and sub-sub-compounds for every residue. Parameters ---------- traj : mdtraj.Trajectory The trajectory to load. frame : int, optional, default=-1 (last) The frame to take coordinates from. coords_only : bool, optional, default=False Only read coordinate information
[ "Extract", "atoms", "and", "bonds", "from", "a", "md", ".", "Trajectory", "." ]
python
train
dcos/shakedown
shakedown/dcos/package.py
https://github.com/dcos/shakedown/blob/e2f9e2382788dbcd29bd18aa058b76e7c3b83b3e/shakedown/dcos/package.py#L46-L144
def install_package( package_name, package_version=None, service_name=None, options_file=None, options_json=None, wait_for_completion=False, timeout_sec=600, expected_running_tasks=0 ): """ Install a package via the DC/OS library :param package_name: name of the package :type package_name: str :param package_version: version of the package (defaults to latest) :type package_version: str :param service_name: unique service name for the package :type service_name: str :param options_file: filename that has options to use and is JSON format :type options_file: str :param options_json: dict that has options to use and is JSON format :type options_json: dict :param wait_for_completion: whether or not to wait for the app's deployment to complete :type wait_for_completion: bool :param timeout_sec: number of seconds to wait for task completion :type timeout_sec: int :param expected_running_tasks: number of service tasks to check for, or zero to disable :type expected_task_count: int :return: True if installation was successful, False otherwise :rtype: bool """ start = time.time() if options_file: options = _get_options(options_file) elif options_json: options = options_json else: options = {} package_manager = _get_package_manager() pkg = package_manager.get_package_version(package_name, package_version) if package_version is None: # Get the resolved version for logging below package_version = 'auto:{}'.format(pkg.version()) if service_name is None: # Get the service name from the marathon template try: labels = pkg.marathon_json(options).get('labels') if 'DCOS_SERVICE_NAME' in labels: service_name = labels['DCOS_SERVICE_NAME'] except errors.DCOSException as e: pass print('\n{}installing {} with service={} version={} options={}'.format( shakedown.cli.helpers.fchr('>>'), package_name, service_name, package_version, options)) try: # Print pre-install notes to console log pre_install_notes = pkg.package_json().get('preInstallNotes') if pre_install_notes: print(pre_install_notes) package_manager.install_app(pkg, options, service_name) # Print post-install notes to console log post_install_notes = pkg.package_json().get('postInstallNotes') if post_install_notes: print(post_install_notes) # Optionally wait for the app's deployment to finish if wait_for_completion: print("\n{}waiting for {} deployment to complete...".format( shakedown.cli.helpers.fchr('>>'), service_name)) if expected_running_tasks > 0 and service_name is not None: wait_for_service_tasks_running(service_name, expected_running_tasks, timeout_sec) app_id = pkg.marathon_json(options).get('id') shakedown.deployment_wait(timeout_sec, app_id) print('\n{}install completed after {}\n'.format( shakedown.cli.helpers.fchr('>>'), pretty_duration(time.time() - start))) else: print('\n{}install started after {}\n'.format( shakedown.cli.helpers.fchr('>>'), pretty_duration(time.time() - start))) except errors.DCOSException as e: print('\n{}{}'.format( shakedown.cli.helpers.fchr('>>'), e)) # Install subcommands (if defined) if pkg.cli_definition(): print("{}installing CLI commands for package '{}'".format( shakedown.cli.helpers.fchr('>>'), package_name)) subcommand.install(pkg) return True
[ "def", "install_package", "(", "package_name", ",", "package_version", "=", "None", ",", "service_name", "=", "None", ",", "options_file", "=", "None", ",", "options_json", "=", "None", ",", "wait_for_completion", "=", "False", ",", "timeout_sec", "=", "600", ...
Install a package via the DC/OS library :param package_name: name of the package :type package_name: str :param package_version: version of the package (defaults to latest) :type package_version: str :param service_name: unique service name for the package :type service_name: str :param options_file: filename that has options to use and is JSON format :type options_file: str :param options_json: dict that has options to use and is JSON format :type options_json: dict :param wait_for_completion: whether or not to wait for the app's deployment to complete :type wait_for_completion: bool :param timeout_sec: number of seconds to wait for task completion :type timeout_sec: int :param expected_running_tasks: number of service tasks to check for, or zero to disable :type expected_task_count: int :return: True if installation was successful, False otherwise :rtype: bool
[ "Install", "a", "package", "via", "the", "DC", "/", "OS", "library" ]
python
train
google/prettytensor
prettytensor/pretty_tensor_class.py
https://github.com/google/prettytensor/blob/75daa0b11252590f548da5647addc0ea610c4c45/prettytensor/pretty_tensor_class.py#L303-L325
def join_pretty_tensors(tensors, output, join_function=None, name='join'): """Joins the list of pretty_tensors and sets head of output_pretty_tensor. Args: tensors: A sequence of Layers or SequentialLayerBuilders to join. output: A pretty_tensor to set the head with the result. join_function: A function to join the tensors, defaults to concat on the last dimension. name: A name that is used for the name_scope Returns: The result of calling with_tensor on output Raises: ValueError: if pretty_tensors is None or empty. """ if not tensors: raise ValueError('pretty_tensors must be a non-empty sequence.') with output.g.name_scope(name): if join_function is None: # Use depth concat last_dim = len(tensors[0].shape) - 1 return output.with_tensor(tf.concat(tensors, last_dim)) else: return output.with_tensor(join_function(tensors))
[ "def", "join_pretty_tensors", "(", "tensors", ",", "output", ",", "join_function", "=", "None", ",", "name", "=", "'join'", ")", ":", "if", "not", "tensors", ":", "raise", "ValueError", "(", "'pretty_tensors must be a non-empty sequence.'", ")", "with", "output", ...
Joins the list of pretty_tensors and sets head of output_pretty_tensor. Args: tensors: A sequence of Layers or SequentialLayerBuilders to join. output: A pretty_tensor to set the head with the result. join_function: A function to join the tensors, defaults to concat on the last dimension. name: A name that is used for the name_scope Returns: The result of calling with_tensor on output Raises: ValueError: if pretty_tensors is None or empty.
[ "Joins", "the", "list", "of", "pretty_tensors", "and", "sets", "head", "of", "output_pretty_tensor", "." ]
python
train
proycon/clam
clam/common/data.py
https://github.com/proycon/clam/blob/09d15cfc26d7cbe0f5976cdd5424dc446d10dbf3/clam/common/data.py#L1889-L1963
def generate(self, profile, parameters, projectpath, inputfiles, provenancedata=None): """Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples""" project = os.path.basename(projectpath) if self.parent: #pylint: disable=too-many-nested-blocks #We have a parent, infer the correct filename #copy filename from parent parent = self.getparent(profile) #get input files for the parent InputTemplate parentinputfiles = parent.matchingfiles(projectpath) if not parentinputfiles: raise Exception("OutputTemplate '"+self.id + "' has parent '" + self.parent + "', but no matching input files were found!") #Do we specify a full filename? for seqnr, inputfilename, inputtemplate in parentinputfiles: #pylint: disable=unused-variable if self.filename: filename = self.filename parentfile = CLAMInputFile(projectpath, inputfilename) elif parent: filename = inputfilename parentfile = CLAMInputFile(projectpath, inputfilename) else: raise Exception("OutputTemplate '"+self.id + "' has no parent nor filename defined!") #Make actual CLAMInputFile objects of ALL relevant input files, that is: all unique=True files and all unique=False files with the same sequence number relevantinputfiles = [] for seqnr2, inputfilename2, inputtemplate2 in inputfiles: if seqnr2 == 0 or seqnr2 == seqnr: relevantinputfiles.append( (inputtemplate2, CLAMInputFile(projectpath, inputfilename2)) ) #resolve # in filename (done later) #if not self.unique: # filename.replace('#',str(seqnr)) if not self.filename and self.removeextensions: #Remove unwanted extensions if self.removeextensions is True: #Remove any and all extensions filename = filename.split('.')[0] elif isinstance(self.removeextensions, list): #Remove specified extension for ext in self.removeextensions: if ext: if ext[0] != '.' and filename[-len(ext) - 1:] == '.' + ext: filename = filename[:-len(ext) - 1] elif ext[0] == '.' and filename[-len(ext):] == ext: filename = filename[:-len(ext)] if self.extension and not self.filename and filename[-len(self.extension) - 1:] != '.' + self.extension: #(also prevents duplicate extensions) filename += '.' + self.extension #Now we create the actual metadata metadata = self.generatemetadata(parameters, parentfile, relevantinputfiles, provenancedata) #Resolve filename filename = resolveoutputfilename(filename, parameters, metadata, self, seqnr, project, inputfilename) yield inputtemplate, inputfilename, filename, metadata elif self.unique and self.filename: #outputtemplate has no parent, but specified a filename and is unique, this implies it is not dependent on input files: metadata = self.generatemetadata(parameters, None, [], provenancedata) filename = resolveoutputfilename(self.filename, parameters, metadata, self, 0, project, None) yield None, None, filename, metadata else: raise Exception("Unable to generate from OutputTemplate, no parent or filename specified")
[ "def", "generate", "(", "self", ",", "profile", ",", "parameters", ",", "projectpath", ",", "inputfiles", ",", "provenancedata", "=", "None", ")", ":", "project", "=", "os", ".", "path", ".", "basename", "(", "projectpath", ")", "if", "self", ".", "paren...
Yields (inputtemplate, inputfilename, outputfilename, metadata) tuples
[ "Yields", "(", "inputtemplate", "inputfilename", "outputfilename", "metadata", ")", "tuples" ]
python
train
SeleniumHQ/selenium
py/selenium/webdriver/common/action_chains.py
https://github.com/SeleniumHQ/selenium/blob/df40c28b41d4b3953f90eaff84838a9ac052b84a/py/selenium/webdriver/common/action_chains.py#L112-L128
def click_and_hold(self, on_element=None): """ Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on current mouse position. """ if on_element: self.move_to_element(on_element) if self._driver.w3c: self.w3c_actions.pointer_action.click_and_hold() self.w3c_actions.key_action.pause() else: self._actions.append(lambda: self._driver.execute( Command.MOUSE_DOWN, {})) return self
[ "def", "click_and_hold", "(", "self", ",", "on_element", "=", "None", ")", ":", "if", "on_element", ":", "self", ".", "move_to_element", "(", "on_element", ")", "if", "self", ".", "_driver", ".", "w3c", ":", "self", ".", "w3c_actions", ".", "pointer_action...
Holds down the left mouse button on an element. :Args: - on_element: The element to mouse down. If None, clicks on current mouse position.
[ "Holds", "down", "the", "left", "mouse", "button", "on", "an", "element", "." ]
python
train
codeinthehole/purl
purl/url.py
https://github.com/codeinthehole/purl/blob/e70ed132f1fdc17d00c78199cedb1e3adcb2bc55/purl/url.py#L100-L129
def parse(url_str): """ Extract all parts from a URL string and return them as a dictionary """ url_str = to_unicode(url_str) result = urlparse(url_str) netloc_parts = result.netloc.rsplit('@', 1) if len(netloc_parts) == 1: username = password = None host = netloc_parts[0] else: user_and_pass = netloc_parts[0].split(':') if len(user_and_pass) == 2: username, password = user_and_pass elif len(user_and_pass) == 1: username = user_and_pass[0] password = None host = netloc_parts[1] if host and ':' in host: host = host.split(':')[0] return {'host': host, 'username': username, 'password': password, 'scheme': result.scheme, 'port': result.port, 'path': result.path, 'query': result.query, 'fragment': result.fragment}
[ "def", "parse", "(", "url_str", ")", ":", "url_str", "=", "to_unicode", "(", "url_str", ")", "result", "=", "urlparse", "(", "url_str", ")", "netloc_parts", "=", "result", ".", "netloc", ".", "rsplit", "(", "'@'", ",", "1", ")", "if", "len", "(", "ne...
Extract all parts from a URL string and return them as a dictionary
[ "Extract", "all", "parts", "from", "a", "URL", "string", "and", "return", "them", "as", "a", "dictionary" ]
python
train
saltstack/salt
salt/modules/aptly.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/aptly.py#L295-L344
def new_repo(name, config_path=_DEFAULT_CONFIG_PATH, comment=None, component=None, distribution=None, uploaders_file=None, from_snapshot=None, saltenv='base'): ''' Create a new local package repository. :param str name: The name of the local repository. :param str config_path: The path to the configuration file for the aptly instance. :param str comment: The description of the repository. :param str component: The default component to use when publishing. :param str distribution: The default distribution to use when publishing. :param str uploaders_file: The repository upload restrictions config. :param str from_snapshot: The snapshot to initialize the repository contents from. :param str saltenv: The environment the file resides in. :return: A boolean representing whether all changes succeeded. :rtype: bool CLI Example: .. code-block:: bash salt '*' aptly.new_repo name="test-repo" comment="Test main repo" component="main" distribution="trusty" ''' _validate_config(config_path) current_repo = __salt__['aptly.get_repo'](name=name, config_path=config_path) if current_repo: log.debug('Repository already exists: %s', name) return True cmd = ['repo', 'create', '-config={}'.format(config_path)] repo_params = _format_repo_args(comment=comment, component=component, distribution=distribution, uploaders_file=uploaders_file, saltenv=saltenv) cmd.extend(repo_params) cmd.append(name) if from_snapshot: cmd.extend(['from', 'snapshot', from_snapshot]) _cmd_run(cmd) repo = __salt__['aptly.get_repo'](name=name, config_path=config_path) if repo: log.debug('Created repo: %s', name) return True log.error('Unable to create repo: %s', name) return False
[ "def", "new_repo", "(", "name", ",", "config_path", "=", "_DEFAULT_CONFIG_PATH", ",", "comment", "=", "None", ",", "component", "=", "None", ",", "distribution", "=", "None", ",", "uploaders_file", "=", "None", ",", "from_snapshot", "=", "None", ",", "salten...
Create a new local package repository. :param str name: The name of the local repository. :param str config_path: The path to the configuration file for the aptly instance. :param str comment: The description of the repository. :param str component: The default component to use when publishing. :param str distribution: The default distribution to use when publishing. :param str uploaders_file: The repository upload restrictions config. :param str from_snapshot: The snapshot to initialize the repository contents from. :param str saltenv: The environment the file resides in. :return: A boolean representing whether all changes succeeded. :rtype: bool CLI Example: .. code-block:: bash salt '*' aptly.new_repo name="test-repo" comment="Test main repo" component="main" distribution="trusty"
[ "Create", "a", "new", "local", "package", "repository", "." ]
python
train
marshmallow-code/apispec
src/apispec/ext/marshmallow/__init__.py
https://github.com/marshmallow-code/apispec/blob/e92ceffd12b2e392b8d199ed314bd2a7e6512dff/src/apispec/ext/marshmallow/__init__.py#L213-L222
def warn_if_schema_already_in_spec(self, schema_key): """Method to warn the user if the schema has already been added to the spec. """ if schema_key in self.openapi.refs: warnings.warn( "{} has already been added to the spec. Adding it twice may " "cause references to not resolve properly.".format(schema_key[0]), UserWarning, )
[ "def", "warn_if_schema_already_in_spec", "(", "self", ",", "schema_key", ")", ":", "if", "schema_key", "in", "self", ".", "openapi", ".", "refs", ":", "warnings", ".", "warn", "(", "\"{} has already been added to the spec. Adding it twice may \"", "\"cause references to n...
Method to warn the user if the schema has already been added to the spec.
[ "Method", "to", "warn", "the", "user", "if", "the", "schema", "has", "already", "been", "added", "to", "the", "spec", "." ]
python
train
Mindwerks/worldengine
worldengine/simulations/precipitation.py
https://github.com/Mindwerks/worldengine/blob/64dff8eb7824ce46b5b6cb8006bcef21822ef144/worldengine/simulations/precipitation.py#L33-L111
def _calculate(seed, world): """Precipitation is a value in [-1,1]""" rng = numpy.random.RandomState(seed) # create our own random generator base = rng.randint(0, 4096) curve_gamma = world.gamma_curve curve_bonus = world.curve_offset height = world.height width = world.width border = width / 4 precipitations = numpy.zeros((height, width), dtype=float) octaves = 6 freq = 64.0 * octaves n_scale = 1024 / float(height) #This is a variable I am adding. It exists #so that worlds sharing a common seed but #different sizes will have similar patterns for y in range(height):#TODO: numpy for x in range(width): n = snoise2((x * n_scale) / freq, (y * n_scale) / freq, octaves, base=base) # Added to allow noise pattern to wrap around right and left. if x < border: n = (snoise2( (x * n_scale) / freq, (y * n_scale) / freq, octaves, base=base) * x / border) + ( snoise2(( (x * n_scale) + width) / freq, (y * n_scale) / freq, octaves, base=base) * (border - x) / border) precipitations[y, x] = n #find ranges min_precip = precipitations.min() max_precip = precipitations.max() min_temp = world.layers['temperature'].min() max_temp = world.layers['temperature'].max() precip_delta = (max_precip - min_precip) temp_delta = (max_temp - min_temp) #normalize temperature and precipitation arrays t = (world.layers['temperature'].data - min_temp) / temp_delta p = (precipitations - min_precip) / precip_delta #modify precipitation based on temperature #-------------------------------------------------------------------------------- # # Ok, some explanation here because why the formula is doing this may be a # little confusing. We are going to generate a modified gamma curve based on # normalized temperature and multiply our precipitation amounts by it. # # numpy.power(t,curve_gamma) generates a standard gamma curve. However # we probably don't want to be multiplying precipitation by 0 at the far # side of the curve. To avoid this we multiply the curve by (1 - curve_bonus) # and then add back curve_bonus. Thus, if we have a curve bonus of .2 then # the range of our modified gamma curve goes from 0-1 to 0-.8 after we # multiply and then to .2-1 after we add back the curve_bonus. # # Because we renormalize there is not much point to offsetting the opposite end # of the curve so it is less than or more than 1. We are trying to avoid # setting the start of the curve to 0 because f(t) * p would equal 0 when t equals # 0. However f(t) * p does not automatically equal 1 when t equals 1 and if we # raise or lower the value for f(t) at 1 it would have negligible impact after # renormalizing. # #-------------------------------------------------------------------------------- curve = (numpy.power(t, curve_gamma) * (1-curve_bonus)) + curve_bonus precipitations = numpy.multiply(p, curve) #Renormalize precipitation because the precipitation #changes will probably not fully extend from -1 to 1. min_precip = precipitations.min() max_precip = precipitations.max() precip_delta = (max_precip - min_precip) precipitations = (((precipitations - min_precip) / precip_delta) * 2) - 1 return precipitations
[ "def", "_calculate", "(", "seed", ",", "world", ")", ":", "rng", "=", "numpy", ".", "random", ".", "RandomState", "(", "seed", ")", "# create our own random generator", "base", "=", "rng", ".", "randint", "(", "0", ",", "4096", ")", "curve_gamma", "=", "...
Precipitation is a value in [-1,1]
[ "Precipitation", "is", "a", "value", "in", "[", "-", "1", "1", "]" ]
python
train
timothydmorton/obliquity
obliquity/kappa_inference.py
https://github.com/timothydmorton/obliquity/blob/ae0a237ae2ca7ba0f7c71f0ee391f52e809da235/obliquity/kappa_inference.py#L46-L49
def cosi_pdf(z,k=1): """Equation (11) of Morton & Winn (2014) """ return 2*k/(np.pi*np.sinh(k)) * quad(cosi_integrand,z,1,args=(k,z))[0]
[ "def", "cosi_pdf", "(", "z", ",", "k", "=", "1", ")", ":", "return", "2", "*", "k", "/", "(", "np", ".", "pi", "*", "np", ".", "sinh", "(", "k", ")", ")", "*", "quad", "(", "cosi_integrand", ",", "z", ",", "1", ",", "args", "=", "(", "k",...
Equation (11) of Morton & Winn (2014)
[ "Equation", "(", "11", ")", "of", "Morton", "&", "Winn", "(", "2014", ")" ]
python
train
glyph/txsni
txsni/snimap.py
https://github.com/glyph/txsni/blob/5014c141a7acef63e20fcf6c36fa07f0cd754ce1/txsni/snimap.py#L56-L62
def get_context(self): """ A basic override of get_context to ensure that the appropriate proxy object is returned. """ ctx = self._obj.get_context() return _ContextProxy(ctx, self._factory)
[ "def", "get_context", "(", "self", ")", ":", "ctx", "=", "self", ".", "_obj", ".", "get_context", "(", ")", "return", "_ContextProxy", "(", "ctx", ",", "self", ".", "_factory", ")" ]
A basic override of get_context to ensure that the appropriate proxy object is returned.
[ "A", "basic", "override", "of", "get_context", "to", "ensure", "that", "the", "appropriate", "proxy", "object", "is", "returned", "." ]
python
train
nugget/python-anthemav
anthemav/tools.py
https://github.com/nugget/python-anthemav/blob/c3cee38f2d452c1ab1335d9885e0769ec24d5f90/anthemav/tools.py#L60-L65
def monitor(): """Wrapper to call console with a loop.""" log = logging.getLogger(__name__) loop = asyncio.get_event_loop() asyncio.ensure_future(console(loop, log)) loop.run_forever()
[ "def", "monitor", "(", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "asyncio", ".", "ensure_future", "(", "console", "(", "loop", ",", "log", ")", ")", "loop", ".", ...
Wrapper to call console with a loop.
[ "Wrapper", "to", "call", "console", "with", "a", "loop", "." ]
python
train
tradenity/python-sdk
tradenity/resources/brand.py
https://github.com/tradenity/python-sdk/blob/d13fbe23f4d6ff22554c6d8d2deaf209371adaf1/tradenity/resources/brand.py#L500-L520
def get_brand_by_id(cls, brand_id, **kwargs): """Find Brand Return single instance of Brand by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_brand_by_id(brand_id, async=True) >>> result = thread.get() :param async bool :param str brand_id: ID of brand to return (required) :return: Brand If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async'): return cls._get_brand_by_id_with_http_info(brand_id, **kwargs) else: (data) = cls._get_brand_by_id_with_http_info(brand_id, **kwargs) return data
[ "def", "get_brand_by_id", "(", "cls", ",", "brand_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_get_brand_by_id_with_http_inf...
Find Brand Return single instance of Brand by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.get_brand_by_id(brand_id, async=True) >>> result = thread.get() :param async bool :param str brand_id: ID of brand to return (required) :return: Brand If the method is called asynchronously, returns the request thread.
[ "Find", "Brand" ]
python
train
ktbyers/netmiko
netmiko/fortinet/fortinet_ssh.py
https://github.com/ktbyers/netmiko/blob/54e6116c0b4664de2123081937e0a9a27bdfdfea/netmiko/fortinet/fortinet_ssh.py#L74-L84
def cleanup(self): """Re-enable paging globally.""" if self.allow_disable_global: # Return paging state output_mode_cmd = "set output {}".format(self._output_mode) enable_paging_commands = ["config system console", output_mode_cmd, "end"] if self.vdoms: enable_paging_commands.insert(0, "config global") # Should test output is valid for command in enable_paging_commands: self.send_command_timing(command)
[ "def", "cleanup", "(", "self", ")", ":", "if", "self", ".", "allow_disable_global", ":", "# Return paging state", "output_mode_cmd", "=", "\"set output {}\"", ".", "format", "(", "self", ".", "_output_mode", ")", "enable_paging_commands", "=", "[", "\"config system ...
Re-enable paging globally.
[ "Re", "-", "enable", "paging", "globally", "." ]
python
train
juju-solutions/jujuresources
jujuresources/backend.py
https://github.com/juju-solutions/jujuresources/blob/7d2c5f50981784cc4b5cde216b930f6d59c951a4/jujuresources/backend.py#L65-L74
def get(cls, name, definition, output_dir): """ Dispatch to the right subclass based on the definition. """ if 'url' in definition: return URLResource(name, definition, output_dir) elif 'pypi' in definition: return PyPIResource(name, definition, output_dir) else: return Resource(name, definition, output_dir)
[ "def", "get", "(", "cls", ",", "name", ",", "definition", ",", "output_dir", ")", ":", "if", "'url'", "in", "definition", ":", "return", "URLResource", "(", "name", ",", "definition", ",", "output_dir", ")", "elif", "'pypi'", "in", "definition", ":", "re...
Dispatch to the right subclass based on the definition.
[ "Dispatch", "to", "the", "right", "subclass", "based", "on", "the", "definition", "." ]
python
train
kipe/enocean
enocean/decorators.py
https://github.com/kipe/enocean/blob/99fa03f47004eef74c7987545c33ecd01af0de07/enocean/decorators.py#L8-L38
def timing(rounds=1, limit=None): ''' Wrapper to implement simple timing of tests. Allows running multiple rounds to calculate average time. Limit (in milliseconds) can be set to assert, if (average) duration is too high. ''' def decorator(method): @functools.wraps(method) def f(): if rounds == 1: start = time.time() method() duration = time.time() - start else: start = time.time() for i in range(rounds): method() duration = (time.time() - start) / rounds # Use milliseconds for duration counter duration = duration * 1e3 print('Test "%s.%s" took %.06f ms.' % (method.__module__, method.__name__, duration)) if limit is not None: assert limit > duration, 'Timing failure: %.06f > %.06f' % (duration, limit) # Run tests with timings, only if WITH_TIMINGS environment variable is set. # This is because tests with multiple rounds can take long to process. if environ.get('WITH_TIMINGS', None) == '1': return f return method return decorator
[ "def", "timing", "(", "rounds", "=", "1", ",", "limit", "=", "None", ")", ":", "def", "decorator", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "f", "(", ")", ":", "if", "rounds", "==", "1", ":", "start", ...
Wrapper to implement simple timing of tests. Allows running multiple rounds to calculate average time. Limit (in milliseconds) can be set to assert, if (average) duration is too high.
[ "Wrapper", "to", "implement", "simple", "timing", "of", "tests", ".", "Allows", "running", "multiple", "rounds", "to", "calculate", "average", "time", ".", "Limit", "(", "in", "milliseconds", ")", "can", "be", "set", "to", "assert", "if", "(", "average", "...
python
train
happyleavesaoc/aoc-mgz
mgz/recorded_game/__init__.py
https://github.com/happyleavesaoc/aoc-mgz/blob/13fc379cc062d7640bfa028eed9c0d45d37a7b2b/mgz/recorded_game/__init__.py#L379-L396
def _compute_diplomacy(self): """Compute diplomacy.""" self._diplomacy = { 'teams': self.teams(), 'ffa': len(self.teams()) == (self._player_num + self._computer_num and self._player_num + self._computer_num > 2), 'TG': len(self.teams()) == 2 and self._player_num + self._computer_num > 2, '1v1': self._player_num + self._computer_num == 2, } self._diplomacy['type'] = 'unknown' if self._diplomacy['ffa']: self._diplomacy['type'] = 'ffa' if self._diplomacy['TG']: self._diplomacy['type'] = 'TG' size = len(self.teams()[0]['player_numbers']) self._diplomacy['team_size'] = '{}v{}'.format(size, size) if self._diplomacy['1v1']: self._diplomacy['type'] = '1v1'
[ "def", "_compute_diplomacy", "(", "self", ")", ":", "self", ".", "_diplomacy", "=", "{", "'teams'", ":", "self", ".", "teams", "(", ")", ",", "'ffa'", ":", "len", "(", "self", ".", "teams", "(", ")", ")", "==", "(", "self", ".", "_player_num", "+",...
Compute diplomacy.
[ "Compute", "diplomacy", "." ]
python
train
gijzelaerr/python-snap7
snap7/client.py
https://github.com/gijzelaerr/python-snap7/blob/a6db134c7a3a2ef187b9eca04669221d6fc634c3/snap7/client.py#L349-L353
def set_session_password(self, password): """Send the password to the PLC to meet its security level.""" assert len(password) <= 8, 'maximum password length is 8' return self.library.Cli_SetSessionPassword(self.pointer, c_char_p(six.b(password)))
[ "def", "set_session_password", "(", "self", ",", "password", ")", ":", "assert", "len", "(", "password", ")", "<=", "8", ",", "'maximum password length is 8'", "return", "self", ".", "library", ".", "Cli_SetSessionPassword", "(", "self", ".", "pointer", ",", "...
Send the password to the PLC to meet its security level.
[ "Send", "the", "password", "to", "the", "PLC", "to", "meet", "its", "security", "level", "." ]
python
train
mlperf/training
object_detection/pytorch/maskrcnn_benchmark/modeling/backbone/fpn.py
https://github.com/mlperf/training/blob/1c6ae725a81d15437a2b2df05cac0673fde5c3a4/object_detection/pytorch/maskrcnn_benchmark/modeling/backbone/fpn.py#L43-L74
def forward(self, x): """ Arguments: x (list[Tensor]): feature maps for each feature level. Returns: results (tuple[Tensor]): feature maps after FPN layers. They are ordered from highest resolution first. """ last_inner = getattr(self, self.inner_blocks[-1])(x[-1]) results = [] results.append(getattr(self, self.layer_blocks[-1])(last_inner)) for feature, inner_block, layer_block in zip( x[:-1][::-1], self.inner_blocks[:-1][::-1], self.layer_blocks[:-1][::-1] ): if not inner_block: continue inner_top_down = F.interpolate(last_inner, scale_factor=2, mode="nearest") inner_lateral = getattr(self, inner_block)(feature) # TODO use size instead of scale to make it robust to different sizes # inner_top_down = F.upsample(last_inner, size=inner_lateral.shape[-2:], # mode='bilinear', align_corners=False) last_inner = inner_lateral + inner_top_down results.insert(0, getattr(self, layer_block)(last_inner)) if isinstance(self.top_blocks, LastLevelP6P7): last_results = self.top_blocks(x[-1], results[-1]) results.extend(last_results) elif isinstance(self.top_blocks, LastLevelMaxPool): last_results = self.top_blocks(results[-1]) results.extend(last_results) return tuple(results)
[ "def", "forward", "(", "self", ",", "x", ")", ":", "last_inner", "=", "getattr", "(", "self", ",", "self", ".", "inner_blocks", "[", "-", "1", "]", ")", "(", "x", "[", "-", "1", "]", ")", "results", "=", "[", "]", "results", ".", "append", "(",...
Arguments: x (list[Tensor]): feature maps for each feature level. Returns: results (tuple[Tensor]): feature maps after FPN layers. They are ordered from highest resolution first.
[ "Arguments", ":", "x", "(", "list", "[", "Tensor", "]", ")", ":", "feature", "maps", "for", "each", "feature", "level", ".", "Returns", ":", "results", "(", "tuple", "[", "Tensor", "]", ")", ":", "feature", "maps", "after", "FPN", "layers", ".", "The...
python
train
gabstopper/smc-python
smc/policy/policy.py
https://github.com/gabstopper/smc-python/blob/e027b8a5dcfaf884eada32d113d41c1e56b32457/smc/policy/policy.py#L78-L109
def search_rule(self, search): """ Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements matching criteria :rtype: list(Element) """ result = self.make_request( resource='search_rule', params={'filter': search}) if result: results = [] for data in result: typeof = data.get('type') if 'ethernet' in typeof: klazz = lookup_class('ethernet_rule') elif typeof in [ 'ips_ipv4_access_rule', 'l2_interface_ipv4_access_rule']: klazz = lookup_class('layer2_ipv4_access_rule') else: klazz = lookup_class(typeof) results.append(klazz(**data)) return results return []
[ "def", "search_rule", "(", "self", ",", "search", ")", ":", "result", "=", "self", ".", "make_request", "(", "resource", "=", "'search_rule'", ",", "params", "=", "{", "'filter'", ":", "search", "}", ")", "if", "result", ":", "results", "=", "[", "]", ...
Search a rule for a rule tag or name value Result will be the meta data for rule (name, href, type) Searching for a rule in specific policy:: f = FirewallPolicy(policy) search = f.search_rule(searchable) :param str search: search string :return: rule elements matching criteria :rtype: list(Element)
[ "Search", "a", "rule", "for", "a", "rule", "tag", "or", "name", "value", "Result", "will", "be", "the", "meta", "data", "for", "rule", "(", "name", "href", "type", ")" ]
python
train
revelc/pyaccumulo
pyaccumulo/proxy/AccumuloProxy.py
https://github.com/revelc/pyaccumulo/blob/8adcf535bb82ba69c749efce785c9efc487e85de/pyaccumulo/proxy/AccumuloProxy.py#L2021-L2028
def pingTabletServer(self, login, tserver): """ Parameters: - login - tserver """ self.send_pingTabletServer(login, tserver) self.recv_pingTabletServer()
[ "def", "pingTabletServer", "(", "self", ",", "login", ",", "tserver", ")", ":", "self", ".", "send_pingTabletServer", "(", "login", ",", "tserver", ")", "self", ".", "recv_pingTabletServer", "(", ")" ]
Parameters: - login - tserver
[ "Parameters", ":", "-", "login", "-", "tserver" ]
python
train
stlehmann/pyads
pyads/pyads_ex.py
https://github.com/stlehmann/pyads/blob/44bd84394db2785332ac44b2948373916bea0f02/pyads/pyads_ex.py#L133-L150
def adsAddRoute(net_id, ip_address): # type: (SAmsNetId, str) -> None """Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint """ add_route = _adsDLL.AdsAddRoute add_route.restype = ctypes.c_long # Convert ip address to bytes (PY3) and get pointer. ip_address_p = ctypes.c_char_p(ip_address.encode("utf-8")) error_code = add_route(net_id, ip_address_p) if error_code: raise ADSError(error_code)
[ "def", "adsAddRoute", "(", "net_id", ",", "ip_address", ")", ":", "# type: (SAmsNetId, str) -> None", "add_route", "=", "_adsDLL", ".", "AdsAddRoute", "add_route", ".", "restype", "=", "ctypes", ".", "c_long", "# Convert ip address to bytes (PY3) and get pointer.", "ip_ad...
Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint
[ "Establish", "a", "new", "route", "in", "the", "AMS", "Router", "." ]
python
valid
tonysimpson/nanomsg-python
nanomsg/__init__.py
https://github.com/tonysimpson/nanomsg-python/blob/3acd9160f90f91034d4a43ce603aaa19fbaf1f2e/nanomsg/__init__.py#L359-L366
def recv(self, buf=None, flags=0): """Recieve a message.""" if buf is None: rtn, out_buf = wrapper.nn_recv(self.fd, flags) else: rtn, out_buf = wrapper.nn_recv(self.fd, buf, flags) _nn_check_positive_rtn(rtn) return bytes(buffer(out_buf))[:rtn]
[ "def", "recv", "(", "self", ",", "buf", "=", "None", ",", "flags", "=", "0", ")", ":", "if", "buf", "is", "None", ":", "rtn", ",", "out_buf", "=", "wrapper", ".", "nn_recv", "(", "self", ".", "fd", ",", "flags", ")", "else", ":", "rtn", ",", ...
Recieve a message.
[ "Recieve", "a", "message", "." ]
python
train
quantumlib/Cirq
cirq/optimizers/decompositions.py
https://github.com/quantumlib/Cirq/blob/0827da80dd7880e5b923eb69407e980ed9bc0bd2/cirq/optimizers/decompositions.py#L118-L143
def single_qubit_op_to_framed_phase_form( mat: np.ndarray) -> Tuple[np.ndarray, complex, complex]: """Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's phase is the amount of rotation around M's rotation axis. This decomposition can be used to decompose controlled single-qubit rotations into controlled-Z operations bordered by single-qubit operations. Args: mat: The qubit operation as a 2x2 unitary matrix. Returns: A 2x2 unitary U, the complex relative phase factor r, and the complex global phase factor g. Applying M is equivalent (up to global phase) to applying U, rotating around the Z axis to apply r, then un-applying U. When M is controlled, the control must be rotated around the Z axis to apply g. """ vals, vecs = np.linalg.eig(mat) u = np.conj(vecs).T r = vals[1] / vals[0] g = vals[0] return u, r, g
[ "def", "single_qubit_op_to_framed_phase_form", "(", "mat", ":", "np", ".", "ndarray", ")", "->", "Tuple", "[", "np", ".", "ndarray", ",", "complex", ",", "complex", "]", ":", "vals", ",", "vecs", "=", "np", ".", "linalg", ".", "eig", "(", "mat", ")", ...
Decomposes a 2x2 unitary M into U^-1 * diag(1, r) * U * diag(g, g). U translates the rotation axis of M to the Z axis. g fixes a global phase factor difference caused by the translation. r's phase is the amount of rotation around M's rotation axis. This decomposition can be used to decompose controlled single-qubit rotations into controlled-Z operations bordered by single-qubit operations. Args: mat: The qubit operation as a 2x2 unitary matrix. Returns: A 2x2 unitary U, the complex relative phase factor r, and the complex global phase factor g. Applying M is equivalent (up to global phase) to applying U, rotating around the Z axis to apply r, then un-applying U. When M is controlled, the control must be rotated around the Z axis to apply g.
[ "Decomposes", "a", "2x2", "unitary", "M", "into", "U^", "-", "1", "*", "diag", "(", "1", "r", ")", "*", "U", "*", "diag", "(", "g", "g", ")", "." ]
python
train
bspaans/python-mingus
mingus/midi/midi_file_in.py
https://github.com/bspaans/python-mingus/blob/aa5a5d992d45ada61be0f9f86261380731bd7749/mingus/midi/midi_file_in.py#L243-L259
def parse_track(self, fp): """Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read. """ events = [] chunk_size = self.parse_track_header(fp) bytes = chunk_size while chunk_size > 0: (delta_time, chunk_delta) = self.parse_varbyte_as_int(fp) chunk_size -= chunk_delta (event, chunk_delta) = self.parse_midi_event(fp) chunk_size -= chunk_delta events.append([delta_time, event]) if chunk_size < 0: print 'yikes.', self.bytes_read, chunk_size return events
[ "def", "parse_track", "(", "self", ",", "fp", ")", ":", "events", "=", "[", "]", "chunk_size", "=", "self", ".", "parse_track_header", "(", "fp", ")", "bytes", "=", "chunk_size", "while", "chunk_size", ">", "0", ":", "(", "delta_time", ",", "chunk_delta"...
Parse a MIDI track from its header to its events. Return a list of events and the number of bytes that were read.
[ "Parse", "a", "MIDI", "track", "from", "its", "header", "to", "its", "events", "." ]
python
train
python-rope/rope
rope/base/libutils.py
https://github.com/python-rope/rope/blob/1c9f9cd5964b099a99a9111e998f0dc728860688/rope/base/libutils.py#L85-L94
def get_string_module(project, code, resource=None, force_errors=False): """Returns a `PyObject` object for the given code If `force_errors` is `True`, `exceptions.ModuleSyntaxError` is raised if module has syntax errors. This overrides ``ignore_syntax_errors`` project config. """ return pyobjectsdef.PyModule(project.pycore, code, resource, force_errors=force_errors)
[ "def", "get_string_module", "(", "project", ",", "code", ",", "resource", "=", "None", ",", "force_errors", "=", "False", ")", ":", "return", "pyobjectsdef", ".", "PyModule", "(", "project", ".", "pycore", ",", "code", ",", "resource", ",", "force_errors", ...
Returns a `PyObject` object for the given code If `force_errors` is `True`, `exceptions.ModuleSyntaxError` is raised if module has syntax errors. This overrides ``ignore_syntax_errors`` project config.
[ "Returns", "a", "PyObject", "object", "for", "the", "given", "code" ]
python
train
Spirent/py-stcrestclient
stcrestclient/resthttp.py
https://github.com/Spirent/py-stcrestclient/blob/80ee82bddf2fb2808f3da8ff2c80b7d588e165e8/stcrestclient/resthttp.py#L252-L271
def delete_request(self, container, resource=None, query_items=None, accept=None): """Send a DELETE request.""" url = self.make_url(container, resource) headers = self._make_headers(accept) if query_items and isinstance(query_items, (list, tuple, set)): url += RestHttp._list_query_str(query_items) query_items = None try: rsp = requests.delete(url, params=query_items, headers=headers, verify=self._verify, timeout=self._timeout) except requests.exceptions.ConnectionError as e: RestHttp._raise_conn_error(e) if self._dbg_print: self.__print_req('DELETE', rsp.url, headers, None) return self._handle_response(rsp)
[ "def", "delete_request", "(", "self", ",", "container", ",", "resource", "=", "None", ",", "query_items", "=", "None", ",", "accept", "=", "None", ")", ":", "url", "=", "self", ".", "make_url", "(", "container", ",", "resource", ")", "headers", "=", "s...
Send a DELETE request.
[ "Send", "a", "DELETE", "request", "." ]
python
train
reingart/pyafipws
wslpg.py
https://github.com/reingart/pyafipws/blob/ee87cfe4ac12285ab431df5fec257f103042d1ab/wslpg.py#L2057-L2068
def AnularCertificacion(self, coe): "Anular liquidación activa" ret = self.client.cgSolicitarAnulacion( auth={ 'token': self.Token, 'sign': self.Sign, 'cuit': self.Cuit, }, coe=coe, ) ret = ret['oReturn'] self.__analizar_errores(ret) self.Estado = ret.get('estadoCertificado', "") return self.COE
[ "def", "AnularCertificacion", "(", "self", ",", "coe", ")", ":", "ret", "=", "self", ".", "client", ".", "cgSolicitarAnulacion", "(", "auth", "=", "{", "'token'", ":", "self", ".", "Token", ",", "'sign'", ":", "self", ".", "Sign", ",", "'cuit'", ":", ...
Anular liquidación activa
[ "Anular", "liquidación", "activa" ]
python
train
padelt/temper-python
temperusb/temper.py
https://github.com/padelt/temper-python/blob/cbdbace7e6755b1d91a2603ab63c9cb778078f79/temperusb/temper.py#L207-L281
def get_data(self, reset_device=False): """ Get data from the USB device. """ try: if reset_device: self._device.reset() # detach kernel driver from both interfaces if attached, so we can set_configuration() for interface in [0,1]: if self._device.is_kernel_driver_active(interface): LOGGER.debug('Detaching kernel driver for interface %d ' 'of %r on ports %r', interface, self._device, self._ports) self._device.detach_kernel_driver(interface) self._device.set_configuration() # Prevent kernel message: # "usbfs: process <PID> (python) did not claim interface x before use" # This will become unnecessary once pull-request #124 for # PyUSB has been accepted and we depend on a fixed release # of PyUSB. Until then, and even with the fix applied, it # does not hurt to explicitly claim the interface. usb.util.claim_interface(self._device, INTERFACE) # Turns out we don't actually need that ctrl_transfer. # Disabling this reduces number of USBErrors from ~7/30 to 0! #self._device.ctrl_transfer(bmRequestType=0x21, bRequest=0x09, # wValue=0x0201, wIndex=0x00, data_or_wLength='\x01\x01', # timeout=TIMEOUT) # Magic: Our TEMPerV1.4 likes to be asked twice. When # only asked once, it get's stuck on the next access and # requires a reset. self._control_transfer(COMMANDS['temp']) self._interrupt_read() # Turns out a whole lot of that magic seems unnecessary. #self._control_transfer(COMMANDS['ini1']) #self._interrupt_read() #self._control_transfer(COMMANDS['ini2']) #self._interrupt_read() #self._interrupt_read() # Get temperature self._control_transfer(COMMANDS['temp']) temp_data = self._interrupt_read() # Get humidity if self._device.product == 'TEMPer1F_H1_V1.4': humidity_data = temp_data else: humidity_data = None # Combine temperature and humidity data data = {'temp_data': temp_data, 'humidity_data': humidity_data} # Be a nice citizen and undo potential interface claiming. # Also see: https://github.com/walac/pyusb/blob/master/docs/tutorial.rst#dont-be-selfish usb.util.dispose_resources(self._device) return data except usb.USBError as err: if not reset_device: LOGGER.warning("Encountered %s, resetting %r and trying again.", err, self._device) return self.get_data(True) # Catch the permissions exception and add our message if "not permitted" in str(err): raise Exception( "Permission problem accessing USB. " "Maybe I need to run as root?") else: LOGGER.error(err) raise
[ "def", "get_data", "(", "self", ",", "reset_device", "=", "False", ")", ":", "try", ":", "if", "reset_device", ":", "self", ".", "_device", ".", "reset", "(", ")", "# detach kernel driver from both interfaces if attached, so we can set_configuration()", "for", "interf...
Get data from the USB device.
[ "Get", "data", "from", "the", "USB", "device", "." ]
python
valid
hobson/aima
aima/learning.py
https://github.com/hobson/aima/blob/3572b2fb92039b4a1abe384be8545560fbd3d470/aima/learning.py#L545-L547
def leave1out(learner, dataset): "Leave one out cross-validation over the dataset." return cross_validation(learner, dataset, k=len(dataset.examples))
[ "def", "leave1out", "(", "learner", ",", "dataset", ")", ":", "return", "cross_validation", "(", "learner", ",", "dataset", ",", "k", "=", "len", "(", "dataset", ".", "examples", ")", ")" ]
Leave one out cross-validation over the dataset.
[ "Leave", "one", "out", "cross", "-", "validation", "over", "the", "dataset", "." ]
python
valid
boriel/zxbasic
zxbpp.py
https://github.com/boriel/zxbasic/blob/23b28db10e41117805bdb3c0f78543590853b132/zxbpp.py#L596-L602
def p_exprle(p): """ expr : expr LE expr """ a = int(p[1]) if p[1].isdigit() else 0 b = int(p[3]) if p[3].isdigit() else 0 p[0] = '1' if a <= b else '0'
[ "def", "p_exprle", "(", "p", ")", ":", "a", "=", "int", "(", "p", "[", "1", "]", ")", "if", "p", "[", "1", "]", ".", "isdigit", "(", ")", "else", "0", "b", "=", "int", "(", "p", "[", "3", "]", ")", "if", "p", "[", "3", "]", ".", "isdi...
expr : expr LE expr
[ "expr", ":", "expr", "LE", "expr" ]
python
train
dmbee/seglearn
seglearn/transform.py
https://github.com/dmbee/seglearn/blob/d8d7039e92c4c6571a70350c03298aceab8dbeec/seglearn/transform.py#L922-L1009
def transform(self, X, y=None, sample_weight=None): ''' Transforms the time series data with linear direct value interpolation If y is a time series and passed, it will be transformed as well The time dimension is removed from the data Parameters ---------- X : array-like, shape [n_series, ...] Time series data and (optionally) contextual data y : array-like shape [n_series], default = None target vector sample_weight : array-like shape [n_series], default = None sample weights Returns ------- X_new : array-like, shape [n_series, ] transformed time series data y_new : array-like, shape [n_series] expanded target vector sample_weight_new : array-like or None None is returned if target is changed. Otherwise it is returned unchanged. ''' check_ts_data(X, y) xt, xc = get_ts_data_parts(X) yt = y swt = sample_weight # number of data channels d = xt[0][0].shape[0] - 2 # number of series N = len(xt) # retrieve the unique identifiers s = np.unique(xt[0][:, 1]) x_new = [] t_lin = [] # transform x for i in np.arange(N): # splits series into a list for each variable xs = [xt[i][xt[i][:, 1] == s[j]] for j in np.arange(len(s))] # find latest/earliest sample time for each identifier's first/last time sample time t_min = np.max([np.min(xs[j][:, 0]) for j in np.arange(len(s))]) t_max = np.min([np.max(xs[j][:, 0]) for j in np.arange(len(s))]) # Generate a regular series of timestamps starting at tStart and tEnd for sample_period t_lin.append(np.arange(t_min, t_max, self.sample_period)) # Interpolate for the new regular sample times if d == 1: x_new.append( np.column_stack( [self._interp(t_lin[i], xs[j][:, 0], xs[j][:, 2], kind=self.kind) for j in np.arange(len(s))])) elif d > 1: xd = [] for j in np.arange(len(s)): # stack the columns of each variable by dimension d after interpolation to new regular sample times temp = np.column_stack( [(self._interp(t_lin[i], xs[j][:, 0], xs[j][:, k], kind=self.kind)) for k in np.arange(2, 2 + d)]) xd.append(temp) # column stack each of the sensors s -- resulting in s*d columns x_new.append(np.column_stack(xd)) # transform y if yt is not None and len(np.atleast_1d(yt[0])) > 1: # y is a time series swt = None if self.categorical_target is True: yt = [self._interp(t_lin[i], xt[i][:, 0], yt[i], kind='nearest') for i in np.arange(N)] else: yt = [self._interp(t_lin[i], xt[i][:, 0], yt[i], kind=self.kind) for i in np.arange(N)] else: # y is static - leave y alone pass if xc is not None: x_new = TS_Data(x_new, xc) return x_new, yt, swt
[ "def", "transform", "(", "self", ",", "X", ",", "y", "=", "None", ",", "sample_weight", "=", "None", ")", ":", "check_ts_data", "(", "X", ",", "y", ")", "xt", ",", "xc", "=", "get_ts_data_parts", "(", "X", ")", "yt", "=", "y", "swt", "=", "sample...
Transforms the time series data with linear direct value interpolation If y is a time series and passed, it will be transformed as well The time dimension is removed from the data Parameters ---------- X : array-like, shape [n_series, ...] Time series data and (optionally) contextual data y : array-like shape [n_series], default = None target vector sample_weight : array-like shape [n_series], default = None sample weights Returns ------- X_new : array-like, shape [n_series, ] transformed time series data y_new : array-like, shape [n_series] expanded target vector sample_weight_new : array-like or None None is returned if target is changed. Otherwise it is returned unchanged.
[ "Transforms", "the", "time", "series", "data", "with", "linear", "direct", "value", "interpolation", "If", "y", "is", "a", "time", "series", "and", "passed", "it", "will", "be", "transformed", "as", "well", "The", "time", "dimension", "is", "removed", "from"...
python
train
Duke-GCB/DukeDSClient
ddsc/sdk/client.py
https://github.com/Duke-GCB/DukeDSClient/blob/117f68fb9bae82e4c81ea487ad5d61ac350f3726/ddsc/sdk/client.py#L102-L111
def create_project(self, name, description): """ Create a new project with the specified name and description :param name: str: name of the project to create :param description: str: description of the project to create :return: Project """ return self._create_item_response( self.data_service.create_project(name, description), Project)
[ "def", "create_project", "(", "self", ",", "name", ",", "description", ")", ":", "return", "self", ".", "_create_item_response", "(", "self", ".", "data_service", ".", "create_project", "(", "name", ",", "description", ")", ",", "Project", ")" ]
Create a new project with the specified name and description :param name: str: name of the project to create :param description: str: description of the project to create :return: Project
[ "Create", "a", "new", "project", "with", "the", "specified", "name", "and", "description", ":", "param", "name", ":", "str", ":", "name", "of", "the", "project", "to", "create", ":", "param", "description", ":", "str", ":", "description", "of", "the", "p...
python
train
gwastro/pycbc
pycbc/waveform/spa_tmplt.py
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/waveform/spa_tmplt.py#L80-L94
def spa_length_in_time(**kwds): """ Returns the length in time of the template, based on the masses, PN order, and low-frequency cut-off. """ m1 = kwds['mass1'] m2 = kwds['mass2'] flow = kwds['f_lower'] porder = int(kwds['phase_order']) # For now, we call the swig-wrapped function below in # lalinspiral. Eventually would be nice to replace this # with a function using PN coeffs from lalsimulation. return findchirp_chirptime(m1, m2, flow, porder)
[ "def", "spa_length_in_time", "(", "*", "*", "kwds", ")", ":", "m1", "=", "kwds", "[", "'mass1'", "]", "m2", "=", "kwds", "[", "'mass2'", "]", "flow", "=", "kwds", "[", "'f_lower'", "]", "porder", "=", "int", "(", "kwds", "[", "'phase_order'", "]", ...
Returns the length in time of the template, based on the masses, PN order, and low-frequency cut-off.
[ "Returns", "the", "length", "in", "time", "of", "the", "template", "based", "on", "the", "masses", "PN", "order", "and", "low", "-", "frequency", "cut", "-", "off", "." ]
python
train
saltstack/salt
salt/modules/cron.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/cron.py#L778-L801
def rm_env(user, name): ''' Remove cron environment variable for a specified user. CLI Example: .. code-block:: bash salt '*' cron.rm_env root MAILTO ''' lst = list_tab(user) ret = 'absent' rm_ = None for ind in range(len(lst['env'])): if name == lst['env'][ind]['name']: rm_ = ind if rm_ is not None: lst['env'].pop(rm_) ret = 'removed' comdat = _write_cron_lines(user, _render_tab(lst)) if comdat['retcode']: # Failed to commit, return the error return comdat['stderr'] return ret
[ "def", "rm_env", "(", "user", ",", "name", ")", ":", "lst", "=", "list_tab", "(", "user", ")", "ret", "=", "'absent'", "rm_", "=", "None", "for", "ind", "in", "range", "(", "len", "(", "lst", "[", "'env'", "]", ")", ")", ":", "if", "name", "=="...
Remove cron environment variable for a specified user. CLI Example: .. code-block:: bash salt '*' cron.rm_env root MAILTO
[ "Remove", "cron", "environment", "variable", "for", "a", "specified", "user", "." ]
python
train
cloudendpoints/endpoints-management-python
endpoints_management/control/metric_descriptor.py
https://github.com/cloudendpoints/endpoints-management-python/blob/ec3c4a330ae9d65738861ce6df4dd6c3cb9f7731/endpoints_management/control/metric_descriptor.py#L276-L289
def matches(self, desc): """Determines if a given metric descriptor matches this enum instance Args: desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the instance to test Return: `True` if desc is supported, otherwise `False` """ return (self.metric_name == desc.name and self.kind == desc.metricKind and self.value_type == desc.valueType)
[ "def", "matches", "(", "self", ",", "desc", ")", ":", "return", "(", "self", ".", "metric_name", "==", "desc", ".", "name", "and", "self", ".", "kind", "==", "desc", ".", "metricKind", "and", "self", ".", "value_type", "==", "desc", ".", "valueType", ...
Determines if a given metric descriptor matches this enum instance Args: desc (:class:`endpoints_management.gen.servicecontrol_v1_messages.MetricDescriptor`): the instance to test Return: `True` if desc is supported, otherwise `False`
[ "Determines", "if", "a", "given", "metric", "descriptor", "matches", "this", "enum", "instance" ]
python
train
SHDShim/pytheos
pytheos/eqn_bm3.py
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L65-L82
def bm3_v(p, v0, k0, k0p, p_ref=0.0, min_strain=0.01): """ find volume at given pressure using brenth in scipy.optimize :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :param min_strain: minimum strain value to find solution (default = 0.01) :return: volume at high pressure """ if isuncertainties([p, v0, k0, k0p]): f_u = np.vectorize(uct.wrap(bm3_v_single), excluded=[1, 2, 3, 4, 5]) return f_u(p, v0, k0, k0p, p_ref=p_ref, min_strain=min_strain) else: f_v = np.vectorize(bm3_v_single, excluded=[1, 2, 3, 4, 5]) return f_v(p, v0, k0, k0p, p_ref=p_ref, min_strain=min_strain)
[ "def", "bm3_v", "(", "p", ",", "v0", ",", "k0", ",", "k0p", ",", "p_ref", "=", "0.0", ",", "min_strain", "=", "0.01", ")", ":", "if", "isuncertainties", "(", "[", "p", ",", "v0", ",", "k0", ",", "k0p", "]", ")", ":", "f_u", "=", "np", ".", ...
find volume at given pressure using brenth in scipy.optimize :param p: pressure :param v0: volume at reference conditions :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at different conditions :param p_ref: reference pressure (default = 0) :param min_strain: minimum strain value to find solution (default = 0.01) :return: volume at high pressure
[ "find", "volume", "at", "given", "pressure", "using", "brenth", "in", "scipy", ".", "optimize" ]
python
train
tomnor/channelpack
channelpack/pack.py
https://github.com/tomnor/channelpack/blob/9ad3cd11c698aed4c0fc178385b2ba38a7d0efae/channelpack/pack.py#L1206-L1237
def txtpack(fn, **kwargs): """Return a ChannelPack instance loaded with text data file fn. Attempt to read out custom channel names from the file and call instance.set_channel_names(). Then return the pack. This is a lazy function to get a loaded instance, using the cleverness provided by pulltxt module. No delimiter or rows-to-skip and such need to be provided. However, if necessary, `**kwargs` can be used to override clevered items to provide to numpys loadtxt. usecols might be such an item for example. Also, the cleverness is only clever if all data is numerical. Note that the call signature is the same as numpys `loadtxt <http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy-loadtxt>`_, which look like this:: np.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0) But, when using this function as a wrapper, the only meaningful argument to override should be `usecols`. """ loadfunc = pulltxt.loadtxt_asdict cp = ChannelPack(loadfunc) cp.load(fn, **kwargs) names = pulltxt.PP.channel_names(kwargs.get('usecols', None)) cp.set_channel_names(names) cp._patpull = pulltxt.PP # Give a reference to the patternpull. # cp.set_basefilemtime() return cp
[ "def", "txtpack", "(", "fn", ",", "*", "*", "kwargs", ")", ":", "loadfunc", "=", "pulltxt", ".", "loadtxt_asdict", "cp", "=", "ChannelPack", "(", "loadfunc", ")", "cp", ".", "load", "(", "fn", ",", "*", "*", "kwargs", ")", "names", "=", "pulltxt", ...
Return a ChannelPack instance loaded with text data file fn. Attempt to read out custom channel names from the file and call instance.set_channel_names(). Then return the pack. This is a lazy function to get a loaded instance, using the cleverness provided by pulltxt module. No delimiter or rows-to-skip and such need to be provided. However, if necessary, `**kwargs` can be used to override clevered items to provide to numpys loadtxt. usecols might be such an item for example. Also, the cleverness is only clever if all data is numerical. Note that the call signature is the same as numpys `loadtxt <http://docs.scipy.org/doc/numpy/reference/generated/numpy.loadtxt.html#numpy-loadtxt>`_, which look like this:: np.loadtxt(fname, dtype=<type 'float'>, comments='#', delimiter=None, converters=None, skiprows=0, usecols=None, unpack=False, ndmin=0) But, when using this function as a wrapper, the only meaningful argument to override should be `usecols`.
[ "Return", "a", "ChannelPack", "instance", "loaded", "with", "text", "data", "file", "fn", "." ]
python
train
pypa/pipenv
pipenv/vendor/delegator.py
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/vendor/delegator.py#L290-L314
def _expand_args(command): """Parses command strings and returns a Popen-ready list.""" # Prepare arguments. if isinstance(command, STR_TYPES): if sys.version_info[0] == 2: splitter = shlex.shlex(command.encode("utf-8")) elif sys.version_info[0] == 3: splitter = shlex.shlex(command) else: splitter = shlex.shlex(command.encode("utf-8")) splitter.whitespace = "|" splitter.whitespace_split = True command = [] while True: token = splitter.get_token() if token: command.append(token) else: break command = list(map(shlex.split, command)) return command
[ "def", "_expand_args", "(", "command", ")", ":", "# Prepare arguments.", "if", "isinstance", "(", "command", ",", "STR_TYPES", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "splitter", "=", "shlex", ".", "shlex", "(", "comman...
Parses command strings and returns a Popen-ready list.
[ "Parses", "command", "strings", "and", "returns", "a", "Popen", "-", "ready", "list", "." ]
python
train
openpaperwork/paperwork-backend
paperwork_backend/docsearch.py
https://github.com/openpaperwork/paperwork-backend/blob/114b831e94e039e68b339751fd18250877abad76/paperwork_backend/docsearch.py#L224-L230
def commit(self, index_update=True, label_guesser_update=True): """ Apply the changes to the index """ logger.info("Index: Commiting changes") self.docsearch.index.commit(index_update=index_update, label_guesser_update=label_guesser_update)
[ "def", "commit", "(", "self", ",", "index_update", "=", "True", ",", "label_guesser_update", "=", "True", ")", ":", "logger", ".", "info", "(", "\"Index: Commiting changes\"", ")", "self", ".", "docsearch", ".", "index", ".", "commit", "(", "index_update", "...
Apply the changes to the index
[ "Apply", "the", "changes", "to", "the", "index" ]
python
train
sosreport/sos
sos/plugins/__init__.py
https://github.com/sosreport/sos/blob/2ebc04da53dc871c8dd5243567afa4f8592dca29/sos/plugins/__init__.py#L1448-L1467
def convert_cmd_scl(self, scl, cmd): """wrapping command in "scl enable" call and adds proper PATH """ # load default SCL prefix to PATH prefix = self.policy.get_default_scl_prefix() # read prefix from /etc/scl/prefixes/${scl} and strip trailing '\n' try: prefix = open('/etc/scl/prefixes/%s' % scl, 'r').read()\ .rstrip('\n') except Exception as e: self._log_error("Failed to find prefix for SCL %s, using %s" % (scl, prefix)) # expand PATH by equivalent prefixes under the SCL tree path = os.environ["PATH"] for p in path.split(':'): path = '%s/%s%s:%s' % (prefix, scl, p, path) scl_cmd = "scl enable %s \"PATH=%s %s\"" % (scl, path, cmd) return scl_cmd
[ "def", "convert_cmd_scl", "(", "self", ",", "scl", ",", "cmd", ")", ":", "# load default SCL prefix to PATH", "prefix", "=", "self", ".", "policy", ".", "get_default_scl_prefix", "(", ")", "# read prefix from /etc/scl/prefixes/${scl} and strip trailing '\\n'", "try", ":",...
wrapping command in "scl enable" call and adds proper PATH
[ "wrapping", "command", "in", "scl", "enable", "call", "and", "adds", "proper", "PATH" ]
python
train
odlgroup/odl
odl/space/fspace.py
https://github.com/odlgroup/odl/blob/b8443f6aca90e191ba36c91d32253c5a36249a6c/odl/space/fspace.py#L610-L636
def zero(self): """Function mapping anything to zero.""" # Since `FunctionSpace.lincomb` may be slow, we implement this # function directly. # The unused **kwargs are needed to support combination with # functions that take parameters. def zero_vec(x, out=None, **kwargs): """Zero function, vectorized.""" if is_valid_input_meshgrid(x, self.domain.ndim): scalar_out_shape = out_shape_from_meshgrid(x) elif is_valid_input_array(x, self.domain.ndim): scalar_out_shape = out_shape_from_array(x) else: raise TypeError('invalid input type') # For tensor-valued functions out_shape = self.out_shape + scalar_out_shape if out is None: return np.zeros(out_shape, dtype=self.scalar_out_dtype) else: # Need to go through an array to fill with the correct # zero value for all dtypes fill_value = np.zeros(1, dtype=self.scalar_out_dtype)[0] out.fill(fill_value) return self.element_type(self, zero_vec)
[ "def", "zero", "(", "self", ")", ":", "# Since `FunctionSpace.lincomb` may be slow, we implement this", "# function directly.", "# The unused **kwargs are needed to support combination with", "# functions that take parameters.", "def", "zero_vec", "(", "x", ",", "out", "=", "None",...
Function mapping anything to zero.
[ "Function", "mapping", "anything", "to", "zero", "." ]
python
train
aws/aws-encryption-sdk-python
src/aws_encryption_sdk/internal/formatting/__init__.py
https://github.com/aws/aws-encryption-sdk-python/blob/d182155d5fb1ef176d9e7d0647679737d5146495/src/aws_encryption_sdk/internal/formatting/__init__.py#L111-L122
def ciphertext_length(header, plaintext_length): """Calculates the complete ciphertext message length, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param int plaintext_length: Length of plaintext in bytes :rtype: int """ ciphertext_length = header_length(header) ciphertext_length += body_length(header, plaintext_length) ciphertext_length += footer_length(header) return ciphertext_length
[ "def", "ciphertext_length", "(", "header", ",", "plaintext_length", ")", ":", "ciphertext_length", "=", "header_length", "(", "header", ")", "ciphertext_length", "+=", "body_length", "(", "header", ",", "plaintext_length", ")", "ciphertext_length", "+=", "footer_lengt...
Calculates the complete ciphertext message length, given a complete header. :param header: Complete message header object :type header: aws_encryption_sdk.structures.MessageHeader :param int plaintext_length: Length of plaintext in bytes :rtype: int
[ "Calculates", "the", "complete", "ciphertext", "message", "length", "given", "a", "complete", "header", "." ]
python
train
lowandrew/OLCTools
spadespipeline/quality.py
https://github.com/lowandrew/OLCTools/blob/88aa90ac85f84d0bbeb03e43c29b0a9d36e4ce2a/spadespipeline/quality.py#L653-L665
def perform_pilon(self): """ Determine if pilon polishing should be attempted. Do not perform polishing if confindr determines that the sample is contaminated or if there are > 500 contigs """ for sample in self.metadata: try: if sample[self.analysistype].num_contigs > 500 or sample.confindr.contam_status == 'Contaminated': sample.general.polish = False else: sample.general.polish = True except AttributeError: sample.general.polish = True
[ "def", "perform_pilon", "(", "self", ")", ":", "for", "sample", "in", "self", ".", "metadata", ":", "try", ":", "if", "sample", "[", "self", ".", "analysistype", "]", ".", "num_contigs", ">", "500", "or", "sample", ".", "confindr", ".", "contam_status", ...
Determine if pilon polishing should be attempted. Do not perform polishing if confindr determines that the sample is contaminated or if there are > 500 contigs
[ "Determine", "if", "pilon", "polishing", "should", "be", "attempted", ".", "Do", "not", "perform", "polishing", "if", "confindr", "determines", "that", "the", "sample", "is", "contaminated", "or", "if", "there", "are", ">", "500", "contigs" ]
python
train
edx/opaque-keys
opaque_keys/edx/locator.py
https://github.com/edx/opaque-keys/blob/9807168660c12e0551c8fdd58fd1bc6b0bcb0a54/opaque_keys/edx/locator.py#L996-L1012
def to_deprecated_son(self, prefix='', tag='i4x'): """ Returns a SON object that represents this location """ # This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'), # because that format was used to store data historically in mongo # adding tag b/c deprecated form used it son = SON({prefix + 'tag': tag}) for field_name in ('org', 'course'): # Temporary filtering of run field because deprecated form left it out son[prefix + field_name] = getattr(self.course_key, field_name) for (dep_field_name, field_name) in [('category', 'block_type'), ('name', 'block_id')]: son[prefix + dep_field_name] = getattr(self, field_name) son[prefix + 'revision'] = self.course_key.branch return son
[ "def", "to_deprecated_son", "(", "self", ",", "prefix", "=", "''", ",", "tag", "=", "'i4x'", ")", ":", "# This preserves the old SON keys ('tag', 'org', 'course', 'category', 'name', 'revision'),", "# because that format was used to store data historically in mongo", "# adding tag b/...
Returns a SON object that represents this location
[ "Returns", "a", "SON", "object", "that", "represents", "this", "location" ]
python
train
ming060/robotframework-uiautomatorlibrary
uiautomatorlibrary/Mobile.py
https://github.com/ming060/robotframework-uiautomatorlibrary/blob/b70202b6a8aa68b4efd9d029c2845407fb33451a/uiautomatorlibrary/Mobile.py#L500-L508
def scroll_backward_vertically(self, steps=10, *args, **selectors): """ Perform scroll backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details. """ return self.device(**selectors).scroll.vert.backward(steps=steps)
[ "def", "scroll_backward_vertically", "(", "self", ",", "steps", "=", "10", ",", "*", "args", ",", "*", "*", "selectors", ")", ":", "return", "self", ".", "device", "(", "*", "*", "selectors", ")", ".", "scroll", ".", "vert", ".", "backward", "(", "st...
Perform scroll backward (vertically)action on the object which has *selectors* attributes. Return whether the object can be Scroll or not. See `Scroll Forward Vertically` for more details.
[ "Perform", "scroll", "backward", "(", "vertically", ")", "action", "on", "the", "object", "which", "has", "*", "selectors", "*", "attributes", "." ]
python
train
radjkarl/imgProcessor
imgProcessor/camera/LensDistortion.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/camera/LensDistortion.py#L129-L144
def addImg(self, img): ''' add one chessboard image for detection lens distortion ''' # self.opts['imgs'].append(img) self.img = imread(img, 'gray', 'uint8') didFindCorners, corners = self.method() self.opts['foundPattern'].append(didFindCorners) if didFindCorners: self.findCount += 1 self.objpoints.append(self.objp) self.opts['imgPoints'].append(corners) return didFindCorners
[ "def", "addImg", "(", "self", ",", "img", ")", ":", "# self.opts['imgs'].append(img)\r", "self", ".", "img", "=", "imread", "(", "img", ",", "'gray'", ",", "'uint8'", ")", "didFindCorners", ",", "corners", "=", "self", ".", "method", "(", ")", "self", "....
add one chessboard image for detection lens distortion
[ "add", "one", "chessboard", "image", "for", "detection", "lens", "distortion" ]
python
train
trec-kba/streamcorpus-pipeline
streamcorpus_pipeline/_kvlayer_keyword_search.py
https://github.com/trec-kba/streamcorpus-pipeline/blob/8bb82ea1beb83c6b40ed03fa1659df2897c2292a/streamcorpus_pipeline/_kvlayer_keyword_search.py#L212-L236
def lookup(self, h): '''Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a large number of stream IDs! This is a scan over a dense region of a :mod:`kvlayer` table so it should be reasonably efficient, but be prepared for it to return many documents in a large corpus. Blindly storing the results in a :class:`list` may be inadvisable. This will return nothing unless the index was written with :attr:`hash_docs` set. No document will correspond to :data:`DOCUMENT_HASH_KEY`; use :data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead. :param int h: Murmur hash to look up ''' for (_, k1, k2) in self.client.scan_keys(HASH_TF_INDEX_TABLE, ((h,), (h,))): yield kvlayer_key_to_stream_id((k1, k2))
[ "def", "lookup", "(", "self", ",", "h", ")", ":", "for", "(", "_", ",", "k1", ",", "k2", ")", "in", "self", ".", "client", ".", "scan_keys", "(", "HASH_TF_INDEX_TABLE", ",", "(", "(", "h", ",", ")", ",", "(", "h", ",", ")", ")", ")", ":", "...
Get stream IDs for a single hash. This yields strings that can be retrieved using :func:`streamcorpus_pipeline._kvlayer.get_kvlayer_stream_item`, or fed back into :mod:`coordinate` or other job queue systems. Note that for common terms this can return a large number of stream IDs! This is a scan over a dense region of a :mod:`kvlayer` table so it should be reasonably efficient, but be prepared for it to return many documents in a large corpus. Blindly storing the results in a :class:`list` may be inadvisable. This will return nothing unless the index was written with :attr:`hash_docs` set. No document will correspond to :data:`DOCUMENT_HASH_KEY`; use :data:`DOCUMENT_HASH_KEY_REPLACEMENT` instead. :param int h: Murmur hash to look up
[ "Get", "stream", "IDs", "for", "a", "single", "hash", "." ]
python
test
watson-developer-cloud/python-sdk
ibm_watson/websocket/recognize_listener.py
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/websocket/recognize_listener.py#L89-L97
def send(self, data, opcode=websocket.ABNF.OPCODE_TEXT): """ Send message to server. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT. """ self.ws_client.send(data, opcode)
[ "def", "send", "(", "self", ",", "data", ",", "opcode", "=", "websocket", ".", "ABNF", ".", "OPCODE_TEXT", ")", ":", "self", ".", "ws_client", ".", "send", "(", "data", ",", "opcode", ")" ]
Send message to server. data: message to send. If you set opcode to OPCODE_TEXT, data must be utf-8 string or unicode. opcode: operation code of data. default is OPCODE_TEXT.
[ "Send", "message", "to", "server", "." ]
python
train
jpype-project/jpype
jpype/_jvmfinder.py
https://github.com/jpype-project/jpype/blob/3ce953ae7b35244077249ce650b9acd0a7010d17/jpype/_jvmfinder.py#L177-L187
def _get_from_known_locations(self): """ Retrieves the first existing Java library path in the predefined known locations :return: The path to the JVM library, or None """ for home in self.find_possible_homes(self._locations): jvm = self.find_libjvm(home) if jvm is not None: return jvm
[ "def", "_get_from_known_locations", "(", "self", ")", ":", "for", "home", "in", "self", ".", "find_possible_homes", "(", "self", ".", "_locations", ")", ":", "jvm", "=", "self", ".", "find_libjvm", "(", "home", ")", "if", "jvm", "is", "not", "None", ":",...
Retrieves the first existing Java library path in the predefined known locations :return: The path to the JVM library, or None
[ "Retrieves", "the", "first", "existing", "Java", "library", "path", "in", "the", "predefined", "known", "locations" ]
python
train
funilrys/PyFunceble
PyFunceble/check.py
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/check.py#L196-L350
def is_domain_valid( self, domain=None, subdomain_check=False ): # pylint:disable=too-many-return-statements, too-many-branches """ Check if the given domain is a valid. :param domain: The domain to validate. :type domain: str :param subdomain_check: Activate the subdomain checking. :type subdomain_check: bool :return: The validity of the sub-domain. :rtype: bool """ # We initate our regex which will match for valid domains. regex_valid_domains = r"^(?=.{0,253}$)(([a-z0-9][a-z0-9-]{0,61}[a-z0-9]|[a-z0-9])\.)+((?=.*[^0-9])([a-z0-9][a-z0-9-]{0,61}[a-z0-9](?:\.)?|[a-z0-9](?:\.)?))$" # pylint: disable=line-too-long # We initiate our regex which will match for valid subdomains. regex_valid_subdomains = r"^(?=.{0,253}$)(([a-z0-9_][a-z0-9-_]{0,61}[a-z0-9_-]|[a-z0-9])\.)+((?=.*[^0-9])([a-z0-9][a-z0-9-]{0,61}[a-z0-9]|[a-z0-9]))$" # pylint: disable=line-too-long if domain: # A domain is given. # We set the element to test as the parsed domain. to_test = domain elif self.element: # A domain is globally given. # We set the globally parsed domain. to_test = self.element else: # A domain is not given. # We set the element to test as the currently tested element. to_test = PyFunceble.INTERN["to_test"] try: # We get the position of the last point. last_point_index = to_test.rindex(".") # And with the help of the position of the last point, we get the domain extension. extension = to_test[last_point_index + 1 :] if not extension and to_test.endswith("."): try: extension = [x for x in to_test.split(".") if x][-1] except IndexError: pass if not extension or extension not in PyFunceble.INTERN["iana_db"]: # * The extension is not found. # or # * The extension is not into the IANA database. # We return false. return False if ( Regex(to_test, regex_valid_domains, return_data=False).match() and not subdomain_check ): # * The element pass the domain validation. # and # * We are not checking if it is a subdomain. # We return True. The domain is valid. return True # The element did not pass the domain validation. That means that # it has invalid character or the position of - or _ are not right. if extension in PyFunceble.INTERN["psl_db"]: # The extension is into the psl database. for suffix in PyFunceble.INTERN["psl_db"][extension]: # We loop through the element of the extension into the psl database. try: # We try to get the position of the currently read suffix # in the element ot test. suffix_index = to_test.rindex("." + suffix) # We get the element to check. # The idea here is to delete the suffix, then retest with our # subdomains regex. to_check = to_test[:suffix_index] if "." not in to_check and subdomain_check: # * There is no point into the new element to check. # and # * We are checking if it is a subdomain. # We return False, it is not a subdomain. return False if "." in to_check and subdomain_check: # * There is a point into the new element to check. # and # * We are checking if it is a subdomain. # We return True, it is a subdomain. return True # We are not checking if it is a subdomain. if "." in to_check: # There is a point into the new element to check. # We check if it passes our subdomain regex. # * True: It's a valid domain. # * False: It's an invalid domain. return Regex( to_check, regex_valid_subdomains, return_data=False ).match() except ValueError: # In case of a value error because the position is not found, # we continue to the next element. pass # * The extension is not into the psl database. # or # * there was no point into the suffix checking. # We get the element before the last point. to_check = to_test[:last_point_index] if "." in to_check and subdomain_check: # * There is a point in to_check. # and # * We are checking if it is a subdomain. # We return True, it is a subdomain. return True # We are not checking if it is a subdomain. if "." in to_check: # There is a point in to_check. # We check if it passes our subdomain regex. # * True: It's a valid domain. # * False: It's an invalid domain. return Regex( to_check, regex_valid_subdomains, return_data=False ).match() except (ValueError, AttributeError): # In case of a value or attribute error we ignore them. pass # And we return False, the domain is not valid. return False
[ "def", "is_domain_valid", "(", "self", ",", "domain", "=", "None", ",", "subdomain_check", "=", "False", ")", ":", "# pylint:disable=too-many-return-statements, too-many-branches", "# We initate our regex which will match for valid domains.", "regex_valid_domains", "=", "r\"^(?=....
Check if the given domain is a valid. :param domain: The domain to validate. :type domain: str :param subdomain_check: Activate the subdomain checking. :type subdomain_check: bool :return: The validity of the sub-domain. :rtype: bool
[ "Check", "if", "the", "given", "domain", "is", "a", "valid", "." ]
python
test
iotile/coretools
iotileemulate/iotile/emulate/virtual/emulation_mixin.py
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotileemulate/iotile/emulate/virtual/emulation_mixin.py#L96-L111
def save_state(self, out_path): """Save the current state of this emulated object to a file. Args: out_path (str): The path to save the dumped state of this emulated object. """ state = self.dump_state() # Remove all IntEnums from state since they cannot be json-serialized on python 2.7 # See https://bitbucket.org/stoneleaf/enum34/issues/17/difference-between-enum34-and-enum-json state = _clean_intenum(state) with open(out_path, "w") as outfile: json.dump(state, outfile, indent=4)
[ "def", "save_state", "(", "self", ",", "out_path", ")", ":", "state", "=", "self", ".", "dump_state", "(", ")", "# Remove all IntEnums from state since they cannot be json-serialized on python 2.7", "# See https://bitbucket.org/stoneleaf/enum34/issues/17/difference-between-enum34-and...
Save the current state of this emulated object to a file. Args: out_path (str): The path to save the dumped state of this emulated object.
[ "Save", "the", "current", "state", "of", "this", "emulated", "object", "to", "a", "file", "." ]
python
train
sorgerlab/indra
indra/databases/cbio_client.py
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/databases/cbio_client.py#L350-L377
def get_ccle_lines_for_mutation(gene, amino_acid_change): """Return cell lines with a given point mutation in a given gene. Checks which cell lines in CCLE have a particular point mutation in a given gene and return their names in a list. Parameters ---------- gene : str The HGNC symbol of the mutated gene in whose product the amino acid change occurs. Example: "BRAF" amino_acid_change : str The amino acid change of interest. Example: "V600E" Returns ------- cell_lines : list A list of CCLE cell lines in which the given mutation occurs. """ data = {'cmd': 'getMutationData', 'case_set_id': ccle_study, 'genetic_profile_id': ccle_study + '_mutations', 'gene_list': gene, 'skiprows': 1} df = send_request(**data) df = df[df['amino_acid_change'] == amino_acid_change] cell_lines = df['case_id'].unique().tolist() return cell_lines
[ "def", "get_ccle_lines_for_mutation", "(", "gene", ",", "amino_acid_change", ")", ":", "data", "=", "{", "'cmd'", ":", "'getMutationData'", ",", "'case_set_id'", ":", "ccle_study", ",", "'genetic_profile_id'", ":", "ccle_study", "+", "'_mutations'", ",", "'gene_list...
Return cell lines with a given point mutation in a given gene. Checks which cell lines in CCLE have a particular point mutation in a given gene and return their names in a list. Parameters ---------- gene : str The HGNC symbol of the mutated gene in whose product the amino acid change occurs. Example: "BRAF" amino_acid_change : str The amino acid change of interest. Example: "V600E" Returns ------- cell_lines : list A list of CCLE cell lines in which the given mutation occurs.
[ "Return", "cell", "lines", "with", "a", "given", "point", "mutation", "in", "a", "given", "gene", "." ]
python
train
Aluriak/bubble-tools
bubbletools/converter.py
https://github.com/Aluriak/bubble-tools/blob/f014f4a1986abefc80dc418feaa05ed258c2221a/bubbletools/converter.py#L43-L58
def tree_to_dot(tree:BubbleTree, dotfile:str=None, render:bool=False): """Write in dotfile a graph equivalent to those depicted in bubble file See http://graphviz.readthedocs.io/en/latest/examples.html#cluster-py for graphviz API """ graph = tree_to_graph(tree) path = None if dotfile: # first save the dot file. path = graph.save(dotfile) if render: # secondly, show it. # As the dot file is known by the Graph object, # it will be placed around the dot file. graph.view() return path
[ "def", "tree_to_dot", "(", "tree", ":", "BubbleTree", ",", "dotfile", ":", "str", "=", "None", ",", "render", ":", "bool", "=", "False", ")", ":", "graph", "=", "tree_to_graph", "(", "tree", ")", "path", "=", "None", "if", "dotfile", ":", "# first save...
Write in dotfile a graph equivalent to those depicted in bubble file See http://graphviz.readthedocs.io/en/latest/examples.html#cluster-py for graphviz API
[ "Write", "in", "dotfile", "a", "graph", "equivalent", "to", "those", "depicted", "in", "bubble", "file" ]
python
train
bcbio/bcbio-nextgen
bcbio/cwl/create.py
https://github.com/bcbio/bcbio-nextgen/blob/6a9348c0054ccd5baffd22f1bb7d0422f6978b20/bcbio/cwl/create.py#L208-L221
def _write_expressiontool(step_dir, name, inputs, outputs, expression, parallel): """Create an ExpressionTool output for the given inputs """ out_file = os.path.join(step_dir, "%s.cwl" % name) out = {"class": "ExpressionTool", "cwlVersion": "v1.0", "requirements": [{"class": "InlineJavascriptRequirement"}], "inputs": [], "outputs": [], "expression": expression} out = _add_inputs_to_tool(inputs, out, parallel) out = _add_outputs_to_tool(outputs, out) _tool_to_file(out, out_file) return os.path.join("steps", os.path.basename(out_file))
[ "def", "_write_expressiontool", "(", "step_dir", ",", "name", ",", "inputs", ",", "outputs", ",", "expression", ",", "parallel", ")", ":", "out_file", "=", "os", ".", "path", ".", "join", "(", "step_dir", ",", "\"%s.cwl\"", "%", "name", ")", "out", "=", ...
Create an ExpressionTool output for the given inputs
[ "Create", "an", "ExpressionTool", "output", "for", "the", "given", "inputs" ]
python
train
tcalmant/ipopo
pelix/ipopo/handlers/requires.py
https://github.com/tcalmant/ipopo/blob/2f9ae0c44cd9c34ef1a9d50837b3254e75678eb1/pelix/ipopo/handlers/requires.py#L282-L312
def service_changed(self, event): """ Called by the framework when a service event occurs """ if ( self._ipopo_instance is None or not self._ipopo_instance.check_event(event) ): # stop() and clean() may have been called after we have been put # inside a listener list copy... # or we've been told to ignore this event return # Call sub-methods kind = event.get_kind() svc_ref = event.get_service_reference() if kind == ServiceEvent.REGISTERED: # Service coming self.on_service_arrival(svc_ref) elif kind in ( ServiceEvent.UNREGISTERING, ServiceEvent.MODIFIED_ENDMATCH, ): # Service gone or not matching anymore self.on_service_departure(svc_ref) elif kind == ServiceEvent.MODIFIED: # Modified properties (can be a new injection) self.on_service_modify(svc_ref, event.get_previous_properties())
[ "def", "service_changed", "(", "self", ",", "event", ")", ":", "if", "(", "self", ".", "_ipopo_instance", "is", "None", "or", "not", "self", ".", "_ipopo_instance", ".", "check_event", "(", "event", ")", ")", ":", "# stop() and clean() may have been called after...
Called by the framework when a service event occurs
[ "Called", "by", "the", "framework", "when", "a", "service", "event", "occurs" ]
python
train
etingof/apacheconfig
apacheconfig/lexer.py
https://github.com/etingof/apacheconfig/blob/7126dbc0a547779276ac04cf32a051c26781c464/apacheconfig/lexer.py#L236-L240
def t_multiline_NEWLINE(self, t): r'\r\n|\n|\r' if t.lexer.multiline_newline_seen: return self.t_multiline_OPTION_AND_VALUE(t) t.lexer.multiline_newline_seen = True
[ "def", "t_multiline_NEWLINE", "(", "self", ",", "t", ")", ":", "if", "t", ".", "lexer", ".", "multiline_newline_seen", ":", "return", "self", ".", "t_multiline_OPTION_AND_VALUE", "(", "t", ")", "t", ".", "lexer", ".", "multiline_newline_seen", "=", "True" ]
r'\r\n|\n|\r
[ "r", "\\", "r", "\\", "n|", "\\", "n|", "\\", "r" ]
python
train
trailofbits/manticore
manticore/core/workspace.py
https://github.com/trailofbits/manticore/blob/54c5a15b1119c523ae54c09972413e8b97f11629/manticore/core/workspace.py#L376-L384
def load_state(self, state_id, delete=True): """ Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State """ return self._store.load_state(f'{self._prefix}{state_id:08x}{self._suffix}', delete=delete)
[ "def", "load_state", "(", "self", ",", "state_id", ",", "delete", "=", "True", ")", ":", "return", "self", ".", "_store", ".", "load_state", "(", "f'{self._prefix}{state_id:08x}{self._suffix}'", ",", "delete", "=", "delete", ")" ]
Load a state from storage identified by `state_id`. :param state_id: The state reference of what to load :return: The deserialized state :rtype: State
[ "Load", "a", "state", "from", "storage", "identified", "by", "state_id", "." ]
python
valid
ConsenSys/mythril-classic
mythril/ethereum/interface/leveldb/client.py
https://github.com/ConsenSys/mythril-classic/blob/27af71c34b2ce94f4fae5613ec457f93df1a8f56/mythril/ethereum/interface/leveldb/client.py#L251-L261
def contract_hash_to_address(self, contract_hash): """Try to find corresponding account address. :param contract_hash: :return: """ address_hash = binascii.a2b_hex(utils.remove_0x_head(contract_hash)) indexer = AccountIndexer(self) return _encode_hex(indexer.get_contract_by_hash(address_hash))
[ "def", "contract_hash_to_address", "(", "self", ",", "contract_hash", ")", ":", "address_hash", "=", "binascii", ".", "a2b_hex", "(", "utils", ".", "remove_0x_head", "(", "contract_hash", ")", ")", "indexer", "=", "AccountIndexer", "(", "self", ")", "return", ...
Try to find corresponding account address. :param contract_hash: :return:
[ "Try", "to", "find", "corresponding", "account", "address", "." ]
python
train
MozillaSecurity/dharma
dharma/core/dharma.py
https://github.com/MozillaSecurity/dharma/blob/34247464fdda51b92790ad6693566a453d198e0b/dharma/core/dharma.py#L239-L242
def process_settings(self, settings): """A lazy way of feeding Dharma with configuration settings.""" logging.debug("Using configuration from: %s", settings.name) exec(compile(settings.read(), settings.name, 'exec'), globals(), locals())
[ "def", "process_settings", "(", "self", ",", "settings", ")", ":", "logging", ".", "debug", "(", "\"Using configuration from: %s\"", ",", "settings", ".", "name", ")", "exec", "(", "compile", "(", "settings", ".", "read", "(", ")", ",", "settings", ".", "n...
A lazy way of feeding Dharma with configuration settings.
[ "A", "lazy", "way", "of", "feeding", "Dharma", "with", "configuration", "settings", "." ]
python
train
mosdef-hub/mbuild
mbuild/compound.py
https://github.com/mosdef-hub/mbuild/blob/dcb80a2becd5d0e6a7e3e7bcb1b59793c46a2dd3/mbuild/compound.py#L1771-L1780
def translate(self, by): """Translate the Compound by a vector Parameters ---------- by : np.ndarray, shape=(3,), dtype=float """ new_positions = _translate(self.xyz_with_ports, by) self.xyz_with_ports = new_positions
[ "def", "translate", "(", "self", ",", "by", ")", ":", "new_positions", "=", "_translate", "(", "self", ".", "xyz_with_ports", ",", "by", ")", "self", ".", "xyz_with_ports", "=", "new_positions" ]
Translate the Compound by a vector Parameters ---------- by : np.ndarray, shape=(3,), dtype=float
[ "Translate", "the", "Compound", "by", "a", "vector" ]
python
train
GoogleCloudPlatform/compute-image-packages
packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py
https://github.com/GoogleCloudPlatform/compute-image-packages/blob/53ea8cd069fb4d9a1984d1c167e54c133033f8da/packages/python-google-compute-engine/google_compute_engine/boto/compute_auth.py#L50-L57
def _GetGsScopes(self): """Return all Google Storage scopes available on this VM.""" service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key) try: scopes = service_accounts[self.service_account]['scopes'] return list(GS_SCOPES.intersection(set(scopes))) if scopes else None except KeyError: return None
[ "def", "_GetGsScopes", "(", "self", ")", ":", "service_accounts", "=", "self", ".", "watcher", ".", "GetMetadata", "(", "metadata_key", "=", "self", ".", "metadata_key", ")", "try", ":", "scopes", "=", "service_accounts", "[", "self", ".", "service_account", ...
Return all Google Storage scopes available on this VM.
[ "Return", "all", "Google", "Storage", "scopes", "available", "on", "this", "VM", "." ]
python
train
ranaroussi/qtpylib
qtpylib/broker.py
https://github.com/ranaroussi/qtpylib/blob/0dbbc465fafd9cb9b0f4d10e1e07fae4e15032dd/qtpylib/broker.py#L196-L205
def add_instruments(self, *instruments): """ add instruments after initialization """ for instrument in instruments: if isinstance(instrument, ezibpy.utils.Contract): instrument = self.ibConn.contract_to_tuple(instrument) contractString = self.ibConn.contractString(instrument) self.instruments[contractString] = instrument self.ibConn.createContract(instrument) self.symbols = list(self.instruments.keys())
[ "def", "add_instruments", "(", "self", ",", "*", "instruments", ")", ":", "for", "instrument", "in", "instruments", ":", "if", "isinstance", "(", "instrument", ",", "ezibpy", ".", "utils", ".", "Contract", ")", ":", "instrument", "=", "self", ".", "ibConn"...
add instruments after initialization
[ "add", "instruments", "after", "initialization" ]
python
train
radjkarl/imgProcessor
imgProcessor/interpolate/polyfit2d.py
https://github.com/radjkarl/imgProcessor/blob/7c5a28718f81c01a430152c60a686ac50afbfd7c/imgProcessor/interpolate/polyfit2d.py#L8-L19
def polyfit2d(x, y, z, order=3 #bounds=None ): ''' fit unstructured data ''' ncols = (order + 1)**2 G = np.zeros((x.size, ncols)) ij = itertools.product(list(range(order+1)), list(range(order+1))) for k, (i,j) in enumerate(ij): G[:,k] = x**i * y**j m = np.linalg.lstsq(G, z)[0] return m
[ "def", "polyfit2d", "(", "x", ",", "y", ",", "z", ",", "order", "=", "3", "#bounds=None\r", ")", ":", "ncols", "=", "(", "order", "+", "1", ")", "**", "2", "G", "=", "np", ".", "zeros", "(", "(", "x", ".", "size", ",", "ncols", ")", ")", "i...
fit unstructured data
[ "fit", "unstructured", "data" ]
python
train
markuskiller/textblob-de
textblob_de/ext/_pattern/text/__init__.py
https://github.com/markuskiller/textblob-de/blob/1b427b2cdd7e5e9fd3697677a98358fae4aa6ad1/textblob_de/ext/_pattern/text/__init__.py#L1594-L1641
def tense_id(*args, **kwargs): """ Returns the tense id for a given (tense, person, number, mood, aspect, negated). Aliases and compound forms (e.g., IMPERFECT) are disambiguated. """ # Unpack tense given as a tuple, e.g., tense((PRESENT, 1, SG)): if len(args) == 1 and isinstance(args[0], (list, tuple)): if args[0] not in ((PRESENT, PARTICIPLE), (PAST, PARTICIPLE)): args = args[0] # No parameters defaults to tense=INFINITIVE, tense=PRESENT otherwise. if len(args) == 0 and len(kwargs) == 0: t = INFINITIVE else: t = PRESENT # Set default values. tense = kwargs.get("tense" , args[0] if len(args) > 0 else t) person = kwargs.get("person" , args[1] if len(args) > 1 else 3) or None number = kwargs.get("number" , args[2] if len(args) > 2 else SINGULAR) mood = kwargs.get("mood" , args[3] if len(args) > 3 else INDICATIVE) aspect = kwargs.get("aspect" , args[4] if len(args) > 4 else IMPERFECTIVE) negated = kwargs.get("negated", args[5] if len(args) > 5 else False) # Disambiguate wrong order of parameters. if mood in (PERFECTIVE, IMPERFECTIVE): mood, aspect = INDICATIVE, mood # Disambiguate INFINITIVE. # Disambiguate PARTICIPLE, IMPERFECT, PRETERITE. # These are often considered to be tenses but are in fact tense + aspect. if tense == INFINITIVE: person = number = mood = aspect = None; negated=False if tense in ((PRESENT, PARTICIPLE), PRESENT+PARTICIPLE, PARTICIPLE, GERUND): tense, aspect = PRESENT, PROGRESSIVE if tense in ((PAST, PARTICIPLE), PAST+PARTICIPLE): tense, aspect = PAST, PROGRESSIVE if tense == IMPERFECT: tense, aspect = PAST, IMPERFECTIVE if tense == PRETERITE: tense, aspect = PAST, PERFECTIVE if aspect in (CONTINUOUS, PARTICIPLE, GERUND): aspect = PROGRESSIVE if aspect == PROGRESSIVE: person = number = None # Disambiguate CONDITIONAL. # In Spanish, the conditional is regarded as an indicative tense. if tense == CONDITIONAL and mood == INDICATIVE: tense, mood = PRESENT, CONDITIONAL # Disambiguate aliases: "pl" => # (PRESENT, None, PLURAL, INDICATIVE, IMPERFECTIVE, False). return TENSES_ID.get(tense.lower(), TENSES_ID.get((tense, person, number, mood, aspect, negated)))
[ "def", "tense_id", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Unpack tense given as a tuple, e.g., tense((PRESENT, 1, SG)):", "if", "len", "(", "args", ")", "==", "1", "and", "isinstance", "(", "args", "[", "0", "]", ",", "(", "list", ",", "tu...
Returns the tense id for a given (tense, person, number, mood, aspect, negated). Aliases and compound forms (e.g., IMPERFECT) are disambiguated.
[ "Returns", "the", "tense", "id", "for", "a", "given", "(", "tense", "person", "number", "mood", "aspect", "negated", ")", ".", "Aliases", "and", "compound", "forms", "(", "e", ".", "g", ".", "IMPERFECT", ")", "are", "disambiguated", "." ]
python
train
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L189-L195
def peer_ips(peer_relation='cluster', addr_key='private-address'): '''Return a dict of peers and their private-address''' peers = {} for r_id in relation_ids(peer_relation): for unit in relation_list(r_id): peers[unit] = relation_get(addr_key, rid=r_id, unit=unit) return peers
[ "def", "peer_ips", "(", "peer_relation", "=", "'cluster'", ",", "addr_key", "=", "'private-address'", ")", ":", "peers", "=", "{", "}", "for", "r_id", "in", "relation_ids", "(", "peer_relation", ")", ":", "for", "unit", "in", "relation_list", "(", "r_id", ...
Return a dict of peers and their private-address
[ "Return", "a", "dict", "of", "peers", "and", "their", "private", "-", "address" ]
python
train
google/grr
grr/server/grr_response_server/aff4_objects/security.py
https://github.com/google/grr/blob/5cef4e8e2f0d5df43ea4877e9c798e0bf60bfe74/grr/server/grr_response_server/aff4_objects/security.py#L405-L408
def ApprovalSymlinkUrnBuilder(approval_type, subject_id, user, approval_id): """Build an approval symlink URN.""" return aff4.ROOT_URN.Add("users").Add(user).Add("approvals").Add( approval_type).Add(subject_id).Add(approval_id)
[ "def", "ApprovalSymlinkUrnBuilder", "(", "approval_type", ",", "subject_id", ",", "user", ",", "approval_id", ")", ":", "return", "aff4", ".", "ROOT_URN", ".", "Add", "(", "\"users\"", ")", ".", "Add", "(", "user", ")", ".", "Add", "(", "\"approvals\"", ")...
Build an approval symlink URN.
[ "Build", "an", "approval", "symlink", "URN", "." ]
python
train
raiden-network/raiden
raiden/transfer/views.py
https://github.com/raiden-network/raiden/blob/407ba15c72074e9de88771d6b9661ff4dc36bef5/raiden/transfer/views.py#L453-L465
def secret_from_transfer_task( transfer_task: Optional[TransferTask], secrethash: SecretHash, ) -> Optional[Secret]: """Return the secret for the transfer, None on EMPTY_SECRET.""" assert isinstance(transfer_task, InitiatorTask) transfer_state = transfer_task.manager_state.initiator_transfers[secrethash] if transfer_state is None: return None return transfer_state.transfer_description.secret
[ "def", "secret_from_transfer_task", "(", "transfer_task", ":", "Optional", "[", "TransferTask", "]", ",", "secrethash", ":", "SecretHash", ",", ")", "->", "Optional", "[", "Secret", "]", ":", "assert", "isinstance", "(", "transfer_task", ",", "InitiatorTask", ")...
Return the secret for the transfer, None on EMPTY_SECRET.
[ "Return", "the", "secret", "for", "the", "transfer", "None", "on", "EMPTY_SECRET", "." ]
python
train
daviddrysdale/python-phonenumbers
python/phonenumbers/phonenumberutil.py
https://github.com/daviddrysdale/python-phonenumbers/blob/9cc5bb4ab5e661e70789b4c64bf7a9383c7bdc20/python/phonenumbers/phonenumberutil.py#L3084-L3114
def is_number_match(num1, num2): """Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. num2 -- Second number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. Returns: - EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. - NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. - SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. - NO_MATCH otherwise. """ if isinstance(num1, PhoneNumber) and isinstance(num2, PhoneNumber): return _is_number_match_OO(num1, num2) elif isinstance(num1, PhoneNumber): return _is_number_match_OS(num1, num2) elif isinstance(num2, PhoneNumber): return _is_number_match_OS(num2, num1) else: return _is_number_match_SS(num1, num2)
[ "def", "is_number_match", "(", "num1", ",", "num2", ")", ":", "if", "isinstance", "(", "num1", ",", "PhoneNumber", ")", "and", "isinstance", "(", "num2", ",", "PhoneNumber", ")", ":", "return", "_is_number_match_OO", "(", "num1", ",", "num2", ")", "elif", ...
Takes two phone numbers and compares them for equality. For example, the numbers +1 345 657 1234 and 657 1234 are a SHORT_NSN_MATCH. The numbers +1 345 657 1234 and 345 657 are a NO_MATCH. Arguments num1 -- First number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. num2 -- Second number object or string to compare. Can contain formatting, and can have country calling code specified with + at the start. Returns: - EXACT_MATCH if the country_code, NSN, presence of a leading zero for Italian numbers and any extension present are the same. - NSN_MATCH if either or both has no region specified, and the NSNs and extensions are the same. - SHORT_NSN_MATCH if either or both has no region specified, or the region specified is the same, and one NSN could be a shorter version of the other number. This includes the case where one has an extension specified, and the other does not. - NO_MATCH otherwise.
[ "Takes", "two", "phone", "numbers", "and", "compares", "them", "for", "equality", "." ]
python
train
inasafe/inasafe
safe/utilities/settings.py
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/settings.py#L173-L207
def export_setting(file_path, qsettings=None): """Export InaSAFE's setting to a file. :param file_path: The file to write the exported setting. :type file_path: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: A dictionary of the exported settings. :rtype: dict """ inasafe_settings = {} if not qsettings: qsettings = QSettings() qsettings.beginGroup('inasafe') all_keys = qsettings.allKeys() qsettings.endGroup() for key in all_keys: inasafe_settings[key] = setting(key, qsettings=qsettings) def custom_default(obj): if obj is None or (hasattr(obj, 'isNull') and obj.isNull()): return '' raise TypeError with open(file_path, 'w') as json_file: json.dump( inasafe_settings, json_file, indent=2, default=custom_default) return inasafe_settings
[ "def", "export_setting", "(", "file_path", ",", "qsettings", "=", "None", ")", ":", "inasafe_settings", "=", "{", "}", "if", "not", "qsettings", ":", "qsettings", "=", "QSettings", "(", ")", "qsettings", ".", "beginGroup", "(", "'inasafe'", ")", "all_keys", ...
Export InaSAFE's setting to a file. :param file_path: The file to write the exported setting. :type file_path: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis.PyQt.QtCore.QSettings :returns: A dictionary of the exported settings. :rtype: dict
[ "Export", "InaSAFE", "s", "setting", "to", "a", "file", "." ]
python
train
mrallen1/pygett
pygett/base.py
https://github.com/mrallen1/pygett/blob/1e21f8674a3634a901af054226670174b5ce2d87/pygett/base.py#L115-L133
def get_share(self, sharename): """ Get a specific share. Does not require authentication. Input: * A sharename Output: * A :py:mod:`pygett.shares.GettShare` object Example:: share = client.get_share("4ddfds") """ response = GettRequest().get("/shares/%s" % sharename) if response.http_status == 200: return GettShare(self.user, **response.response)
[ "def", "get_share", "(", "self", ",", "sharename", ")", ":", "response", "=", "GettRequest", "(", ")", ".", "get", "(", "\"/shares/%s\"", "%", "sharename", ")", "if", "response", ".", "http_status", "==", "200", ":", "return", "GettShare", "(", "self", "...
Get a specific share. Does not require authentication. Input: * A sharename Output: * A :py:mod:`pygett.shares.GettShare` object Example:: share = client.get_share("4ddfds")
[ "Get", "a", "specific", "share", ".", "Does", "not", "require", "authentication", "." ]
python
train
basho/riak-python-client
riak/codecs/pbuf.py
https://github.com/basho/riak-python-client/blob/91de13a16607cdf553d1a194e762734e3bec4231/riak/codecs/pbuf.py#L372-L387
def encode_modfun(self, props, msg=None): """ Encodes a dict with 'mod' and 'fun' keys into a protobuf modfun pair. Used in bucket properties. :param props: the module/function pair :type props: dict :param msg: the protobuf message to fill :type msg: riak.pb.riak_pb2.RpbModFun :rtype riak.pb.riak_pb2.RpbModFun """ if msg is None: msg = riak.pb.riak_pb2.RpbModFun() msg.module = str_to_bytes(props['mod']) msg.function = str_to_bytes(props['fun']) return msg
[ "def", "encode_modfun", "(", "self", ",", "props", ",", "msg", "=", "None", ")", ":", "if", "msg", "is", "None", ":", "msg", "=", "riak", ".", "pb", ".", "riak_pb2", ".", "RpbModFun", "(", ")", "msg", ".", "module", "=", "str_to_bytes", "(", "props...
Encodes a dict with 'mod' and 'fun' keys into a protobuf modfun pair. Used in bucket properties. :param props: the module/function pair :type props: dict :param msg: the protobuf message to fill :type msg: riak.pb.riak_pb2.RpbModFun :rtype riak.pb.riak_pb2.RpbModFun
[ "Encodes", "a", "dict", "with", "mod", "and", "fun", "keys", "into", "a", "protobuf", "modfun", "pair", ".", "Used", "in", "bucket", "properties", "." ]
python
train
spacetelescope/stsci.imagestats
stsci/imagestats/histogram1d.py
https://github.com/spacetelescope/stsci.imagestats/blob/d7fc9fe9783f7ed3dc9e4af47acd357a5ccd68e3/stsci/imagestats/histogram1d.py#L55-L68
def _populateHistogram(self): """Call the C-code that actually populates the histogram""" try : buildHistogram.populate1DHist(self._data, self.histogram, self.minValue, self.maxValue, self.binWidth) except: if ((self._data.max() - self._data.min()) < self.binWidth): raise ValueError("In histogram1d class, the binWidth is " "greater than the data range of the array " "object.") else: raise SystemError("An error processing the array object " "information occured in the buildHistogram " "module of histogram1d.")
[ "def", "_populateHistogram", "(", "self", ")", ":", "try", ":", "buildHistogram", ".", "populate1DHist", "(", "self", ".", "_data", ",", "self", ".", "histogram", ",", "self", ".", "minValue", ",", "self", ".", "maxValue", ",", "self", ".", "binWidth", "...
Call the C-code that actually populates the histogram
[ "Call", "the", "C", "-", "code", "that", "actually", "populates", "the", "histogram" ]
python
train
jlmadurga/permabots
permabots/views/api/bot.py
https://github.com/jlmadurga/permabots/blob/781a91702529a23fe7bc2aa84c5d88e961412466/permabots/views/api/bot.py#L319-L328
def get(self, request, bot_id, id, format=None): """ Get MessengerBot by id --- serializer: MessengerBotSerializer responseMessages: - code: 401 message: Not authenticated """ return super(MessengerBotDetail, self).get(request, bot_id, id, format)
[ "def", "get", "(", "self", ",", "request", ",", "bot_id", ",", "id", ",", "format", "=", "None", ")", ":", "return", "super", "(", "MessengerBotDetail", ",", "self", ")", ".", "get", "(", "request", ",", "bot_id", ",", "id", ",", "format", ")" ]
Get MessengerBot by id --- serializer: MessengerBotSerializer responseMessages: - code: 401 message: Not authenticated
[ "Get", "MessengerBot", "by", "id", "---", "serializer", ":", "MessengerBotSerializer", "responseMessages", ":", "-", "code", ":", "401", "message", ":", "Not", "authenticated" ]
python
train
Clinical-Genomics/scout
scout/server/blueprints/cases/controllers.py
https://github.com/Clinical-Genomics/scout/blob/90a551e2e1653a319e654c2405c2866f93d0ebb9/scout/server/blueprints/cases/controllers.py#L413-L434
def rerun(store, mail, current_user, institute_id, case_name, sender, recipient): """Request a rerun by email.""" institute_obj, case_obj = institute_and_case(store, institute_id, case_name) user_obj = store.user(current_user.email) link = url_for('cases.case', institute_id=institute_id, case_name=case_name) store.request_rerun(institute_obj, case_obj, user_obj, link) # this should send a JSON document to the SuSy API in the future html = """ <p>{institute}: {case} ({case_id})</p> <p>Re-run requested by: {name}</p> """.format(institute=institute_obj['display_name'], case=case_obj['display_name'], case_id=case_obj['_id'], name=user_obj['name'].encode()) # compose and send the email message msg = Message(subject=("SCOUT: request RERUN for {}" .format(case_obj['display_name'])), html=html, sender=sender, recipients=[recipient], # cc the sender of the email for confirmation cc=[user_obj['email']]) mail.send(msg)
[ "def", "rerun", "(", "store", ",", "mail", ",", "current_user", ",", "institute_id", ",", "case_name", ",", "sender", ",", "recipient", ")", ":", "institute_obj", ",", "case_obj", "=", "institute_and_case", "(", "store", ",", "institute_id", ",", "case_name", ...
Request a rerun by email.
[ "Request", "a", "rerun", "by", "email", "." ]
python
test
JukeboxPipeline/jukebox-core
src/jukeboxcore/addons/configer/configer.py
https://github.com/JukeboxPipeline/jukebox-core/blob/bac2280ca49940355270e4b69400ce9976ab2e6f/src/jukeboxcore/addons/configer/configer.py#L186-L200
def doc_modified_prompt(self, ): """Create a message box, that asks the user to continue although files have been modified :returns: value of the standard button of qmessagebox that has been pressed. Either Yes or Cancel. :rtype: QtGui.QMessageBox.StandardButton :raises: None """ msgbox = QtGui.QMessageBox() msgbox.setWindowTitle("Discard changes?") msgbox.setText("Documents have been modified.") msgbox.setInformativeText("Do you really want to exit? Changes will be lost!") msgbox.setStandardButtons(msgbox.Yes | msgbox.Cancel) msgbox.setDefaultButton(msgbox.Cancel) msgbox.exec_() return msgbox.result()
[ "def", "doc_modified_prompt", "(", "self", ",", ")", ":", "msgbox", "=", "QtGui", ".", "QMessageBox", "(", ")", "msgbox", ".", "setWindowTitle", "(", "\"Discard changes?\"", ")", "msgbox", ".", "setText", "(", "\"Documents have been modified.\"", ")", "msgbox", ...
Create a message box, that asks the user to continue although files have been modified :returns: value of the standard button of qmessagebox that has been pressed. Either Yes or Cancel. :rtype: QtGui.QMessageBox.StandardButton :raises: None
[ "Create", "a", "message", "box", "that", "asks", "the", "user", "to", "continue", "although", "files", "have", "been", "modified" ]
python
train
adafruit/Adafruit_Python_MPR121
Adafruit_MPR121/MPR121.py
https://github.com/adafruit/Adafruit_Python_MPR121/blob/86360b80186617e0056d5bd5279bda000978d92c/Adafruit_MPR121/MPR121.py#L182-L188
def is_touched(self, pin): """Return True if the specified pin is being touched, otherwise returns False. """ assert pin >= 0 and pin < 12, 'pin must be between 0-11 (inclusive)' t = self.touched() return (t & (1 << pin)) > 0
[ "def", "is_touched", "(", "self", ",", "pin", ")", ":", "assert", "pin", ">=", "0", "and", "pin", "<", "12", ",", "'pin must be between 0-11 (inclusive)'", "t", "=", "self", ".", "touched", "(", ")", "return", "(", "t", "&", "(", "1", "<<", "pin", ")...
Return True if the specified pin is being touched, otherwise returns False.
[ "Return", "True", "if", "the", "specified", "pin", "is", "being", "touched", "otherwise", "returns", "False", "." ]
python
train
ARMmbed/mbed-cloud-sdk-python
scripts/generate_news.py
https://github.com/ARMmbed/mbed-cloud-sdk-python/blob/c0af86fb2cdd4dc7ed26f236139241067d293509/scripts/generate_news.py#L35-L61
def main(): """Writes out newsfile if significant version bump""" last_known = '0' if os.path.isfile(metafile): with open(metafile) as fh: last_known = fh.read() import mbed_cloud current = mbed_cloud.__version__ # how significant a change in version scheme should trigger a new changelog entry # (api major, api minor, sdk major, sdk minor, sdk patch) sigfigs = 4 current_version = LooseVersion(current).version last_known_version = LooseVersion(last_known).version should_towncrier = current_version[:sigfigs] != last_known_version[:sigfigs] print('%s -- %s :: current vs previous changelog build' % (current, last_known)) if should_towncrier: print('%s >> %s :: running changelog build' % (current, last_known)) subprocess.check_call( ['towncrier', '--yes'], cwd=os.path.join(PROJECT_ROOT, 'docs', 'changelog') ) with open(metafile, 'w') as fh: fh.write(current)
[ "def", "main", "(", ")", ":", "last_known", "=", "'0'", "if", "os", ".", "path", ".", "isfile", "(", "metafile", ")", ":", "with", "open", "(", "metafile", ")", "as", "fh", ":", "last_known", "=", "fh", ".", "read", "(", ")", "import", "mbed_cloud"...
Writes out newsfile if significant version bump
[ "Writes", "out", "newsfile", "if", "significant", "version", "bump" ]
python
train
Pylons/plaster
src/plaster/uri.py
https://github.com/Pylons/plaster/blob/e70e55c182a8300d7ccf67e54d47740c72e72cd8/src/plaster/uri.py#L59-L125
def parse_uri(config_uri): """ Parse the ``config_uri`` into a :class:`plaster.PlasterURL` object. ``config_uri`` can be a relative or absolute file path such as ``development.ini`` or ``/path/to/development.ini``. The file must have an extension that can be handled by a :class:`plaster.ILoader` registered with the system. Alternatively, ``config_uri`` may be a :rfc:`1738`-style string. """ if isinstance(config_uri, PlasterURL): return config_uri # force absolute paths to look like a uri for more accurate parsing # we throw away the dummy scheme later and parse it from the resolved # path extension isabs = os.path.isabs(config_uri) if isabs: config_uri = 'dummy://' + config_uri # check if the uri is actually a url parts = urlparse.urlparse(config_uri) # reconstruct the path without the scheme and fragment path = urlparse.ParseResult( scheme='', netloc=parts.netloc, path=parts.path, params='', query='', fragment='', ).geturl() # strip off leading // if path.startswith('//'): path = path[2:] if parts.scheme and not isabs: scheme = parts.scheme else: scheme = os.path.splitext(path)[1] if scheme.startswith('.'): scheme = scheme[1:] # tag uris coming from file extension as file+scheme if scheme: scheme = 'file+' + scheme query = parts.query if parts.query else None options = OrderedDict() if query: options.update(urlparse.parse_qsl(query)) fragment = parts.fragment if parts.fragment else None if not scheme: raise InvalidURI(config_uri, ( 'Could not determine the loader scheme for the supplied ' 'config_uri "{0}"'.format(config_uri))) return PlasterURL( scheme=scheme, path=path, options=options, fragment=fragment, )
[ "def", "parse_uri", "(", "config_uri", ")", ":", "if", "isinstance", "(", "config_uri", ",", "PlasterURL", ")", ":", "return", "config_uri", "# force absolute paths to look like a uri for more accurate parsing", "# we throw away the dummy scheme later and parse it from the resolved...
Parse the ``config_uri`` into a :class:`plaster.PlasterURL` object. ``config_uri`` can be a relative or absolute file path such as ``development.ini`` or ``/path/to/development.ini``. The file must have an extension that can be handled by a :class:`plaster.ILoader` registered with the system. Alternatively, ``config_uri`` may be a :rfc:`1738`-style string.
[ "Parse", "the", "config_uri", "into", "a", ":", "class", ":", "plaster", ".", "PlasterURL", "object", "." ]
python
train
apache/spark
python/pyspark/ml/param/__init__.py
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/ml/param/__init__.py#L467-L486
def _copyValues(self, to, extra=None): """ Copies param values from this instance to another instance for params shared by them. :param to: the target instance :param extra: extra params to be copied :return: the target instance with param values copied """ paramMap = self._paramMap.copy() if extra is not None: paramMap.update(extra) for param in self.params: # copy default params if param in self._defaultParamMap and to.hasParam(param.name): to._defaultParamMap[to.getParam(param.name)] = self._defaultParamMap[param] # copy explicitly set params if param in paramMap and to.hasParam(param.name): to._set(**{param.name: paramMap[param]}) return to
[ "def", "_copyValues", "(", "self", ",", "to", ",", "extra", "=", "None", ")", ":", "paramMap", "=", "self", ".", "_paramMap", ".", "copy", "(", ")", "if", "extra", "is", "not", "None", ":", "paramMap", ".", "update", "(", "extra", ")", "for", "para...
Copies param values from this instance to another instance for params shared by them. :param to: the target instance :param extra: extra params to be copied :return: the target instance with param values copied
[ "Copies", "param", "values", "from", "this", "instance", "to", "another", "instance", "for", "params", "shared", "by", "them", "." ]
python
train
CyberInt/dockermon
dockermon.py
https://github.com/CyberInt/dockermon/blob/a8733b9395cb1b551971f17c31d7f4a8268bb969/dockermon.py#L71-L106
def watch(callback, url=default_sock_url): """Watch docker events. Will call callback with each new event (dict). url can be either tcp://<host>:port or ipc://<path> """ sock, hostname = connect(url) request = 'GET /events HTTP/1.1\nHost: %s\n\n' % hostname request = request.encode('utf-8') with closing(sock): sock.sendall(request) header, payload = read_http_header(sock) status, reason = header_status(header) if status != HTTP_OK: raise DockermonError('bad HTTP status: %s %s' % (status, reason)) # Messages are \r\n<size in hex><JSON payload>\r\n buf = [payload] while True: chunk = sock.recv(bufsize) if not chunk: raise EOFError('socket closed') buf.append(chunk.decode('utf-8')) data = ''.join(buf) i = data.find('\r\n') if i == -1: continue size = int(data[:i], 16) start = i + 2 # Skip initial \r\n if len(data) < start + size + 2: continue payload = data[start:start+size] callback(json.loads(payload)) buf = [data[start+size+2:]]
[ "def", "watch", "(", "callback", ",", "url", "=", "default_sock_url", ")", ":", "sock", ",", "hostname", "=", "connect", "(", "url", ")", "request", "=", "'GET /events HTTP/1.1\\nHost: %s\\n\\n'", "%", "hostname", "request", "=", "request", ".", "encode", "(",...
Watch docker events. Will call callback with each new event (dict). url can be either tcp://<host>:port or ipc://<path>
[ "Watch", "docker", "events", ".", "Will", "call", "callback", "with", "each", "new", "event", "(", "dict", ")", "." ]
python
train
saltstack/salt
salt/modules/x509.py
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/x509.py#L1732-L1761
def verify_signature(certificate, signing_pub_key=None, signing_pub_key_passphrase=None): ''' Verify that ``certificate`` has been signed by ``signing_pub_key`` certificate: The certificate to verify. Can be a path or string containing a PEM formatted certificate. signing_pub_key: The public key to verify, can be a string or path to a PEM formatted certificate, csr, or private key. signing_pub_key_passphrase: Passphrase to the signing_pub_key if it is an encrypted private key. CLI Example: .. code-block:: bash salt '*' x509.verify_signature /etc/pki/mycert.pem \\ signing_pub_key=/etc/pki/myca.crt ''' cert = _get_certificate_obj(certificate) if signing_pub_key: signing_pub_key = get_public_key(signing_pub_key, passphrase=signing_pub_key_passphrase, asObj=True) return bool(cert.verify(pkey=signing_pub_key) == 1)
[ "def", "verify_signature", "(", "certificate", ",", "signing_pub_key", "=", "None", ",", "signing_pub_key_passphrase", "=", "None", ")", ":", "cert", "=", "_get_certificate_obj", "(", "certificate", ")", "if", "signing_pub_key", ":", "signing_pub_key", "=", "get_pub...
Verify that ``certificate`` has been signed by ``signing_pub_key`` certificate: The certificate to verify. Can be a path or string containing a PEM formatted certificate. signing_pub_key: The public key to verify, can be a string or path to a PEM formatted certificate, csr, or private key. signing_pub_key_passphrase: Passphrase to the signing_pub_key if it is an encrypted private key. CLI Example: .. code-block:: bash salt '*' x509.verify_signature /etc/pki/mycert.pem \\ signing_pub_key=/etc/pki/myca.crt
[ "Verify", "that", "certificate", "has", "been", "signed", "by", "signing_pub_key" ]
python
train
rvswift/EB
EB/builder/exhaustive/exhaustive.py
https://github.com/rvswift/EB/blob/341880b79faf8147dc9fa6e90438531cd09fabcc/EB/builder/exhaustive/exhaustive.py#L119-L132
def evaluate(molecules, ensemble_chunk, sort_order, options, output_queue=None): """ Evaluate VS performance of each ensemble in ensemble_chunk """ results = {} # {('receptor_1', ..., 'receptor_n') : ensemble storage object} for ensemble in ensemble_chunk: results[ensemble] = calculate_performance(molecules, ensemble, sort_order, options) if output_queue is not None: output_queue.put(results) else: return results
[ "def", "evaluate", "(", "molecules", ",", "ensemble_chunk", ",", "sort_order", ",", "options", ",", "output_queue", "=", "None", ")", ":", "results", "=", "{", "}", "# {('receptor_1', ..., 'receptor_n') : ensemble storage object}", "for", "ensemble", "in", "ensemble_c...
Evaluate VS performance of each ensemble in ensemble_chunk
[ "Evaluate", "VS", "performance", "of", "each", "ensemble", "in", "ensemble_chunk" ]
python
train
limodou/uliweb
uliweb/utils/common.py
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/common.py#L619-L627
def get_uuid(type=4): """ Get uuid value """ import uuid name = 'uuid'+str(type) u = getattr(uuid, name) return u().hex
[ "def", "get_uuid", "(", "type", "=", "4", ")", ":", "import", "uuid", "name", "=", "'uuid'", "+", "str", "(", "type", ")", "u", "=", "getattr", "(", "uuid", ",", "name", ")", "return", "u", "(", ")", ".", "hex" ]
Get uuid value
[ "Get", "uuid", "value" ]
python
train
morse-talk/morse-talk
morse_talk/encoding.py
https://github.com/morse-talk/morse-talk/blob/71e09ace0aa554d28cada5ee658e43758305b8fa/morse_talk/encoding.py#L128-L142
def _encode_to_binary_string(message, on, off): """ >>> message = "SOS" >>> _encode_to_binary_string(message, on='1', off='0') '101010001110111011100010101' >>> message = " SOS" >>> _encode_to_binary_string(message, on='1', off='0') '0000000101010001110111011100010101' """ def to_string(i, s): if i == 0 and s == off: return off * 4 return s return ''.join(to_string(i, s) for i, s in enumerate(_encode_binary(message, on=on, off=off)))
[ "def", "_encode_to_binary_string", "(", "message", ",", "on", ",", "off", ")", ":", "def", "to_string", "(", "i", ",", "s", ")", ":", "if", "i", "==", "0", "and", "s", "==", "off", ":", "return", "off", "*", "4", "return", "s", "return", "''", "....
>>> message = "SOS" >>> _encode_to_binary_string(message, on='1', off='0') '101010001110111011100010101' >>> message = " SOS" >>> _encode_to_binary_string(message, on='1', off='0') '0000000101010001110111011100010101'
[ ">>>", "message", "=", "SOS", ">>>", "_encode_to_binary_string", "(", "message", "on", "=", "1", "off", "=", "0", ")", "101010001110111011100010101" ]
python
train
python-gitlab/python-gitlab
gitlab/v4/objects.py
https://github.com/python-gitlab/python-gitlab/blob/16de1b03fde3dbbe8f851614dd1d8c09de102fe5/gitlab/v4/objects.py#L1819-L1841
def create(self, data, **kwargs): """Create a new object. Args: data (dict): parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo) Returns: RESTObject, RESTObject: The source and target issues Raises: GitlabAuthenticationError: If authentication is not correct GitlabCreateError: If the server cannot perform the request """ self._check_missing_create_attrs(data) server_data = self.gitlab.http_post(self.path, post_data=data, **kwargs) source_issue = ProjectIssue(self._parent.manager, server_data['source_issue']) target_issue = ProjectIssue(self._parent.manager, server_data['target_issue']) return source_issue, target_issue
[ "def", "create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_missing_create_attrs", "(", "data", ")", "server_data", "=", "self", ".", "gitlab", ".", "http_post", "(", "self", ".", "path", ",", "post_data", "=", "d...
Create a new object. Args: data (dict): parameters to send to the server to create the resource **kwargs: Extra options to send to the server (e.g. sudo) Returns: RESTObject, RESTObject: The source and target issues Raises: GitlabAuthenticationError: If authentication is not correct GitlabCreateError: If the server cannot perform the request
[ "Create", "a", "new", "object", "." ]
python
train
nvdv/vprof
vprof/memory_profiler.py
https://github.com/nvdv/vprof/blob/4c3ff78f8920ab10cb9c00b14143452aa09ff6bb/vprof/memory_profiler.py#L180-L186
def profile_function(self): """Returns memory stats for a function.""" target_modules = {self._run_object.__code__.co_filename} with _CodeEventsTracker(target_modules) as prof: prof.compute_mem_overhead() result = self._run_object(*self._run_args, **self._run_kwargs) return prof, result
[ "def", "profile_function", "(", "self", ")", ":", "target_modules", "=", "{", "self", ".", "_run_object", ".", "__code__", ".", "co_filename", "}", "with", "_CodeEventsTracker", "(", "target_modules", ")", "as", "prof", ":", "prof", ".", "compute_mem_overhead", ...
Returns memory stats for a function.
[ "Returns", "memory", "stats", "for", "a", "function", "." ]
python
test
Gandi/gandi.cli
gandi/cli/commands/webacc.py
https://github.com/Gandi/gandi.cli/blob/6ee5b8fc8ec44b0a6c232043ca610606ad8f693d/gandi/cli/commands/webacc.py#L215-L240
def delete(gandi, webacc, vhost, backend, port): """ Delete a webaccelerator, a vhost or a backend """ result = [] if webacc: result = gandi.webacc.delete(webacc) if backend: backends = backend for backend in backends: if 'port' not in backend: if not port: backend['port'] = click.prompt('Please set a port for ' 'backends. If you want to ' ' different port for ' 'each backend, use `-b ' 'ip:port`', type=int) else: backend['port'] = port result = gandi.webacc.backend_remove(backend) if vhost: vhosts = vhost for vhost in vhosts: result = gandi.webacc.vhost_remove(vhost) return result
[ "def", "delete", "(", "gandi", ",", "webacc", ",", "vhost", ",", "backend", ",", "port", ")", ":", "result", "=", "[", "]", "if", "webacc", ":", "result", "=", "gandi", ".", "webacc", ".", "delete", "(", "webacc", ")", "if", "backend", ":", "backen...
Delete a webaccelerator, a vhost or a backend
[ "Delete", "a", "webaccelerator", "a", "vhost", "or", "a", "backend" ]
python
train
ianmiell/shutit
shutit_class.py
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4412-L4435
def check_conflicts(self): """Checks for any conflicts between modules configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now consider conflicts self.log('PHASE: conflicts', level=logging.DEBUG) errs = [] self.pause_point('\nNow checking for conflicts between modules', print_input=False, level=3) for module_id in self.module_ids(): if not cfg[module_id]['shutit.core.module.build']: continue conflicter = self.shutit_map[module_id] for conflictee in conflicter.conflicts_with: # If the module id isn't there, there's no problem. conflictee_obj = self.shutit_map.get(conflictee) if conflictee_obj is None: continue if ((cfg[conflicter.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflicter)) and (cfg[conflictee_obj.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflictee_obj))): errs.append(('conflicter module id: ' + conflicter.module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj.module_id,)) return errs
[ "def", "check_conflicts", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# Now consider conflicts", "self", ".", "log", "(", "'PHASE: conflicts'", ",", "level", "=", "logging"...
Checks for any conflicts between modules configured to be built.
[ "Checks", "for", "any", "conflicts", "between", "modules", "configured", "to", "be", "built", "." ]
python
train
openfisca/openfisca-core
openfisca_core/simulations.py
https://github.com/openfisca/openfisca-core/blob/92ce9396e29ae5d9bac5ea604cfce88517c6b35c/openfisca_core/simulations.py#L94-L104
def data_storage_dir(self): """ Temporary folder used to store intermediate calculation data in case the memory is saturated """ if self._data_storage_dir is None: self._data_storage_dir = tempfile.mkdtemp(prefix = "openfisca_") log.warn(( "Intermediate results will be stored on disk in {} in case of memory overflow. " "You should remove this directory once you're done with your simulation." ).format(self._data_storage_dir)) return self._data_storage_dir
[ "def", "data_storage_dir", "(", "self", ")", ":", "if", "self", ".", "_data_storage_dir", "is", "None", ":", "self", ".", "_data_storage_dir", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "\"openfisca_\"", ")", "log", ".", "warn", "(", "(", "\"Inte...
Temporary folder used to store intermediate calculation data in case the memory is saturated
[ "Temporary", "folder", "used", "to", "store", "intermediate", "calculation", "data", "in", "case", "the", "memory", "is", "saturated" ]
python
train
MacHu-GWU/angora-project
angora/gadget/configuration.py
https://github.com/MacHu-GWU/angora-project/blob/689a60da51cd88680ddbe26e28dbe81e6b01d275/angora/gadget/configuration.py#L276-L287
def set_section(self, section): """Set a section. If section already exists, overwrite the old one. """ if not isinstance(section, Section): raise Exception("You") try: self.remove_section(section.name) except: pass self._sections[section.name] = copy.deepcopy(section)
[ "def", "set_section", "(", "self", ",", "section", ")", ":", "if", "not", "isinstance", "(", "section", ",", "Section", ")", ":", "raise", "Exception", "(", "\"You\"", ")", "try", ":", "self", ".", "remove_section", "(", "section", ".", "name", ")", "e...
Set a section. If section already exists, overwrite the old one.
[ "Set", "a", "section", ".", "If", "section", "already", "exists", "overwrite", "the", "old", "one", "." ]
python
train
LordSputnik/mutagen
mutagen/ogg.py
https://github.com/LordSputnik/mutagen/blob/38e62c8dc35c72b16554f5dbe7c0fde91acc3411/mutagen/ogg.py#L165-L177
def size(self): """Total frame size.""" header_size = 27 # Initial header size for datum in self.packets: quot, rem = divmod(len(datum), 255) header_size += quot + 1 if not self.complete and rem == 0: # Packet contains a multiple of 255 bytes and is not # terminated, so we don't have a \x00 at the end. header_size -= 1 header_size += sum(map(len, self.packets)) return header_size
[ "def", "size", "(", "self", ")", ":", "header_size", "=", "27", "# Initial header size", "for", "datum", "in", "self", ".", "packets", ":", "quot", ",", "rem", "=", "divmod", "(", "len", "(", "datum", ")", ",", "255", ")", "header_size", "+=", "quot", ...
Total frame size.
[ "Total", "frame", "size", "." ]
python
test
pettarin/ipapy
ipapy/ipachar.py
https://github.com/pettarin/ipapy/blob/ede4b3c40636f6eb90068369d31a2e75c7115324/ipapy/ipachar.py#L797-L805
def backness(self, value): """ Set the backness of the vowel. :param str value: the value to be set """ if (value is not None) and (not value in DG_V_BACKNESS): raise ValueError("Unrecognized value for backness: '%s'" % value) self.__backness = value
[ "def", "backness", "(", "self", ",", "value", ")", ":", "if", "(", "value", "is", "not", "None", ")", "and", "(", "not", "value", "in", "DG_V_BACKNESS", ")", ":", "raise", "ValueError", "(", "\"Unrecognized value for backness: '%s'\"", "%", "value", ")", "...
Set the backness of the vowel. :param str value: the value to be set
[ "Set", "the", "backness", "of", "the", "vowel", "." ]
python
train